



"""simple docstring"""
import argparse
from pathlib import Path

import fairseq
import torch
from fairseq.models.xmod import XMODModel as FairseqXmodModel
from packaging import version

from transformers import XmodConfig, XmodForMaskedLM, XmodForSequenceClassification
from transformers.utils import logging


if version.parse(fairseq.__version__) < version.parse("0.12.2"):
 raise Exception("requires fairseq >= 0.12.2")
if version.parse(fairseq.__version__) > version.parse("2"):
 raise Exception("requires fairseq < v2")

logging.set_verbosity_info()
_A													=   logging.get_logger(__name__)

_A													=   '''Hello, World!'''
_A													=   '''en_XX'''



def 			lowercase	(_snake_case ,_snake_case ,_snake_case			)       ->    str:




  '''simple docstring'''







  __UpperCamelCase  						=							Path("data_bin"			)
  __UpperCamelCase  						=							FairseqXmodModel.from_pretrained(
      model_name_or_path=str(Path(_lowerCAmelCase			).parent			) ,checkpoint_file=Path(_lowerCAmelCase			).name ,_name="xmod_base" ,arch="xmod_base" ,task="multilingual_masked_lm" ,data_name_or_path=str(_lowerCAmelCase			) ,bpe="sentencepiece" ,sentencepiece_model=str(Path(_lowerCAmelCase			).parent / "sentencepiece.bpe.model"			) ,src_dict=str(data_dir / "dict.txt"			) ,)
  xmod.eval()  # disable dropout
  print(_lowerCAmelCase			)

  __UpperCamelCase  						=							xmod.model.encoder.sentence_encoder
  __UpperCamelCase  						=							XmodConfig(
      vocab_size=xmod_sent_encoder.embed_tokens.num_embeddings ,hidden_size=xmod.cfg.model.encoder_embed_dim ,num_hidden_layers=xmod.cfg.model.encoder_layers ,num_attention_heads=xmod.cfg.model.encoder_attention_heads ,intermediate_size=xmod.cfg.model.encoder_ffn_embed_dim ,max_position_embeddings=514 ,type_vocab_size=1 ,layer_norm_eps=1e-5 ,pre_norm=xmod.cfg.model.encoder_normalize_before ,adapter_reduction_factor=getattr(xmod.cfg.model ,"bottleneck" ,2			) ,adapter_layer_norm=xmod.cfg.model.adapter_layer_norm ,adapter_reuse_layer_norm=xmod.cfg.model.adapter_reuse_layer_norm ,ln_before_adapter=xmod.cfg.model.ln_before_adapter ,languages=xmod.cfg.model.languages ,)
  if classification_head:
    __UpperCamelCase  						=							xmod.model.classification_heads["mnli"].out_proj.weight.shape[0]

  print("Our X-MOD config:" ,_lowerCAmelCase			)

  __UpperCamelCase  						=							XmodForSequenceClassification(_lowerCAmelCase			) if classification_head else XmodForMaskedLM(_lowerCAmelCase			)
  model.eval()

  # Now let's copy all the weights.
  # Embeddings
  __UpperCamelCase  						=							xmod_sent_encoder.embed_tokens.weight
  __UpperCamelCase  						=							xmod_sent_encoder.embed_positions.weight
  __UpperCamelCase  						=							torch.zeros_like(
      model.roberta.embeddings.token_type_embeddings.weight			)  # just zero them out b/c xmod doesn't use them.

  __UpperCamelCase  						=							xmod_sent_encoder.layernorm_embedding.weight
  __UpperCamelCase  						=							xmod_sent_encoder.layernorm_embedding.bias

  for i in range(config.num_hidden_layers			):
    # Encoder: start of layer
    __UpperCamelCase  						=							model.roberta.encoder.layer[i]
    __UpperCamelCase  						=							xmod_sent_encoder.layers[i]

    # self attention
    __UpperCamelCase  						=							layer.attention.self
    if not (
        xmod_layer.self_attn.k_proj.weight.data.shape
        == xmod_layer.self_attn.q_proj.weight.data.shape
        == xmod_layer.self_attn.v_proj.weight.data.shape
        == torch.Size((config.hidden_size, config.hidden_size)			)
    ):
      raise AssertionError("Dimensions of self-attention weights do not match."			)

    __UpperCamelCase  						=							xmod_layer.self_attn.q_proj.weight
    __UpperCamelCase  						=							xmod_layer.self_attn.q_proj.bias
    __UpperCamelCase  						=							xmod_layer.self_attn.k_proj.weight
    __UpperCamelCase  						=							xmod_layer.self_attn.k_proj.bias
    __UpperCamelCase  						=							xmod_layer.self_attn.v_proj.weight
    __UpperCamelCase  						=							xmod_layer.self_attn.v_proj.bias

    # self-attention output
    __UpperCamelCase  						=							layer.attention.output
    if self_output.dense.weight.shape != xmod_layer.self_attn.out_proj.weight.shape:
      raise AssertionError("Dimensions of self-attention output weights do not match."			)
    __UpperCamelCase  						=							xmod_layer.self_attn.out_proj.weight
    __UpperCamelCase  						=							xmod_layer.self_attn.out_proj.bias
    __UpperCamelCase  						=							xmod_layer.self_attn_layer_norm.weight
    __UpperCamelCase  						=							xmod_layer.self_attn_layer_norm.bias

    # intermediate
    __UpperCamelCase  						=							layer.intermediate
    if intermediate.dense.weight.shape != xmod_layer.fca.weight.shape:
      raise AssertionError("Dimensions of intermediate weights do not match."			)
    __UpperCamelCase  						=							xmod_layer.fca.weight
    __UpperCamelCase  						=							xmod_layer.fca.bias

    # output
    __UpperCamelCase  						=							layer.output
    if bert_output.dense.weight.shape != xmod_layer.fca.weight.shape:
      raise AssertionError("Dimensions of feed-forward weights do not match."			)
    __UpperCamelCase  						=							xmod_layer.fca.weight
    __UpperCamelCase  						=							xmod_layer.fca.bias
    __UpperCamelCase  						=							xmod_layer.final_layer_norm.weight
    __UpperCamelCase  						=							xmod_layer.final_layer_norm.bias
    if bert_output.adapter_layer_norm is not None:
      __UpperCamelCase  						=							xmod_layer.adapter_layer_norm.weight
      __UpperCamelCase  						=							xmod_layer.adapter_layer_norm.bias

    if sorted(bert_output.adapter_modules.keys()			) != sorted(xmod_layer.adapter_modules.keys()			):
      raise AssertionError("Lists of language adapters do not match."			)
    for lang_code, adapter in xmod_layer.adapter_modules.items():
      __UpperCamelCase  						=							bert_output.adapter_modules[lang_code]
      __UpperCamelCase  						=							xmod_layer.adapter_modules[lang_code]
      __UpperCamelCase  						=							from_adapter.fca.weight
      __UpperCamelCase  						=							from_adapter.fca.bias
      __UpperCamelCase  						=							from_adapter.fca.weight
      __UpperCamelCase  						=							from_adapter.fca.bias

    # end of layer

  if xmod_sent_encoder.layer_norm is not None:
    __UpperCamelCase  						=							xmod_sent_encoder.layer_norm.weight
    __UpperCamelCase  						=							xmod_sent_encoder.layer_norm.bias

  if classification_head:
    __UpperCamelCase  						=							xmod.model.classification_heads["mnli"].dense.weight
    __UpperCamelCase  						=							xmod.model.classification_heads["mnli"].dense.bias
    __UpperCamelCase  						=							xmod.model.classification_heads["mnli"].out_proj.weight
    __UpperCamelCase  						=							xmod.model.classification_heads["mnli"].out_proj.bias
  else:
    # LM Head
    __UpperCamelCase  						=							xmod.model.encoder.lm_head.dense.weight
    __UpperCamelCase  						=							xmod.model.encoder.lm_head.dense.bias
    __UpperCamelCase  						=							xmod.model.encoder.lm_head.layer_norm.weight
    __UpperCamelCase  						=							xmod.model.encoder.lm_head.layer_norm.bias
    __UpperCamelCase  						=							xmod.model.encoder.lm_head.weight
    __UpperCamelCase  						=							xmod.model.encoder.lm_head.bias

  # Let's check that we get the same results.
  __UpperCamelCase  						=							xmod.encode(_lowerCAmelCase			).unsqueeze(0			)  # batch of size 1
  model.roberta.set_default_language(_lowerCAmelCase			)

  __UpperCamelCase  						=							model(_lowerCAmelCase			)[0]
  if classification_head:
    __UpperCamelCase  						=							xmod.model.classification_heads["mnli"](xmod.extract_features(_lowerCAmelCase			)			)
  else:
    __UpperCamelCase  						=							xmod.model(_lowerCAmelCase ,lang_id=[SAMPLE_LANGUAGE]			)[0]
  print(our_output.shape ,their_output.shape			)
  __UpperCamelCase  						=							torch.max(torch.abs(our_output - their_output			)			).item()
  print(f"""max_absolute_diff = {max_absolute_diff}"""			)  # ~ 1e-7
  __UpperCamelCase  						=							torch.allclose(_lowerCAmelCase ,_lowerCAmelCase ,atol=1e-3			)
  print("Do both models output the same tensors?" ,"🔥" if success else "💩"			)
  if not success:
    raise Exception("Something went wRoNg"			)

  Path(_lowerCAmelCase			).mkdir(parents=_lowerCAmelCase ,exist_ok=_lowerCAmelCase			)
  print(f"""Saving model to {pytorch_dump_folder_path}"""			)
  model.save_pretrained(_lowerCAmelCase			)


if __name__ == "__main__":
 _A													=   argparse.ArgumentParser()
 # Required parameters
 parser.add_argument(
     "--xmod_checkpoint_path", default=None, type=str, required=True, help="Path the official PyTorch dump."
 )
 parser.add_argument(
     "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
 )
 parser.add_argument(
     "--classification_head", action="store_true", help="Whether to convert a final classification head."
 )
 _A													=   parser.parse_args()
 convert_xmod_checkpoint_to_pytorch(
     args.xmod_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head
 )






from __future__ import annotations

import math
import random
from typing import Any


class        __magic_name__	:





     """simple docstring"""



     def __init__(				self							:Tuple	):





        '''simple docstring'''




        A_       :					list[Any]        =      []
        A_       :					int        =      0
        A_       :					int        =      0



     def     SCREAMING_SNAKE_CASE		(				self							:List[Any]	):





        '''simple docstring'''




        return self.head == self.tail



     def     SCREAMING_SNAKE_CASE		(				self							:Optional[Any]      ,   snake_case							:Any	):





        '''simple docstring'''




        self.data.append(snake_case	)
        A_       :					int        =      self.tail + 1



     def     SCREAMING_SNAKE_CASE		(				self							:str	):





        '''simple docstring'''




        A_       :					int        =      self.data[self.head]
        A_       :					Tuple        =      self.head + 1
        return ret



     def     SCREAMING_SNAKE_CASE		(				self							:Optional[int]	):





        '''simple docstring'''




        return self.tail - self.head





     def     SCREAMING_SNAKE_CASE		(				self							:Any	):





        '''simple docstring'''




        print(self.data	)
        print("**************"	)
        print(self.data[self.head : self.tail]	)




class        __magic_name__	:





     """simple docstring"""



     def __init__(				self							:Any      ,   snake_case							:Any	):





        '''simple docstring'''




        A_       :					Any        =      data
        A_       :					MyNode | None        =      None
        A_       :					MyNode | None        =      None
        A_       :					int        =      1



     def     SCREAMING_SNAKE_CASE		(				self							:List[str]	):





        '''simple docstring'''




        return self.data



     def     SCREAMING_SNAKE_CASE		(				self							:Dict	):





        '''simple docstring'''




        return self.left



     def     SCREAMING_SNAKE_CASE		(				self							:Any	):





        '''simple docstring'''




        return self.right



     def     SCREAMING_SNAKE_CASE		(				self							:List[Any]	):





        '''simple docstring'''




        return self.height



     def     SCREAMING_SNAKE_CASE		(				self							:List[str]      ,   snake_case							:Any	):





        '''simple docstring'''




        A_       :					Optional[int]        =      data



     def     SCREAMING_SNAKE_CASE		(				self							:Optional[int]      ,   snake_case							:MyNode | None	):





        '''simple docstring'''




        A_       :					Tuple        =      node



     def     SCREAMING_SNAKE_CASE		(				self							:str      ,   snake_case							:MyNode | None	):





        '''simple docstring'''




        A_       :					str        =      node





     def     SCREAMING_SNAKE_CASE		(				self							:Tuple      ,   snake_case							:int	):





        '''simple docstring'''




        A_       :					Optional[int]        =      height




def   __snake_case    (       _lowerCAmelCase			:			MyNode | None						)			->    int:
   if node is None:
      return 0
   return node.get_height()

def   __snake_case    (       _lowerCAmelCase			:			int					,					_lowerCAmelCase			:			int						)			->    int:
   if a > b:
      return a
   return b

def   __snake_case    (       _lowerCAmelCase			:			MyNode						)			->    MyNode:
   print("left rotation node:"					,					node.get_data()						)
   A_       :					Optional[int]        =      node.get_left()
   assert ret is not None
   node.set_left(ret.get_right()						)
   ret.set_right(_lowerCAmelCase						)
   A_       :					Any        =      my_max(get_height(node.get_right()						)					,					get_height(node.get_left()						)						) + 1
   node.set_height(_lowerCAmelCase						)
   A_       :					List[str]        =      my_max(get_height(ret.get_right()						)					,					get_height(ret.get_left()						)						) + 1
   ret.set_height(_lowerCAmelCase						)
   return ret

def   __snake_case    (       _lowerCAmelCase			:			MyNode						)			->    MyNode:
   print("right rotation node:"					,					node.get_data()						)
   A_       :					Union[str, Any]        =      node.get_right()
   assert ret is not None
   node.set_right(ret.get_left()						)
   ret.set_left(_lowerCAmelCase						)
   A_       :					int        =      my_max(get_height(node.get_right()						)					,					get_height(node.get_left()						)						) + 1
   node.set_height(_lowerCAmelCase						)
   A_       :					Dict        =      my_max(get_height(ret.get_right()						)					,					get_height(ret.get_left()						)						) + 1
   ret.set_height(_lowerCAmelCase						)
   return ret

def   __snake_case    (       _lowerCAmelCase			:			MyNode						)			->    MyNode:
   A_       :					List[Any]        =      node.get_left()
   assert left_child is not None
   node.set_left(left_rotation(_lowerCAmelCase						)						)
   return right_rotation(_lowerCAmelCase						)

def   __snake_case    (       _lowerCAmelCase			:			MyNode						)			->    MyNode:
   A_       :					List[Any]        =      node.get_right()
   assert right_child is not None
   node.set_right(right_rotation(_lowerCAmelCase						)						)
   return left_rotation(_lowerCAmelCase						)

def   __snake_case    (       _lowerCAmelCase			:			MyNode | None					,					_lowerCAmelCase			:			Any						)			->    MyNode | None:
   if node is None:
      return MyNode(_lowerCAmelCase						)
   if data < node.get_data():
      node.set_left(insert_node(node.get_left()					,					_lowerCAmelCase						)						)
      if (
          get_height(node.get_left()						) - get_height(node.get_right()						) == 2
      ):  # an unbalance detected
         A_       :					Any        =      node.get_left()
         assert left_child is not None
         if (
             data < left_child.get_data()
         ):  # new node is the left child of the left child
            A_       :					Optional[int]        =      right_rotation(_lowerCAmelCase						)
         else:
            A_       :					int        =      lr_rotation(_lowerCAmelCase						)
   else:
      node.set_right(insert_node(node.get_right()					,					_lowerCAmelCase						)						)
      if get_height(node.get_right()						) - get_height(node.get_left()						) == 2:
         A_       :					Dict        =      node.get_right()
         assert right_child is not None
         if data < right_child.get_data():
            A_       :					Optional[Any]        =      rl_rotation(_lowerCAmelCase						)
         else:
            A_       :					Dict        =      left_rotation(_lowerCAmelCase						)
   A_       :					Optional[int]        =      my_max(get_height(node.get_right()						)					,					get_height(node.get_left()						)						) + 1
   node.set_height(_lowerCAmelCase						)
   return node

def   __snake_case    (       _lowerCAmelCase			:			MyNode						)			->    Any:
   while True:
      A_       :					Any        =      root.get_right()
      if right_child is None:
         break
      A_       :					Optional[Any]        =      right_child
   return root.get_data()

def   __snake_case    (       _lowerCAmelCase			:			MyNode						)			->    Any:
   while True:
      A_       :					Optional[Any]        =      root.get_left()
      if left_child is None:
         break
      A_       :					int        =      left_child
   return root.get_data()

def   __snake_case    (       _lowerCAmelCase			:			MyNode					,					_lowerCAmelCase			:			Any						)			->    MyNode | None:
   A_       :					Optional[int]        =      root.get_left()
   A_       :					Dict        =      root.get_right()
   if root.get_data() == data:
      if left_child is not None and right_child is not None:
         A_       :					int        =      get_left_most(_lowerCAmelCase						)
         root.set_data(_lowerCAmelCase						)
         root.set_right(del_node(_lowerCAmelCase					,					_lowerCAmelCase						)						)
      elif left_child is not None:
         A_       :					Tuple        =      left_child
      elif right_child is not None:
         A_       :					Any        =      right_child
      else:
         return None
   elif root.get_data() > data:
      if left_child is None:
         print("No such data"						)
         return root
      else:
         root.set_left(del_node(_lowerCAmelCase					,					_lowerCAmelCase						)						)
   else:  # root.get_data() < data
      if right_child is None:
         return root
      else:
         root.set_right(del_node(_lowerCAmelCase					,					_lowerCAmelCase						)						)

   if get_height(_lowerCAmelCase						) - get_height(_lowerCAmelCase						) == 2:
      assert right_child is not None
      if get_height(right_child.get_right()						) > get_height(right_child.get_left()						):
         A_       :					Dict        =      left_rotation(_lowerCAmelCase						)
      else:
         A_       :					List[Any]        =      rl_rotation(_lowerCAmelCase						)
   elif get_height(_lowerCAmelCase						) - get_height(_lowerCAmelCase						) == -2:
      assert left_child is not None
      if get_height(left_child.get_left()						) > get_height(left_child.get_right()						):
         A_       :					Optional[Any]        =      right_rotation(_lowerCAmelCase						)
      else:
         A_       :					Tuple        =      lr_rotation(_lowerCAmelCase						)
   A_       :					List[str]        =      my_max(get_height(root.get_right()						)					,					get_height(root.get_left()						)						) + 1
   root.set_height(_lowerCAmelCase						)
   return root


class        __magic_name__	:





     """simple docstring"""



     def __init__(				self							:List[str]	):





        '''simple docstring'''




        A_       :					MyNode | None        =      None



     def     SCREAMING_SNAKE_CASE		(				self							:List[Any]	):





        '''simple docstring'''




        return get_height(self.root	)



     def     SCREAMING_SNAKE_CASE		(				self							:str      ,   snake_case							:Any	):





        '''simple docstring'''




        print("insert:" + str(snake_case	)	)
        A_       :					List[Any]        =      insert_node(self.root      ,   snake_case	)



     def     SCREAMING_SNAKE_CASE		(				self							:Optional[Any]      ,   snake_case							:Any	):





        '''simple docstring'''




        print("delete:" + str(snake_case	)	)
        if self.root is None:
           print("Tree is empty!"	)
           return
        A_       :					Dict        =      del_node(self.root      ,   snake_case	)





     def __str__(				self							:Optional[int]      ,   ):  # a level traversale, gives a more intuitive look on the tree





        '''simple docstring'''




        A_       :					Optional[Any]        =      ""
        A_       :					Optional[int]        =      MyQueue()
        q.push(self.root	)
        A_       :					Optional[int]        =      self.get_height()
        if layer == 0:
           return output
        A_       :					Dict        =      0
        while not q.is_empty():
           A_       :					Optional[int]        =      q.pop()
           A_       :					Union[str, Any]        =      " " * int(math.pow(2      ,   layer - 1	)	)
           output += space
           if node is None:
              output += "*"
              q.push(snake_case	)
              q.push(snake_case	)
           else:
              output += str(node.get_data()	)
              q.push(node.get_left()	)
              q.push(node.get_right()	)
           output += space
           A_       :					str        =      cnt + 1
           for i in range(100	):
              if cnt == math.pow(2      ,   snake_case	) - 1:
                 A_       :					int        =      layer - 1
                 if layer == 0:
                    output += "\n*************************************"
                    return output
                 output += "\n"
                 break
        output += "\n*************************************"
        return output




def   __snake_case    (       )			->    None:
   import doctest

   doctest.testmod()


if __name__ == "__main__":
 _test()
 _lowerCAmelCase				:   int						       =						AVLtree()
 _lowerCAmelCase				:   Optional[int]						       =						list(range(10))
 random.shuffle(lst)
 for i in lst:
  t.insert(i)
  print(str(t))
 random.shuffle(lst)
 for i in lst:
  t.del_node(i)
  print(str(t))
