


'''simple docstring'''


from collections import Counter
from pathlib import Path
from typing import Optional, Tuple

import yaml






class 		lowerCAmelCase__	(	yaml.SafeLoader		):




			def 							lowerCAmelCase__			(						self     :   List[Any]		,     lowerCamelCase__     :   int       )      ->int:



					'''simple docstring'''







					_UpperCAmelCase						:				List[str]	    =					[self.constructed_objects[key_node] for key_node, _ in node.value]
					_UpperCAmelCase						:				List[str]	    =					[tuple(lowerCamelCase__       ) if isinstance(lowerCamelCase__		,     lowerCamelCase__       ) else key for key in keys]
					_UpperCAmelCase						:				Optional[Any]	    =					Counter(lowerCamelCase__       )
					_UpperCAmelCase						:				int	    =					[key for key in counter if counter[key] > 1]
					if duplicate_keys:
							raise TypeError(F"""Got duplicate yaml keys: {duplicate_keys}"""       )






			def 							lowerCAmelCase__			(						self     :   Optional[int]		,     lowerCamelCase__     :   Tuple		,     lowerCamelCase__     :   Dict=False       )      ->List[str]:



					'''simple docstring'''







					_UpperCAmelCase						:				Optional[int]	    =					super().construct_mapping(lowerCamelCase__		,     deep=lowerCamelCase__       )
					self._check_no_duplicates_on_constructed_node(lowerCamelCase__       )
					return mapping






def        __lowerCAmelCase       (__lowerCAmelCase      ):
		_UpperCAmelCase						:				Optional[int]	    =					list(readme_content.splitlines()      )
		if full_content and full_content[0] == "---" and "---" in full_content[1:]:
				_UpperCAmelCase						:				Any	    =					full_content[1:].index("---"      ) + 1
				_UpperCAmelCase						:				Any	    =					"\n".join(full_content[1:sep_idx]      )
				return yamlblock, "\n".join(full_content[sep_idx + 1 :]      )

		return None, "\n".join(__lowerCAmelCase      )






class 		lowerCAmelCase__	(	UpperCAmelCase__		):
			# class attributes
			lowerCAmelCase       :		List[Any]				      =   {"train_eval_index"}  # train-eval-index in the YAML metadata




			@classmethod
			def 							lowerCAmelCase__			(						cls     :   str		,     lowerCamelCase__     :   Path       )      ->"DatasetMetadata":



					'''simple docstring'''







					with open(lowerCamelCase__		,     encoding="utf-8"       ) as readme_file:
							_UpperCAmelCase    ,			_UpperCAmelCase						:				List[Any]	    =					_split_yaml_from_readme(readme_file.read()       )
					if yaml_string is not None:
							return cls.from_yaml_string(lowerCamelCase__       )
					else:
							return cls()




			def 							lowerCAmelCase__			(						self     :   Optional[int]		,     lowerCamelCase__     :   Path       )      ->Dict:



					'''simple docstring'''







					if path.exists():
							with open(lowerCamelCase__		,     encoding="utf-8"       ) as readme_file:
									_UpperCAmelCase						:				Tuple	    =					readme_file.read()
					else:
							_UpperCAmelCase						:				List[str]	    =					None
					_UpperCAmelCase						:				Optional[Any]	    =					self._to_readme(lowerCamelCase__       )
					with open(lowerCamelCase__		,     "w"		,     encoding="utf-8"       ) as readme_file:
							readme_file.write(lowerCamelCase__       )




			def 							lowerCAmelCase__			(						self     :   List[Any]		,     lowerCamelCase__     :   Optional[str] = None       )      ->str:



					'''simple docstring'''







					if readme_content is not None:
							_UpperCAmelCase    ,			_UpperCAmelCase						:				List[str]	    =					_split_yaml_from_readme(lowerCamelCase__       )
							_UpperCAmelCase						:				int	    =					"---\n" + self.to_yaml_string() + "---\n" + content
					else:
							_UpperCAmelCase						:				Dict	    =					"---\n" + self.to_yaml_string() + "---\n"
					return full_content




			@classmethod
			def 							lowerCAmelCase__			(						cls     :   Dict		,     lowerCamelCase__     :   str       )      ->"DatasetMetadata":



					'''simple docstring'''







					_UpperCAmelCase						:				int	    =					yaml.load(lowerCamelCase__		,     Loader=_NoDuplicateSafeLoader       ) or {}

					# Convert the YAML keys to DatasetMetadata fields
					_UpperCAmelCase						:				Optional[Any]	    =					{
					    (key.replace("-"		,     "_"       ) if key.replace("-"		,     "_"       ) in cls._FIELDS_WITH_DASHES else key): value
					    for key, value in metadata_dict.items()
					}
					return cls(**lowerCamelCase__       )






			def 							lowerCAmelCase__			(						self     :   Optional[Any]       )      ->str:



					'''simple docstring'''







					return yaml.safe_dump(
					    {
					        (key.replace("_"		,     "-"       ) if key in self._FIELDS_WITH_DASHES else key): value
					        for key, value in self.items()
					    }		,     sort_keys=lowerCamelCase__		,     allow_unicode=lowerCamelCase__		,     encoding="utf-8"		,     ).decode("utf-8"       )




lowerCamelCase__					=   {
    'image-classification': [],
    'translation': [],
    'image-segmentation': [],
    'fill-mask': [],
    'automatic-speech-recognition': [],
    'token-classification': [],
    'sentence-similarity': [],
    'audio-classification': [],
    'question-answering': [],
    'summarization': [],
    'zero-shot-classification': [],
    'table-to-text': [],
    'feature-extraction': [],
    'other': [],
    'multiple-choice': [],
    'text-classification': [],
    'text-to-image': [],
    'text2text-generation': [],
    'zero-shot-image-classification': [],
    'tabular-classification': [],
    'tabular-regression': [],
    'image-to-image': [],
    'tabular-to-text': [],
    'unconditional-image-generation': [],
    'text-retrieval': [],
    'text-to-speech': [],
    'object-detection': [],
    'audio-to-audio': [],
    'text-generation': [],
    'conversational': [],
    'table-question-answering': [],
    'visual-question-answering': [],
    'image-to-text': [],
    'reinforcement-learning': [],
    'voice-activity-detection': [],
    'time-series-forecasting': [],
    'document-question-answering': [],
}


if __name__ == "__main__":
						from argparse import ArgumentParser

						lowerCamelCase__					=   ArgumentParser(usage='Validate the yaml metadata block of a README.md file.')
						ap.add_argument('readme_filepath')
						lowerCamelCase__					=   ap.parse_args()

						lowerCamelCase__					=   Path(args.readme_filepath)
						lowerCamelCase__					=   DatasetMetadata.from_readme(readme_filepath)
						print(dataset_metadata)
						dataset_metadata.to_readme(readme_filepath)







'''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       (__lowerCAmelCase      ):
		_UpperCAmelCase						:				List[str]	    =					[
		    "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(__lowerCAmelCase					,       __lowerCAmelCase      )






def        __lowerCAmelCase       (__lowerCAmelCase      ):
		_UpperCAmelCase    ,			_UpperCAmelCase						:				Optional[Any]	    =					emb.weight.shape
		_UpperCAmelCase						:				str	    =					nn.Linear(__lowerCAmelCase					,       __lowerCAmelCase					,       bias=__lowerCAmelCase      )
		_UpperCAmelCase						:				Optional[int]	    =					emb.weight.data
		return lin_layer






def        __lowerCAmelCase       (__lowerCAmelCase					,       __lowerCAmelCase=None      ):
		_UpperCAmelCase						:				int	    =					{}
		for old_key in state_dict.keys():
				_UpperCAmelCase						:				Tuple	    =					old_key
				if "moe_layer.experts." in key:
						if expert_idx is not None:
								_UpperCAmelCase						:				Optional[int]	    =					key.replace("moe_layer.experts.0"					,       F"""ffn.experts.expert_{expert_idx}"""      )
						else:
								_UpperCAmelCase						:				Any	    =					key.replace("moe_layer.experts."					,       "ffn.experts.expert_"      )
				if "gate" in key:
						_UpperCAmelCase						:				List[Any]	    =					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						:				List[Any]	    =					key.replace(".encoder_attn."					,       ".cross_attention."      )
				if "encoder_attn_layer_norm" in key:
						_UpperCAmelCase						:				Any	    =					key.replace("encoder_attn_layer_norm"					,       "cross_attention_layer_norm"      )
				if "final_layer_norm" in key:
						_UpperCAmelCase						:				int	    =					key.replace("final_layer_norm"					,       "ff_layer_norm"      )
				_UpperCAmelCase						:				Tuple	    =					state_dict[old_key]
		return new_dict






def        __lowerCAmelCase       (__lowerCAmelCase					,       __lowerCAmelCase					,       __lowerCAmelCase					,       __lowerCAmelCase					,       __lowerCAmelCase = WEIGHTS_NAME      ):
		_UpperCAmelCase						:				Optional[int]	    =					[]
		_UpperCAmelCase						:				Optional[Any]	    =					0
		os.makedirs(__lowerCAmelCase					,       exist_ok=__lowerCAmelCase      )

		for expert in range(__lowerCAmelCase      ):
				_UpperCAmelCase						:				Tuple	    =					switch_checkpoint_path + F"""-rank-{expert}.pt"""
				if os.path.isfile(__lowerCAmelCase      ):
						_UpperCAmelCase						:				Tuple	    =					torch.load(__lowerCAmelCase      )["model"]
						remove_ignore_keys_(__lowerCAmelCase      )
						_UpperCAmelCase						:				Dict	    =					rename_fairseq_keys(__lowerCAmelCase					,       __lowerCAmelCase      )
						_UpperCAmelCase						:				List[str]	    =					os.path.join(
						    __lowerCAmelCase					,       weights_name.replace(".bin"					,       F"""-{len(__lowerCAmelCase      )+1:05d}-of-???.bin"""      )      )
						torch.save(__lowerCAmelCase					,       __lowerCAmelCase      )
						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(__lowerCAmelCase      )[0]].dtype      )

    # Add the last block
		_UpperCAmelCase						:				Tuple	    =					os.path.join(__lowerCAmelCase					,       weights_name.replace(".bin"					,       F"""-{len(__lowerCAmelCase      )+1:05d}-of-???.bin"""      )      )
		_UpperCAmelCase						:				Union[str, Any]	    =					torch.load(switch_checkpoint_path + "-shared.pt"      )["model"]
		remove_ignore_keys_(__lowerCAmelCase      )
		_UpperCAmelCase						:				Union[str, Any]	    =					rename_fairseq_keys(__lowerCAmelCase					,       __lowerCAmelCase      )
		_UpperCAmelCase						:				Any	    =					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(__lowerCAmelCase      ) == 1:
				_UpperCAmelCase						:				List[str]	    =					os.path.join(__lowerCAmelCase					,       __lowerCAmelCase      )
				torch.save(__lowerCAmelCase					,       __lowerCAmelCase      )
				return {weights_name: sharded_state_dicts[0]}, None
		else:
				torch.save(__lowerCAmelCase					,       __lowerCAmelCase      )
		# Otherwise, let's build the index
		_UpperCAmelCase						:				Union[str, Any]	    =					{}
		for idx, shard in enumerate(__lowerCAmelCase      ):
				_UpperCAmelCase						:				Tuple	    =					weights_name.replace(".bin"					,       F"""-{idx+1:05d}-of-{len(__lowerCAmelCase      ):05d}.bin"""      )
				_UpperCAmelCase						:				List[Any]	    =					os.path.join(__lowerCAmelCase					,       weights_name.replace(".bin"					,       F"""-{idx+1:05d}-of-???.bin"""      )      )
				os.rename(__lowerCAmelCase					,       os.path.join(__lowerCAmelCase					,       __lowerCAmelCase      )      )
				for key in shard:
						_UpperCAmelCase						:				List[Any]	    =					shard_file

    # Add the metadata
		_UpperCAmelCase						:				Any	    =					{"total_size": total_size}
		_UpperCAmelCase						:				List[str]	    =					{"metadata": metadata, "weight_map": weight_map}

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

		return metadata, index


if __name__ == "__main__":
						lowerCamelCase__					=   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.',
						)
						lowerCamelCase__					=   parser.parse_args()
						lowerCamelCase__		,lowerCamelCase__					=   shard_on_the_fly(
						    args.nllb_moe_checkpoint_path,
						    args.pytorch_dump_folder_path,
						    128,
						    args.dtype,
						)

						lowerCamelCase__					=   NllbMoeConfig.from_pretrained(
						    'facebook/nllb-200-3.3B', encoder_sparse_step=4, decoder_sparse_step=4, num_experts=128
						)
						config.save_pretrained(args.pytorch_dump_folder_path)
						lowerCamelCase__					=   NllbMoeModel.from_pretrained(args.pytorch_dump_folder_path)
						print('Done')
						model.save_pretrained(args.pytorch_dump_folder_path)



