





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      UpperCAmelCase_    (    _UpperCAmelCase							:Union[str, Any]  ,						_UpperCAmelCase							:Union[str, Any]=False				)	->				str:
     '''simple docstring'''


     try:
          A_          =       os.environ[key]
     except KeyError:
          # KEY isn't set, default to `default`.
          A_          =       default
     else:
          # KEY is set, convert it to True or False.
          try:
               A_          =       strtobool(_UpperCAmelCase				)
          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


a__      :     Optional[int]         =		parse_flag_from_env('RUN_SLOW', default=False)
a__      :     Optional[int]         =		parse_flag_from_env('RUN_REMOTE', default=False)
a__      :     Optional[Any]         =		parse_flag_from_env('RUN_LOCAL', default=True)
a__      :     Any         =		parse_flag_from_env('RUN_PACKAGED', default=True)

# Compression
a__      :     List[str]         =		pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='test requires lz4')
a__      :     List[Any]         =		pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='test requires py7zr')
a__      :     Tuple         =		pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='test requires zstandard')

# Audio
a__      :     Dict         =		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
a__      :     List[str]         =		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
a__      :     Any         =		pytest.mark.skipif(
    config.DILL_VERSION <= version.parse('0.3.2'),
    reason='test requires dill>0.3.2 for cloudpickle compatibility',
)

# Windows
a__      :     str         =		pytest.mark.skipif(
    sys.platform == 'win32',
    reason='test should not be run on Windows',
)

def      UpperCAmelCase_    (    _UpperCAmelCase							:int				)	->				str:
     '''simple docstring'''


     try:
          import faiss  # noqa
     except ImportError:
          A_          =       unittest.skip('''test requires faiss'''				)(_UpperCAmelCase				)
     return test_case

def      UpperCAmelCase_    (    _UpperCAmelCase							:int				)	->				List[str]:
     '''simple docstring'''


     try:
          import regex  # noqa
     except ImportError:
          A_          =       unittest.skip('''test requires regex'''				)(_UpperCAmelCase				)
     return test_case

def      UpperCAmelCase_    (    _UpperCAmelCase							:Dict				)	->				Union[str, Any]:
     '''simple docstring'''


     try:
          import elasticsearch  # noqa
     except ImportError:
          A_          =       unittest.skip('''test requires elasticsearch'''				)(_UpperCAmelCase				)
     return test_case

def      UpperCAmelCase_    (    _UpperCAmelCase							:Dict				)	->				Union[str, Any]:
     '''simple docstring'''


     try:
          import sqlalchemy  # noqa
     except ImportError:
          A_          =       unittest.skip('''test requires sqlalchemy'''				)(_UpperCAmelCase				)
     return test_case

def      UpperCAmelCase_    (    _UpperCAmelCase							:int				)	->				Optional[int]:
     '''simple docstring'''


     if not config.TORCH_AVAILABLE:
          A_          =       unittest.skip('''test requires PyTorch'''				)(_UpperCAmelCase				)
     return test_case

def      UpperCAmelCase_    (    _UpperCAmelCase							:List[Any]				)	->				List[str]:
     '''simple docstring'''


     if not config.TF_AVAILABLE:
          A_          =       unittest.skip('''test requires TensorFlow'''				)(_UpperCAmelCase				)
     return test_case

def      UpperCAmelCase_    (    _UpperCAmelCase							:List[Any]				)	->				int:
     '''simple docstring'''


     if not config.JAX_AVAILABLE:
          A_          =       unittest.skip('''test requires JAX'''				)(_UpperCAmelCase				)
     return test_case

def      UpperCAmelCase_    (    _UpperCAmelCase							:List[str]				)	->				Optional[int]:
     '''simple docstring'''


     if not config.PIL_AVAILABLE:
          A_          =       unittest.skip('''test requires Pillow'''				)(_UpperCAmelCase				)
     return test_case

def      UpperCAmelCase_    (    _UpperCAmelCase							:Optional[Any]				)	->				Union[str, Any]:
     '''simple docstring'''


     try:
          import transformers  # noqa F401
     except ImportError:
          return unittest.skip('''test requires transformers'''				)(_UpperCAmelCase				)
     else:
          return test_case

def      UpperCAmelCase_    (    _UpperCAmelCase							:Any				)	->				Optional[Any]:
     '''simple docstring'''


     try:
          import tiktoken  # noqa F401
     except ImportError:
          return unittest.skip('''test requires tiktoken'''				)(_UpperCAmelCase				)
     else:
          return test_case

def      UpperCAmelCase_    (    _UpperCAmelCase							:List[Any]				)	->				List[Any]:
     '''simple docstring'''


     try:
          import spacy  # noqa F401
     except ImportError:
          return unittest.skip('''test requires spacy'''				)(_UpperCAmelCase				)
     else:
          return test_case

def      UpperCAmelCase_    (    _UpperCAmelCase							:Optional[int]				)	->				str:
     '''simple docstring'''


     def _require_spacy_model(_UpperCAmelCase							:str				):
          try:
               import spacy  # noqa F401

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

     return _require_spacy_model

def      UpperCAmelCase_    (    _UpperCAmelCase							:Optional[Any]				)	->				str:
     '''simple docstring'''


     try:
          import pyspark  # noqa F401
     except ImportError:
          return unittest.skip('''test requires pyspark'''				)(_UpperCAmelCase				)
     else:
          return test_case

def      UpperCAmelCase_    (    _UpperCAmelCase							:Any				)	->				Optional[Any]:
     '''simple docstring'''


     try:
          import joblibspark  # noqa F401
     except ImportError:
          return unittest.skip('''test requires joblibspark'''				)(_UpperCAmelCase				)
     else:
          return test_case

def      UpperCAmelCase_    (    _UpperCAmelCase							:Optional[Any]				)	->				str:
     '''simple docstring'''


     if not _run_slow_tests or _run_slow_tests == 0:
          A_          =       unittest.skip('''test is slow'''				)(_UpperCAmelCase				)
     return test_case

def      UpperCAmelCase_    (    _UpperCAmelCase							:str				)	->				List[str]:
     '''simple docstring'''


     if not _run_local_tests or _run_local_tests == 0:
          A_          =       unittest.skip('''test is local'''				)(_UpperCAmelCase				)
     return test_case

def      UpperCAmelCase_    (    _UpperCAmelCase							:List[str]				)	->				List[Any]:
     '''simple docstring'''


     if not _run_packaged_tests or _run_packaged_tests == 0:
          A_          =       unittest.skip('''test is packaged'''				)(_UpperCAmelCase				)
     return test_case

def      UpperCAmelCase_    (    _UpperCAmelCase							:Optional[Any]				)	->				Tuple:
     '''simple docstring'''


     if not _run_remote_tests or _run_remote_tests == 0:
          A_          =       unittest.skip('''test requires remote'''				)(_UpperCAmelCase				)
     return test_case

def      UpperCAmelCase_    (    *_UpperCAmelCase							:Any				)	->				Dict:
     '''simple docstring'''


     def decorate(cls							:Union[str, Any]				):
          for name, fn in cls.__dict__.items():
               if callable(_UpperCAmelCase				) and name.startswith('''test'''				):
                    for decorator in decorators:
                         A_          =       decorator(_UpperCAmelCase				)
                    setattr(cls  ,						_UpperCAmelCase  ,						_UpperCAmelCase				)
          return cls

     return decorate





class UpperCAmelCase_				( _SCREAMING_SNAKE_CASE ):
  pass





class UpperCAmelCase_				( _SCREAMING_SNAKE_CASE ):
  __lowerCAmelCase   :						int							=   0
  __lowerCAmelCase   :						Dict							=   1
  __lowerCAmelCase   :						Optional[Any]							=   2




@contextmanager
def      UpperCAmelCase_    (    _UpperCAmelCase							:int=OfflineSimulationMode.CONNECTION_FAILS  ,						_UpperCAmelCase							:Any=1e-16				)	->				List[str]:
     '''simple docstring'''


     A_          =       requests.Session().request

     def timeout_request(_UpperCAmelCase							:str  ,						_UpperCAmelCase							:Dict  ,						_UpperCAmelCase							:Tuple  ,						**_UpperCAmelCase							:Union[str, Any]				):
          # Change the url to an invalid url so that the connection hangs
          A_          =       '''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.'				)
          A_          =       timeout
          try:
               return online_request(_UpperCAmelCase  ,						_UpperCAmelCase  ,						**_UpperCAmelCase				)
          except Exception as e:
               # The following changes in the error are just here to make the offline timeout error prettier
               A_          =       url
               A_          =       e.args[0]
               A_          =       (max_retry_error.args[0].replace('''10.255.255.1'''  ,						f'OfflineMock[{url}]'				),)
               A_          =       (max_retry_error,)
               raise

     def raise_connection_error(_UpperCAmelCase							:str  ,						_UpperCAmelCase							:Any  ,						**_UpperCAmelCase							:Tuple				):
          raise requests.ConnectionError('''Offline mode is enabled.'''  ,						request=_UpperCAmelCase				)

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

@contextmanager
def      UpperCAmelCase_    (    *_UpperCAmelCase							:Union[str, Any]  ,						**_UpperCAmelCase							:str				)	->				Union[str, Any]:
     '''simple docstring'''


     A_          =       str(Path().resolve()				)
     with tempfile.TemporaryDirectory(*_UpperCAmelCase  ,						**_UpperCAmelCase				) as tmp_dir:
          try:
               os.chdir(_UpperCAmelCase				)
               yield
          finally:
               os.chdir(_UpperCAmelCase				)

@contextmanager
def      UpperCAmelCase_    (    )	->				Tuple:
     '''simple docstring'''


     import gc

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

@contextmanager
def      UpperCAmelCase_    (    )	->				Optional[int]:
     '''simple docstring'''


     import gc

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

def      UpperCAmelCase_    (    _UpperCAmelCase							:Union[str, Any]  ,						_UpperCAmelCase							:List[str]				)	->				List[Any]:
     '''simple docstring'''


     return deepcopy(_UpperCAmelCase				).integers(0  ,						100  ,						10				).tolist() == deepcopy(_UpperCAmelCase				).integers(0  ,						100  ,						10				).tolist()

def      UpperCAmelCase_    (    _UpperCAmelCase							:List[Any]				)	->				str:
     '''simple docstring'''


     import decorator
     from requests.exceptions import HTTPError

     def _wrapper(_UpperCAmelCase							:Any  ,						*_UpperCAmelCase							:List[Any]  ,						**_UpperCAmelCase							:List[Any]				):
          try:
               return func(*_UpperCAmelCase  ,						**_UpperCAmelCase				)
          except HTTPError as err:
               if str(_UpperCAmelCase				).startswith('''500'''				) or str(_UpperCAmelCase				).startswith('''502'''				):
                    pytest.xfail(str(_UpperCAmelCase				)				)
               raise err

     return decorator.decorator(_wrapper  ,						_UpperCAmelCase				)





class UpperCAmelCase_				:


  def __init__(							self ,__snake_case ,__snake_case ,__snake_case ):



       """simple docstring"""





       A_          =       returncode
       A_          =       stdout
       A_          =       stderr




async def      UpperCAmelCase_    (    _UpperCAmelCase							:Optional[int]  ,						_UpperCAmelCase							:Optional[Any]				)	->				Any:
     '''simple docstring'''


     while True:
          A_          =       await stream.readline()
          if line:
               callback(_UpperCAmelCase				)
          else:
               break

async def      UpperCAmelCase_    (    _UpperCAmelCase							:List[str]  ,						_UpperCAmelCase							:List[Any]=None  ,						_UpperCAmelCase							:List[str]=None  ,						_UpperCAmelCase							:Any=None  ,						_UpperCAmelCase							:Optional[Any]=False  ,						_UpperCAmelCase							:Tuple=False				)	->				_RunOutput:
     '''simple docstring'''


     if echo:
          print('''\nRunning: '''  ,						''' '''.join(_UpperCAmelCase				)				)

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

     # 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)

     A_          =       []
     A_          =       []

     def tee(_UpperCAmelCase							:Union[str, Any]  ,						_UpperCAmelCase							:Tuple  ,						_UpperCAmelCase							:List[str]  ,						_UpperCAmelCase							:Dict=""				):
          A_          =       line.decode('''utf-8'''				).rstrip()
          sink.append(_UpperCAmelCase				)
          if not quiet:
               print(_UpperCAmelCase  ,						_UpperCAmelCase  ,						file=_UpperCAmelCase				)

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

def      UpperCAmelCase_    (    _UpperCAmelCase							:Dict  ,						_UpperCAmelCase							:Any=None  ,						_UpperCAmelCase							:int=None  ,						_UpperCAmelCase							:Optional[Any]=180  ,						_UpperCAmelCase							:List[str]=False  ,						_UpperCAmelCase							:List[Any]=True				)	->				_RunOutput:
     '''simple docstring'''


     A_          =       asyncio.get_event_loop()
     A_          =       loop.run_until_complete(
         _stream_subprocess(_UpperCAmelCase  ,						env=_UpperCAmelCase  ,						stdin=_UpperCAmelCase  ,						timeout=_UpperCAmelCase  ,						quiet=_UpperCAmelCase  ,						echo=_UpperCAmelCase				)				)

     A_          =       ''' '''.join(_UpperCAmelCase				)
     if result.returncode > 0:
          A_          =       '''\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      UpperCAmelCase_    (    )	->				Optional[Any]:
     '''simple docstring'''


     A_          =       os.environ.get('''PYTEST_XDIST_WORKER'''  ,						'''gw0'''				)
     A_          =       re.sub(R'''^gw'''  ,						''''''  ,						_UpperCAmelCase  ,						0  ,						re.M				)
     return int(_UpperCAmelCase				)


def      UpperCAmelCase_    (    )	->				str:
     '''simple docstring'''


     A_          =       29500
     A_          =       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__      :     Any         =		logging.get_logger(__name__)

a__      :     Tuple         =		'Hello, World!'
a__      :     Any         =		'en_XX'

def      UpperCAmelCase_    (    _UpperCAmelCase							:str  ,						_UpperCAmelCase							:str  ,						_UpperCAmelCase							:bool				)	->				Optional[Any]:
     '''simple docstring'''


     A_          =       Path('''data_bin'''				)
     A_          =       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				)

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

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

     A_          =       XmodForSequenceClassification(_UpperCAmelCase				) if classification_head else XmodForMaskedLM(_UpperCAmelCase				)
     model.eval()

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

     A_          =       xmod_sent_encoder.layernorm_embedding.weight
     A_          =       xmod_sent_encoder.layernorm_embedding.bias

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

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

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

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

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

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

          # end of layer

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

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

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

     A_          =       model(_UpperCAmelCase				)[0]
     if classification_head:
          A_          =       xmod.model.classification_heads['''mnli'''](xmod.extract_features(_UpperCAmelCase				)				)
     else:
          A_          =       xmod.model(_UpperCAmelCase  ,						lang_id=[SAMPLE_LANGUAGE]				)[0]
     print(our_output.shape  ,						their_output.shape				)
     A_          =       torch.max(torch.abs(our_output - their_output				)				).item()
     print(f'max_absolute_diff = {max_absolute_diff}'				)  # ~ 1e-7
     A_          =       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__      :     List[str]         =		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__      :     Tuple         =		parser.parse_args()
      convert_xmod_checkpoint_to_pytorch(
          args.xmod_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head
      )



