






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


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

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

# Audio
lowercase  							=					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
lowercase  							=					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
lowercase  							=					pytest.mark.skipif(
    config.DILL_VERSION <= version.parse("0.3.2"),
    reason="test requires dill>0.3.2 for cloudpickle compatibility",
)

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





def 						__UpperCAmelCase			(     a_):
							try:
														import faiss  # noqa
							except ImportError:
														snake_case_				=							unittest.skip('test requires faiss')(_lowercase)
							return test_case





def 						__UpperCAmelCase			(     a_):
							try:
														import regex  # noqa
							except ImportError:
														snake_case_				=							unittest.skip('test requires regex')(_lowercase)
							return test_case





def 						__UpperCAmelCase			(     a_):
							try:
														import elasticsearch  # noqa
							except ImportError:
														snake_case_				=							unittest.skip('test requires elasticsearch')(_lowercase)
							return test_case





def 						__UpperCAmelCase			(     a_):
							try:
														import sqlalchemy  # noqa
							except ImportError:
														snake_case_				=							unittest.skip('test requires sqlalchemy')(_lowercase)
							return test_case





def 						__UpperCAmelCase			(     a_):
							if not config.TORCH_AVAILABLE:
														snake_case_				=							unittest.skip('test requires PyTorch')(_lowercase)
							return test_case





def 						__UpperCAmelCase			(     a_):
							if not config.TF_AVAILABLE:
														snake_case_				=							unittest.skip('test requires TensorFlow')(_lowercase)
							return test_case





def 						__UpperCAmelCase			(     a_):
							if not config.JAX_AVAILABLE:
														snake_case_				=							unittest.skip('test requires JAX')(_lowercase)
							return test_case





def 						__UpperCAmelCase			(     a_):
							if not config.PIL_AVAILABLE:
														snake_case_				=							unittest.skip('test requires Pillow')(_lowercase)
							return test_case





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





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





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





def 						__UpperCAmelCase			(     a_):

							def _require_spacy_model(a_):
														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 						__UpperCAmelCase			(     a_):
							try:
														import pyspark  # noqa F401
							except ImportError:
														return unittest.skip('test requires pyspark')(_lowercase)
							else:
														return test_case





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





def 						__UpperCAmelCase			(     a_):
							if not _run_slow_tests or _run_slow_tests == 0:
														snake_case_				=							unittest.skip('test is slow')(_lowercase)
							return test_case





def 						__UpperCAmelCase			(     a_):
							if not _run_local_tests or _run_local_tests == 0:
														snake_case_				=							unittest.skip('test is local')(_lowercase)
							return test_case





def 						__UpperCAmelCase			(     a_):
							if not _run_packaged_tests or _run_packaged_tests == 0:
														snake_case_				=							unittest.skip('test is packaged')(_lowercase)
							return test_case





def 						__UpperCAmelCase			(     a_):
							if not _run_remote_tests or _run_remote_tests == 0:
														snake_case_				=							unittest.skip('test requires remote')(_lowercase)
							return test_case





def 						__UpperCAmelCase			(     *a_):
							def decorate(cls):
														for name, fn in cls.__dict__.items():
																					if callable(_lowercase) and name.startswith('test'):
																												for decorator in decorators:
																																			snake_case_				=							decorator(_lowercase)
																												setattr(cls							,     _lowercase							,     _lowercase)
														return cls

							return decorate




class  UpperCamelCase_      (			snake_case_				):



	'''simple docstring'''




	pass






class  UpperCamelCase_      (			snake_case_				):



	'''simple docstring'''




	lowerCAmelCase													= 0
	lowerCAmelCase													= 1
	lowerCAmelCase													= 2






@contextmanager
def 						__UpperCAmelCase			(     a_=OfflineSimulationMode.CONNECTION_FAILS							,     a_=1E-16):
							snake_case_				=							requests.Session().request

							def timeout_request(a_							,     a_							,     a_							,     **a_):
														# Change the url to an invalid url so that the connection hangs
														snake_case_				=							"""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.''')
														snake_case_				=							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
																					snake_case_				=							url
																					snake_case_				=							e.args[0]
																					snake_case_				=							(max_retry_error.args[0].replace('10.255.255.1'							,     f'''OfflineMock[{url}]'''),)
																					snake_case_				=							(max_retry_error,)
																					raise

							def raise_connection_error(a_							,     a_							,     **a_):
														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 						__UpperCAmelCase			(     *a_							,     **a_):
							snake_case_				=							str(Path().resolve())
							with tempfile.TemporaryDirectory(*_lowercase							,     **_lowercase) as tmp_dir:
														try:
																					os.chdir(_lowercase)
																					yield
														finally:
																					os.chdir(_lowercase)





@contextmanager
def 						__UpperCAmelCase			(     ):
							import gc

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





@contextmanager
def 						__UpperCAmelCase			(     ):
							import gc

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





def 						__UpperCAmelCase			(     a_							,     a_):
							return deepcopy(_lowercase).integers(0							,     1_00							,     10).tolist() == deepcopy(_lowercase).integers(0							,     1_00							,     10).tolist()





def 						__UpperCAmelCase			(     a_):
							import decorator
							from requests.exceptions import HTTPError

							def _wrapper(a_							,     *a_							,     **a_):
														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  UpperCamelCase_      :



	'''simple docstring'''




	def __init__(       self       ,			a       ,			a       ,			a					)       ->    Any:
								snake_case_				=							returncode
								snake_case_				=							stdout
								snake_case_				=							stderr






async def 						__UpperCAmelCase			(     a_							,     a_):
							while True:
														snake_case_				=							await stream.readline()
														if line:
																					callback(_lowercase)
														else:
																					break





async def 						__UpperCAmelCase			(     a_							,     a_=None							,     a_=None							,     a_=None							,     a_=False							,     a_=False):
							if echo:
														print('\nRunning: '							,     ' '.join(_lowercase))

							snake_case_				=							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)

							snake_case_				=							[]
							snake_case_				=							[]

							def tee(a_							,     a_							,     a_							,     a_=""):
														snake_case_				=							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 a_: tee(_lowercase							,     _lowercase							,     sys.stdout							,     label='stdout:')),
							        _read_stream(p.stderr							,     lambda a_: tee(_lowercase							,     _lowercase							,     sys.stderr							,     label='stderr:')),
							    ]							,     timeout=_lowercase							,     )
							return _RunOutput(await p.wait()							,     _lowercase							,     _lowercase)





def 						__UpperCAmelCase			(     a_							,     a_=None							,     a_=None							,     a_=1_80							,     a_=False							,     a_=True):
							snake_case_				=							asyncio.get_event_loop()
							snake_case_				=							loop.run_until_complete(
							    _stream_subprocess(_lowercase							,     env=_lowercase							,     stdin=_lowercase							,     timeout=_lowercase							,     quiet=_lowercase							,     echo=_lowercase))

							snake_case_				=							""" """.join(_lowercase)
							if result.returncode > 0:
														snake_case_				=							"""\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			(     ):
							snake_case_				=							os.environ.get('PYTEST_XDIST_WORKER'							,     'gw0')
							snake_case_				=							re.sub(R'^gw'							,     ''							,     _lowercase							,     0							,     re.M)
							return int(_lowercase)





def 						__UpperCAmelCase			(     ):
							snake_case_				=							2_95_00
							snake_case_				=							pytest_xdist_worker_id()
							return port + uniq_delta










'''simple docstring'''




import argparse
import json
import os

import torch
from torch import nn

from transformers import NllbMoeConfig, NllbMoeModel
from transformers.modeling_utils import dtype_byte_size
from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME



def       __lowerCamelCase  (					_lowercase		)      ->			Union[str, Any]:
							UpperCAmelCase     :		Dict							     =		[
							    """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(_lowercase	,				_lowercase		)



def       __lowerCamelCase  (					_lowercase		)      ->			Tuple:
							UpperCAmelCase     ,     UpperCAmelCase     :		List[str]							     =		emb.weight.shape
							UpperCAmelCase     :		Dict							     =		nn.Linear(_lowercase	,				_lowercase	,				bias=_lowercase		)
							UpperCAmelCase     :		Optional[Any]							     =		emb.weight.data
							return lin_layer



def       __lowerCamelCase  (					_lowercase	,				_lowercase=None		)      ->			List[Any]:
							UpperCAmelCase     :		Dict							     =		{}
							for old_key in state_dict.keys():
														UpperCAmelCase     :		str							     =		old_key
														if "moe_layer.experts." in key:
																					if expert_idx is not None:
																												UpperCAmelCase     :		int							     =		key.replace("""moe_layer.experts.0"""	,				F'''ffn.experts.expert_{expert_idx}'''		)
																					else:
																												UpperCAmelCase     :		str							     =		key.replace("""moe_layer.experts."""	,				"""ffn.experts.expert_"""		)
														if "gate" in key:
																					UpperCAmelCase     :		str							     =		key.replace(""".moe_layer.gate.wg"""	,				""".ffn.router.classifier"""		)
														if "fc2" and "experts" not in key:
																					UpperCAmelCase     :		Tuple							     =		key.replace(""".fc2."""	,				""".ffn.fc2."""		)
														if "fc1" and "experts" not in key:
																					UpperCAmelCase     :		List[Any]							     =		key.replace(""".fc1."""	,				""".ffn.fc1."""		)
														if ".encoder_attn." in key:
																					UpperCAmelCase     :		Union[str, Any]							     =		key.replace(""".encoder_attn."""	,				""".cross_attention."""		)
														if "encoder_attn_layer_norm" in key:
																					UpperCAmelCase     :		str							     =		key.replace("""encoder_attn_layer_norm"""	,				"""cross_attention_layer_norm"""		)
														if "final_layer_norm" in key:
																					UpperCAmelCase     :		Optional[int]							     =		key.replace("""final_layer_norm"""	,				"""ff_layer_norm"""		)
														UpperCAmelCase     :		str							     =		state_dict[old_key]
							return new_dict



def       __lowerCamelCase  (					_lowercase	,				_lowercase	,				_lowercase	,				_lowercase	,				_lowercase = WEIGHTS_NAME		)      ->			Tuple:
							UpperCAmelCase     :		Any							     =		[]
							UpperCAmelCase     :		Dict							     =		0
							os.makedirs(_lowercase	,				exist_ok=_lowercase		)

							for expert in range(_lowercase		):
														UpperCAmelCase     :		str							     =		switch_checkpoint_path + F'''-rank-{expert}.pt'''
														if os.path.isfile(_lowercase		):
																					UpperCAmelCase     :		Optional[Any]							     =		torch.load(_lowercase		)["""model"""]
																					remove_ignore_keys_(_lowercase		)
																					UpperCAmelCase     :		List[str]							     =		rename_fairseq_keys(_lowercase	,				_lowercase		)
																					UpperCAmelCase     :		Optional[Any]							     =		os.path.join(
																					    _lowercase	,				weights_name.replace(""".bin"""	,				F'''-{len(_lowercase		)+1:05d}-of-???.bin'''		)		)
																					torch.save(_lowercase	,				_lowercase		)
																					sharded_state_dicts.append(expert_state.keys()		)
																					total_size += sum([value.numel() for key, value in expert_state.items()]		) * dtype_byte_size(
																					    expert_state[list(_lowercase		)[0]].dtype		)

    # Add the last block
							UpperCAmelCase     :		Optional[Any]							     =		os.path.join(_lowercase	,				weights_name.replace(""".bin"""	,				F'''-{len(_lowercase		)+1:05d}-of-???.bin'''		)		)
							UpperCAmelCase     :		Optional[int]							     =		torch.load(switch_checkpoint_path + """-shared.pt"""		)["""model"""]
							remove_ignore_keys_(_lowercase		)
							UpperCAmelCase     :		Optional[Any]							     =		rename_fairseq_keys(_lowercase	,				_lowercase		)
							UpperCAmelCase     :		int							     =		shared_weights["""decoder.embed_tokens.weight"""]
							sharded_state_dicts.append(shared_weights.keys()		)

							# If we only have the shared weights (dummy model/experts saved on the same file)
							if len(_lowercase		) == 1:
														UpperCAmelCase     :		Dict							     =		os.path.join(_lowercase	,				_lowercase		)
														torch.save(_lowercase	,				_lowercase		)
														return {weights_name: sharded_state_dicts[0]}, None
							else:
														torch.save(_lowercase	,				_lowercase		)
							# Otherwise, let's build the index
							UpperCAmelCase     :		Optional[int]							     =		{}
							for idx, shard in enumerate(_lowercase		):
														UpperCAmelCase     :		List[str]							     =		weights_name.replace(""".bin"""	,				F'''-{idx+1:05d}-of-{len(_lowercase		):05d}.bin'''		)
														UpperCAmelCase     :		List[str]							     =		os.path.join(_lowercase	,				weights_name.replace(""".bin"""	,				F'''-{idx+1:05d}-of-???.bin'''		)		)
														os.rename(_lowercase	,				os.path.join(_lowercase	,				_lowercase		)		)
														for key in shard:
																					UpperCAmelCase     :		Tuple							     =		shard_file

    # Add the metadata
							UpperCAmelCase     :		Any							     =		{"""total_size""": total_size}
							UpperCAmelCase     :		Optional[Any]							     =		{"""metadata""": metadata, """weight_map""": weight_map}

							with open(os.path.join(_lowercase	,				_lowercase		)	,				"""w"""	,				encoding="""utf-8"""		) as f:
														UpperCAmelCase     :		str							     =		json.dumps(_lowercase	,				indent=2	,				sort_keys=_lowercase		) + """\n"""
														f.write(_lowercase		)

							return metadata, index


if __name__ == "__main__":
							a   :			List[Any]					  =    argparse.ArgumentParser()
							# Required parameters
							parser.add_argument(
							    """--nllb_moe_checkpoint_path""",
							    default="""/home/arthur_huggingface_co/fairseq/weights/checkpoints/model_moe_54b/checkpoint_2_300000""",
							    type=str,
							    required=False,
							    help="""Path to a directory containing a folder per layer. Follows the original Google format.""",
							)
							parser.add_argument("""--dtype""", default="""float32""", type=str, required=False, help="""dtype of the saved model""")
							parser.add_argument(
							    """--pytorch_dump_folder_path""",
							    default="""/home/arthur_huggingface_co/fairseq/weights/checkpoints/hf-converted-moe-54b""",
							    type=str,
							    required=False,
							    help="""Path to the output pytorch model.""",
							)
							a   :			int					  =    parser.parse_args()
							a  ,      a   :			Any					  =    shard_on_the_fly(
							    args.nllb_moe_checkpoint_path,
							    args.pytorch_dump_folder_path,
							    1_2_8,
							    args.dtype,
							)

							a   :			str					  =    NllbMoeConfig.from_pretrained(
							    """facebook/nllb-200-3.3B""", encoder_sparse_step=4, decoder_sparse_step=4, num_experts=1_2_8
							)
							config.save_pretrained(args.pytorch_dump_folder_path)
							a   :			Optional[int]					  =    NllbMoeModel.from_pretrained(args.pytorch_dump_folder_path)
							print("""Done""")
							model.save_pretrained(args.pytorch_dump_folder_path)

