






import asyncio
import os
import re
import sys
import tempfile
import unittest
from contextlib import contextmanager
from copy import deepcopy
from distutils.util import strtobool
from enum import Enum
from importlib.util import find_spec
from pathlib import Path
from unittest.mock import patch

import pyarrow as pa
import pytest
import requests
from packaging import version

from datasets import config


if config.PY_VERSION < version.parse("3.8"):
							import importlib_metadata
else:
							import importlib.metadata as importlib_metadata




def 				A		(					lowercase__  :  int ,		lowercase__  :  Union[str, Any]=False  )		-> Dict:
	try:
		UpperCamelCase__ :str						=      os.environ[key]
	except KeyError:
		# KEY isn't set, default to `default`.
		UpperCamelCase__ :Dict						=      default
	else:
		# KEY is set, convert it to True or False.
		try:
			UpperCamelCase__ :Any						=      strtobool(lowercase__  )
		except ValueError:
			# More values are supported, but let's keep the message simple.
			raise ValueError(f"""If set, {key} must be yes or no."""  )
	return _value


UpperCamelCase        =				parse_flag_from_env("RUN_SLOW", default=False)
UpperCamelCase        =				parse_flag_from_env("RUN_REMOTE", default=False)
UpperCamelCase        =				parse_flag_from_env("RUN_LOCAL", default=True)
UpperCamelCase        =				parse_flag_from_env("RUN_PACKAGED", default=True)

# Compression
UpperCamelCase        =				pytest.mark.skipif(not config.LZ4_AVAILABLE, reason="test requires lz4")
UpperCamelCase        =				pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason="test requires py7zr")
UpperCamelCase        =				pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason="test requires zstandard")

# Audio
UpperCamelCase        =				pytest.mark.skipif(
    # On Windows and OS X, soundfile installs sndfile
    find_spec("soundfile") is None or version.parse(importlib_metadata.version("soundfile")) < version.parse("0.12.0"),
    reason="test requires sndfile>=0.12.1: 'pip install \"soundfile>=0.12.1\"'; ",
)

# Beam
UpperCamelCase        =				pytest.mark.skipif(
    not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse("0.3.2"),
    reason="test requires apache-beam and a compatible dill version",
)

# Dill-cloudpickle compatibility
UpperCamelCase        =				pytest.mark.skipif(
    config.DILL_VERSION <= version.parse("0.3.2"),
    reason="test requires dill>0.3.2 for cloudpickle compatibility",
)

# Windows
UpperCamelCase        =				pytest.mark.skipif(
    sys.platform == "win32",
    reason="test should not be run on Windows",
)




def 				A		(					lowercase__  :  Any  )		-> List[Any]:
	try:
		import faiss  # noqa
	except ImportError:
		UpperCamelCase__ :Optional[Any]						=      unittest.skip("""test requires faiss"""  )(lowercase__  )
	return test_case




def 				A		(					lowercase__  :  List[str]  )		-> List[str]:
	try:
		import regex  # noqa
	except ImportError:
		UpperCamelCase__ :List[str]						=      unittest.skip("""test requires regex"""  )(lowercase__  )
	return test_case




def 				A		(					lowercase__  :  int  )		-> List[str]:
	try:
		import elasticsearch  # noqa
	except ImportError:
		UpperCamelCase__ :Tuple						=      unittest.skip("""test requires elasticsearch"""  )(lowercase__  )
	return test_case




def 				A		(					lowercase__  :  Dict  )		-> str:
	try:
		import sqlalchemy  # noqa
	except ImportError:
		UpperCamelCase__ :str						=      unittest.skip("""test requires sqlalchemy"""  )(lowercase__  )
	return test_case




def 				A		(					lowercase__  :  List[str]  )		-> List[str]:
	if not config.TORCH_AVAILABLE:
		UpperCamelCase__ :Tuple						=      unittest.skip("""test requires PyTorch"""  )(lowercase__  )
	return test_case




def 				A		(					lowercase__  :  Dict  )		-> Union[str, Any]:
	if not config.TF_AVAILABLE:
		UpperCamelCase__ :List[str]						=      unittest.skip("""test requires TensorFlow"""  )(lowercase__  )
	return test_case




def 				A		(					lowercase__  :  Tuple  )		-> Optional[int]:
	if not config.JAX_AVAILABLE:
		UpperCamelCase__ :str						=      unittest.skip("""test requires JAX"""  )(lowercase__  )
	return test_case




def 				A		(					lowercase__  :  List[Any]  )		-> Optional[Any]:
	if not config.PIL_AVAILABLE:
		UpperCamelCase__ :Optional[int]						=      unittest.skip("""test requires Pillow"""  )(lowercase__  )
	return test_case




def 				A		(					lowercase__  :  Any  )		-> Any:
	try:
		import transformers  # noqa F401
	except ImportError:
		return unittest.skip("""test requires transformers"""  )(lowercase__  )
	else:
		return test_case




def 				A		(					lowercase__  :  Union[str, Any]  )		-> Any:
	try:
		import tiktoken  # noqa F401
	except ImportError:
		return unittest.skip("""test requires tiktoken"""  )(lowercase__  )
	else:
		return test_case




def 				A		(					lowercase__  :  Optional[Any]  )		-> Union[str, Any]:
	try:
		import spacy  # noqa F401
	except ImportError:
		return unittest.skip("""test requires spacy"""  )(lowercase__  )
	else:
		return test_case




def 				A		(					lowercase__  :  Optional[Any]  )		-> str:

	def _require_spacy_model(lowercase__  :  Tuple  ):
		try:
			import spacy  # noqa F401

			spacy.load(lowercase__  )
		except ImportError:
			return unittest.skip("""test requires spacy"""  )(lowercase__  )
		except OSError:
			return unittest.skip("""test requires spacy model '{}'""".format(lowercase__  )  )(lowercase__  )
		else:
			return test_case

	return _require_spacy_model




def 				A		(					lowercase__  :  int  )		-> List[str]:
	try:
		import pyspark  # noqa F401
	except ImportError:
		return unittest.skip("""test requires pyspark"""  )(lowercase__  )
	else:
		return test_case




def 				A		(					lowercase__  :  Dict  )		-> List[str]:
	try:
		import joblibspark  # noqa F401
	except ImportError:
		return unittest.skip("""test requires joblibspark"""  )(lowercase__  )
	else:
		return test_case




def 				A		(					lowercase__  :  List[str]  )		-> Dict:
	if not _run_slow_tests or _run_slow_tests == 0:
		UpperCamelCase__ :Optional[int]						=      unittest.skip("""test is slow"""  )(lowercase__  )
	return test_case




def 				A		(					lowercase__  :  Optional[Any]  )		-> int:
	if not _run_local_tests or _run_local_tests == 0:
		UpperCamelCase__ :Dict						=      unittest.skip("""test is local"""  )(lowercase__  )
	return test_case




def 				A		(					lowercase__  :  Optional[Any]  )		-> List[Any]:
	if not _run_packaged_tests or _run_packaged_tests == 0:
		UpperCamelCase__ :str						=      unittest.skip("""test is packaged"""  )(lowercase__  )
	return test_case




def 				A		(					lowercase__  :  int  )		-> List[Any]:
	if not _run_remote_tests or _run_remote_tests == 0:
		UpperCamelCase__ :List[Any]						=      unittest.skip("""test requires remote"""  )(lowercase__  )
	return test_case




def 				A		(					*lowercase__  :  List[Any]  )		-> str:
	def decorate(cls  :  Optional[Any]  ):
		for name, fn in cls.__dict__.items():
			if callable(lowercase__  ) and name.startswith("""test"""  ):
				for decorator in decorators:
					UpperCamelCase__ :Any						=      decorator(lowercase__  )
				setattr(cls ,		lowercase__ ,		lowercase__  )
		return cls

	return decorate

class        lowerCAmelCase_				(      lowercase	):







				"""simple docstring"""




				pass

class        lowerCAmelCase_				(      lowercase	):







				"""simple docstring"""




				_snake_case				:   Tuple        =			0
				_snake_case				:   Any        =			1
				_snake_case				:   Union[str, Any]        =			2




@contextmanager
def 				A		(					lowercase__  :  Dict=OfflineSimulationMode.CONNECTION_FAILS ,		lowercase__  :  Tuple=1E-16  )		-> Union[str, Any]:
	UpperCamelCase__ :List[str]						=      requests.Session().request

	def timeout_request(lowercase__  :  str ,		lowercase__  :  Union[str, Any] ,		lowercase__  :  Optional[int] ,		**lowercase__  :  int  ):
		# Change the url to an invalid url so that the connection hangs
		UpperCamelCase__ :Dict						=      """https://10.255.255.1"""
		if kwargs.get("""timeout"""  ) is None:
			raise RequestWouldHangIndefinitelyError(
			    f"""Tried a call to {url} in offline mode with no timeout set. Please set a timeout."""  )
		UpperCamelCase__ :List[str]						=      timeout
		try:
			return online_request(lowercase__ ,		lowercase__ ,		**lowercase__  )
		except Exception as e:
			# The following changes in the error are just here to make the offline timeout error prettier
			UpperCamelCase__ :Optional[int]						=      url
			UpperCamelCase__ :Union[str, Any]						=      e.args[0]
			UpperCamelCase__ :List[Any]						=      (max_retry_error.args[0].replace("""10.255.255.1""" ,		f"""OfflineMock[{url}]"""  ),)
			UpperCamelCase__ :Optional[Any]						=      (max_retry_error,)
			raise

	def raise_connection_error(lowercase__  :  Union[str, Any] ,		lowercase__  :  Tuple ,		**lowercase__  :  Any  ):
		raise requests.ConnectionError("""Offline mode is enabled.""" ,		request=lowercase__  )

	if mode is OfflineSimulationMode.CONNECTION_FAILS:
		with patch("""requests.Session.send""" ,		lowercase__  ):
			yield
	elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT:
		# inspired from https://stackoverflow.com/a/904609
		with patch("""requests.Session.request""" ,		lowercase__  ):
			yield
	elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1:
		with patch("""datasets.config.HF_DATASETS_OFFLINE""" ,		lowercase__  ):
			yield
	else:
		raise ValueError("""Please use a value from the OfflineSimulationMode enum."""  )




@contextmanager
def 				A		(					*lowercase__  :  Tuple ,		**lowercase__  :  List[Any]  )		-> Optional[int]:
	UpperCamelCase__ :Any						=      str(Path().resolve()  )
	with tempfile.TemporaryDirectory(*lowercase__ ,		**lowercase__  ) as tmp_dir:
		try:
			os.chdir(lowercase__  )
			yield
		finally:
			os.chdir(lowercase__  )




@contextmanager
def 				A		(					)		-> List[Any]:
	import gc

	gc.collect()
	UpperCamelCase__ :Tuple						=      pa.total_allocated_bytes()
	yield
	assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase."




@contextmanager
def 				A		(					)		-> Optional[int]:
	import gc

	gc.collect()
	UpperCamelCase__ :int						=      pa.total_allocated_bytes()
	yield
	assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase."




def 				A		(					lowercase__  :  List[str] ,		lowercase__  :  List[str]  )		-> str:
	return deepcopy(lowercase__  ).integers(0 ,		100 ,		10  ).tolist() == deepcopy(lowercase__  ).integers(0 ,		100 ,		10  ).tolist()




def 				A		(					lowercase__  :  str  )		-> Union[str, Any]:
	import decorator
	from requests.exceptions import HTTPError

	def _wrapper(lowercase__  :  int ,		*lowercase__  :  str ,		**lowercase__  :  Optional[int]  ):
		try:
			return func(*lowercase__ ,		**lowercase__  )
		except HTTPError as err:
			if str(lowercase__  ).startswith("""500"""  ) or str(lowercase__  ).startswith("""502"""  ):
				pytest.xfail(str(lowercase__  )  )
			raise err

	return decorator.decorator(_wrapper ,		lowercase__  )

class        lowerCAmelCase_				:







				"""simple docstring"""




				def __init__( self     :Optional[Any]  ,     lowerCamelCase__     :int  ,     lowerCamelCase__     :Tuple  ,     lowerCamelCase__     :Union[str, Any]     ):
					UpperCamelCase__ :Union[str, Any]						=      returncode
					UpperCamelCase__ :Tuple						=      stdout
					UpperCamelCase__ :List[Any]						=      stderr




async def 				A		(					lowercase__  :  Union[str, Any] ,		lowercase__  :  List[Any]  )		-> Dict:
	while True:
		UpperCamelCase__ :str						=      await stream.readline()
		if line:
			callback(lowercase__  )
		else:
			break




async def 				A		(					lowercase__  :  Optional[Any] ,		lowercase__  :  Tuple=None ,		lowercase__  :  Union[str, Any]=None ,		lowercase__  :  Dict=None ,		lowercase__  :  Optional[Any]=False ,		lowercase__  :  List[Any]=False  )		-> _RunOutput:
	if echo:
		print("""\nRunning: """ ,		""" """.join(lowercase__  )  )

	UpperCamelCase__ :int						=      await asyncio.create_subprocess_exec(
	    cmd[0] ,		*cmd[1:] ,		stdin=lowercase__ ,		stdout=asyncio.subprocess.PIPE ,		stderr=asyncio.subprocess.PIPE ,		env=lowercase__ ,		)

	# note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
	# https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
	#
	# If it starts hanging, will need to switch to the following code. The problem is that no data
	# will be seen until it's done and if it hangs for example there will be no debug info.
	# out, err = await p.communicate()
	# return _RunOutput(p.returncode, out, err)

	UpperCamelCase__ :Dict						=      []
	UpperCamelCase__ :int						=      []

	def tee(lowercase__  :  int ,		lowercase__  :  List[str] ,		lowercase__  :  Any ,		lowercase__  :  Tuple=""  ):
		UpperCamelCase__ :int						=      line.decode("""utf-8"""  ).rstrip()
		sink.append(lowercase__  )
		if not quiet:
			print(lowercase__ ,		lowercase__ ,		file=lowercase__  )

    # XXX: the timeout doesn't seem to make any difference here
	await asyncio.wait(
	    [
	        _read_stream(p.stdout ,		lambda lowercase__  : tee(lowercase__ ,		lowercase__ ,		sys.stdout ,		label="""stdout:"""  )  ),
	        _read_stream(p.stderr ,		lambda lowercase__  : tee(lowercase__ ,		lowercase__ ,		sys.stderr ,		label="""stderr:"""  )  ),
	    ] ,		timeout=lowercase__ ,		)
	return _RunOutput(await p.wait() ,		lowercase__ ,		lowercase__  )




def 				A		(					lowercase__  :  Tuple ,		lowercase__  :  Optional[Any]=None ,		lowercase__  :  Optional[Any]=None ,		lowercase__  :  List[str]=180 ,		lowercase__  :  Any=False ,		lowercase__  :  Optional[Any]=True  )		-> _RunOutput:
	UpperCamelCase__ :Optional[Any]						=      asyncio.get_event_loop()
	UpperCamelCase__ :Optional[int]						=      loop.run_until_complete(
	    _stream_subprocess(lowercase__ ,		env=lowercase__ ,		stdin=lowercase__ ,		timeout=lowercase__ ,		quiet=lowercase__ ,		echo=lowercase__  )  )

	UpperCamelCase__ :Tuple						=      """ """.join(lowercase__  )
	if result.returncode > 0:
		UpperCamelCase__ :str						=      """\n""".join(result.stderr  )
		raise RuntimeError(
		    f"""'{cmd_str}' failed with returncode {result.returncode}\n\n"""
		    f"""The combined stderr from workers follows:\n{stderr}"""  )

	# check that the subprocess actually did run and produced some output, should the test rely on
	# the remote side to do the testing
	if not result.stdout and not result.stderr:
		raise RuntimeError(f"""'{cmd_str}' produced no output."""  )

	return result




def 				A		(					)		-> Optional[int]:
	UpperCamelCase__ :str						=      os.environ.get("""PYTEST_XDIST_WORKER""" ,		"""gw0"""  )
	UpperCamelCase__ :Tuple						=      re.sub(r"""^gw""" ,		"""""" ,		lowercase__ ,		0 ,		re.M  )
	return int(lowercase__  )




def 				A		(					)		-> str:
	UpperCamelCase__ :Optional[Any]						=      2_9500
	UpperCamelCase__ :List[str]						=      pytest_xdist_worker_id()
	return port + uniq_delta




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 		a__      (		_UpperCamelCase      :			str			,_UpperCamelCase      :			str			,_UpperCamelCase      :			bool				):
   __lowerCamelCase    				=     Path('''data_bin'''				)
   __lowerCamelCase    				=     FairseqXmodModel.from_pretrained(
       model_name_or_path=str(Path(_UpperCamelCase				).parent				)			,checkpoint_file=Path(_UpperCamelCase				).name			,_name='''xmod_base'''			,arch='''xmod_base'''			,task='''multilingual_masked_lm'''			,data_name_or_path=str(_UpperCamelCase				)			,bpe='''sentencepiece'''			,sentencepiece_model=str(Path(_UpperCamelCase				).parent / '''sentencepiece.bpe.model'''				)			,src_dict=str(data_dir / '''dict.txt'''				)			,)
   xmod.eval()  # disable dropout
   print(_UpperCamelCase				)

   __lowerCamelCase    				=     xmod.model.encoder.sentence_encoder
   __lowerCamelCase    				=     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=5_14			,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:
      __lowerCamelCase    				=     xmod.model.classification_heads['''mnli'''].out_proj.weight.shape[0]

   print('''Our X-MOD config:'''			,_UpperCamelCase				)

   __lowerCamelCase    				=     XmodForSequenceClassification(_UpperCamelCase				) if classification_head else XmodForMaskedLM(_UpperCamelCase				)
   model.eval()

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

   __lowerCamelCase    				=     xmod_sent_encoder.layernorm_embedding.weight
   __lowerCamelCase    				=     xmod_sent_encoder.layernorm_embedding.bias

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

      # self attention
      __lowerCamelCase    				=     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.'''				)

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

      # self-attention output
      __lowerCamelCase    				=     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.'''				)
      __lowerCamelCase    				=     xmod_layer.self_attn.out_proj.weight
      __lowerCamelCase    				=     xmod_layer.self_attn.out_proj.bias
      __lowerCamelCase    				=     xmod_layer.self_attn_layer_norm.weight
      __lowerCamelCase    				=     xmod_layer.self_attn_layer_norm.bias

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

      # output
      __lowerCamelCase    				=     layer.output
      if bert_output.dense.weight.shape != xmod_layer.fca.weight.shape:
         raise AssertionError('''Dimensions of feed-forward weights do not match.'''				)
      __lowerCamelCase    				=     xmod_layer.fca.weight
      __lowerCamelCase    				=     xmod_layer.fca.bias
      __lowerCamelCase    				=     xmod_layer.final_layer_norm.weight
      __lowerCamelCase    				=     xmod_layer.final_layer_norm.bias
      if bert_output.adapter_layer_norm is not None:
         __lowerCamelCase    				=     xmod_layer.adapter_layer_norm.weight
         __lowerCamelCase    				=     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():
         __lowerCamelCase    				=     bert_output.adapter_modules[lang_code]
         __lowerCamelCase    				=     xmod_layer.adapter_modules[lang_code]
         __lowerCamelCase    				=     from_adapter.fca.weight
         __lowerCamelCase    				=     from_adapter.fca.bias
         __lowerCamelCase    				=     from_adapter.fca.weight
         __lowerCamelCase    				=     from_adapter.fca.bias

      # end of layer

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

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

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

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

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


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
  )






