






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   __lowercase       (			snake_case,	snake_case=False			):







				"""simple docstring"""






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


SCREAMING_SNAKE_CASE__   :      Union[str, Any]				=		parse_flag_from_env("""RUN_SLOW""", default=False)
SCREAMING_SNAKE_CASE__   :      Dict				=		parse_flag_from_env("""RUN_REMOTE""", default=False)
SCREAMING_SNAKE_CASE__   :      Any				=		parse_flag_from_env("""RUN_LOCAL""", default=True)
SCREAMING_SNAKE_CASE__   :      Dict				=		parse_flag_from_env("""RUN_PACKAGED""", default=True)

# Compression
SCREAMING_SNAKE_CASE__   :      Optional[Any]				=		pytest.mark.skipif(not config.LZ4_AVAILABLE, reason="""test requires lz4""")
SCREAMING_SNAKE_CASE__   :      Dict				=		pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason="""test requires py7zr""")
SCREAMING_SNAKE_CASE__   :      Optional[int]				=		pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason="""test requires zstandard""")

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

# Windows
SCREAMING_SNAKE_CASE__   :      Union[str, Any]				=		pytest.mark.skipif(
    sys.platform == """win32""",
    reason="""test should not be run on Windows""",
)

def   __lowercase       (			snake_case			):







				"""simple docstring"""






				try:
								import faiss  # noqa
				except ImportError:
								__magic_name__		:Optional[Any]   =   unittest.skip('''test requires faiss'''			)(snake_case			)
				return test_case

def   __lowercase       (			snake_case			):







				"""simple docstring"""






				try:
								import regex  # noqa
				except ImportError:
								__magic_name__		:Union[str, Any]   =   unittest.skip('''test requires regex'''			)(snake_case			)
				return test_case

def   __lowercase       (			snake_case			):







				"""simple docstring"""






				try:
								import elasticsearch  # noqa
				except ImportError:
								__magic_name__		:Optional[int]   =   unittest.skip('''test requires elasticsearch'''			)(snake_case			)
				return test_case

def   __lowercase       (			snake_case			):







				"""simple docstring"""






				try:
								import sqlalchemy  # noqa
				except ImportError:
								__magic_name__		:Tuple   =   unittest.skip('''test requires sqlalchemy'''			)(snake_case			)
				return test_case

def   __lowercase       (			snake_case			):







				"""simple docstring"""






				if not config.TORCH_AVAILABLE:
								__magic_name__		:Optional[int]   =   unittest.skip('''test requires PyTorch'''			)(snake_case			)
				return test_case

def   __lowercase       (			snake_case			):







				"""simple docstring"""






				if not config.TF_AVAILABLE:
								__magic_name__		:Tuple   =   unittest.skip('''test requires TensorFlow'''			)(snake_case			)
				return test_case

def   __lowercase       (			snake_case			):







				"""simple docstring"""






				if not config.JAX_AVAILABLE:
								__magic_name__		:Optional[int]   =   unittest.skip('''test requires JAX'''			)(snake_case			)
				return test_case

def   __lowercase       (			snake_case			):







				"""simple docstring"""






				if not config.PIL_AVAILABLE:
								__magic_name__		:Tuple   =   unittest.skip('''test requires Pillow'''			)(snake_case			)
				return test_case

def   __lowercase       (			snake_case			):







				"""simple docstring"""






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

def   __lowercase       (			snake_case			):







				"""simple docstring"""






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

def   __lowercase       (			snake_case			):







				"""simple docstring"""






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

def   __lowercase       (			snake_case			):







				"""simple docstring"""






				def _require_spacy_model(snake_case			):
								try:
												import spacy  # noqa F401

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

				return _require_spacy_model

def   __lowercase       (			snake_case			):







				"""simple docstring"""






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

def   __lowercase       (			snake_case			):







				"""simple docstring"""






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

def   __lowercase       (			snake_case			):







				"""simple docstring"""






				if not _run_slow_tests or _run_slow_tests == 0:
								__magic_name__		:List[str]   =   unittest.skip('''test is slow'''			)(snake_case			)
				return test_case

def   __lowercase       (			snake_case			):







				"""simple docstring"""






				if not _run_local_tests or _run_local_tests == 0:
								__magic_name__		:Optional[Any]   =   unittest.skip('''test is local'''			)(snake_case			)
				return test_case

def   __lowercase       (			snake_case			):







				"""simple docstring"""






				if not _run_packaged_tests or _run_packaged_tests == 0:
								__magic_name__		:List[str]   =   unittest.skip('''test is packaged'''			)(snake_case			)
				return test_case

def   __lowercase       (			snake_case			):







				"""simple docstring"""






				if not _run_remote_tests or _run_remote_tests == 0:
								__magic_name__		:Any   =   unittest.skip('''test requires remote'''			)(snake_case			)
				return test_case

def   __lowercase       (			*snake_case			):







				"""simple docstring"""






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

				return decorate
class     lowerCamelCase_					(   lowerCamelCase			):
				pass







class     lowerCamelCase_					(   lowerCamelCase			):
				a__       							=	0
				a__       							=	1
				a__       							=	2







@contextmanager
def   __lowercase       (			snake_case=OfflineSimulationMode.CONNECTION_FAILS,	snake_case=1E-1_6			):







				"""simple docstring"""






				__magic_name__		:Optional[Any]   =   requests.Session().request

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

				def raise_connection_error(snake_case,	snake_case,	**snake_case			):
								raise requests.ConnectionError('''Offline mode is enabled.''',	request=snake_case			)

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

@contextmanager
def   __lowercase       (			*snake_case,	**snake_case			):







				"""simple docstring"""






				__magic_name__		:List[Any]   =   str(Path().resolve()			)
				with tempfile.TemporaryDirectory(*snake_case,	**snake_case			) as tmp_dir:
								try:
												os.chdir(snake_case			)
												yield
								finally:
												os.chdir(snake_case			)

@contextmanager
def   __lowercase       (			):







				"""simple docstring"""






				import gc

				gc.collect()
				__magic_name__		:List[Any]   =   pa.total_allocated_bytes()
				yield
				assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase."

@contextmanager
def   __lowercase       (			):







				"""simple docstring"""






				import gc

				gc.collect()
				__magic_name__		:Optional[Any]   =   pa.total_allocated_bytes()
				yield
				assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase."

def   __lowercase       (			snake_case,	snake_case			):







				"""simple docstring"""






				return deepcopy(snake_case			).integers(0,	1_0_0,	1_0			).tolist() == deepcopy(snake_case			).integers(0,	1_0_0,	1_0			).tolist()

def   __lowercase       (			snake_case			):







				"""simple docstring"""






				import decorator
				from requests.exceptions import HTTPError

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

				return decorator.decorator(_wrapper,	snake_case			)
class     lowerCamelCase_					:







				def __init__(    self							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase  ):
								"""simple docstring"""
								__magic_name__		:str   =   returncode
								__magic_name__		:Any   =   stdout
								__magic_name__		:str   =   stderr







async def   __lowercase       (			snake_case,	snake_case			):







				"""simple docstring"""






				while True:
								__magic_name__		:Optional[int]   =   await stream.readline()
								if line:
												callback(snake_case			)
								else:
												break

async def   __lowercase       (			snake_case,	snake_case=None,	snake_case=None,	snake_case=None,	snake_case=False,	snake_case=False			):







				"""simple docstring"""






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

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

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

				__magic_name__		:Any   =   []
				__magic_name__		:Optional[Any]   =   []

				def tee(snake_case,	snake_case,	snake_case,	snake_case=""			):
								__magic_name__		:Optional[Any]   =   line.decode('''utf-8'''			).rstrip()
								sink.append(snake_case			)
								if not quiet:
												print(snake_case,	snake_case,	file=snake_case			)

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

def   __lowercase       (			snake_case,	snake_case=None,	snake_case=None,	snake_case=1_8_0,	snake_case=False,	snake_case=True			):







				"""simple docstring"""






				__magic_name__		:Union[str, Any]   =   asyncio.get_event_loop()
				__magic_name__		:List[Any]   =   loop.run_until_complete(
				    _stream_subprocess(snake_case,	env=snake_case,	stdin=snake_case,	timeout=snake_case,	quiet=snake_case,	echo=snake_case			)			)

				__magic_name__		:str   =   ''' '''.join(snake_case			)
				if result.returncode > 0:
								__magic_name__		:Tuple   =   '''\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   __lowercase       (			):







				"""simple docstring"""






				__magic_name__		:str   =   os.environ.get('''PYTEST_XDIST_WORKER''',	'''gw0'''			)
				__magic_name__		:Union[str, Any]   =   re.sub(R'''^gw''',	'''''',	snake_case,	0,	re.M			)
				return int(snake_case			)

def   __lowercase       (			):







				"""simple docstring"""






				__magic_name__		:Union[str, Any]   =   2_9_5_0_0
				__magic_name__		:List[Any]   =   pytest_xdist_worker_id()
				return port + uniq_delta














import argparse

import torch
from torch import nn

from transformers import MaMaaaConfig, MaMaaaForConditionalGeneration

def   __lowercase       (			snake_case			):







				"""simple docstring"""






				__magic_name__		:Optional[Any]   =   [
				    '''encoder.version''',
				    '''decoder.version''',
				    '''model.encoder.version''',
				    '''model.decoder.version''',
				    '''decoder.output_projection.weight''',
				    '''_float_tensor''',
				    '''encoder.embed_positions._float_tensor''',
				    '''decoder.embed_positions._float_tensor''',
				]
				for k in ignore_keys:
								state_dict.pop(snake_case,	snake_case			)

def   __lowercase       (			snake_case			):







				"""simple docstring"""






				__magic_name__  ,					__magic_name__		:Tuple   =   emb.weight.shape
				__magic_name__		:int   =   nn.Linear(snake_case,	snake_case,	bias=snake_case			)
				__magic_name__		:str   =   emb.weight.data
				return lin_layer

def   __lowercase       (			snake_case			):







				"""simple docstring"""






				__magic_name__		:int   =   torch.load(snake_case,	map_location='''cpu'''			)
				__magic_name__		:Optional[Any]   =   mam_aaa['''args'''] or mam_aaa['''cfg''']['''model''']
				__magic_name__		:List[Any]   =   mam_aaa['''model''']
				remove_ignore_keys_(snake_case			)
				__magic_name__		:Tuple   =   state_dict['''encoder.embed_tokens.weight'''].shape[0]

				__magic_name__		:List[str]   =   MaMaaaConfig(
				    vocab_size=snake_case,	max_position_embeddings=1_0_2_4,	encoder_layers=args.encoder_layers,	decoder_layers=args.decoder_layers,	encoder_attention_heads=args.encoder_attention_heads,	decoder_attention_heads=args.decoder_attention_heads,	encoder_ffn_dim=args.encoder_ffn_embed_dim,	decoder_ffn_dim=args.decoder_ffn_embed_dim,	d_model=args.encoder_embed_dim,	encoder_layerdrop=args.encoder_layerdrop,	decoder_layerdrop=args.decoder_layerdrop,	dropout=args.dropout,	attention_dropout=args.attention_dropout,	activation_dropout=args.activation_dropout,	activation_function='''relu''',	)

				__magic_name__		:int   =   state_dict['''decoder.embed_tokens.weight''']
				__magic_name__		:List[str]   =   MaMaaaForConditionalGeneration(snake_case			)
				model.model.load_state_dict(snake_case,	strict=snake_case			)
				__magic_name__		:List[str]   =   make_linear_from_emb(model.model.shared			)

				return model


if __name__ == "__main__":
					SCREAMING_SNAKE_CASE__   :      Optional[Any]				=		argparse.ArgumentParser()
					# Required parameters
					parser.add_argument("""fairseq_path""", type=str, help="""path to a model.pt on local filesystem.""")
					parser.add_argument("""pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""")
					SCREAMING_SNAKE_CASE__   :      int				=		parser.parse_args()
					SCREAMING_SNAKE_CASE__   :      Any				=		convert_fairseq_mamaaa_checkpoint_from_disk(args.fairseq_pathß)
					model.save_pretrained(args.pytorch_dump_folder_path)






