



'''simple docstring'''




import gc
import random
import tempfile
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel
from diffusers.pipelines.stable_diffusion_safe import StableDiffusionPipelineSafe as StableDiffusionPipeline
from diffusers.utils import floats_tensor, nightly, torch_device
from diffusers.utils.testing_utils import require_torch_gpu

class 			UpperCamelCase_ (							unittest.TestCase			):





	def  _lowercase(  self    )			->			int:
								# clean up the VRAM after each test
								super().tearDown()
								gc.collect()
								torch.cuda.empty_cache()





	@property
	def  _lowercase(  self    )			->			List[str]:
								UpperCAmelCase     :		int							     =		1
								UpperCAmelCase     :		Dict							     =		3
								UpperCAmelCase     :		Dict							     =		(32, 32)

								UpperCAmelCase     :		Tuple							     =		floats_tensor((batch_size, num_channels) + sizes		,		rng=random.Random(0    )    ).to(A    )
								return image





	@property
	def  _lowercase(  self    )			->			Dict:
								torch.manual_seed(0    )
								UpperCAmelCase     :		Tuple							     =		UNetaDConditionModel(
								    block_out_channels=(32, 64)		,		layers_per_block=2		,		sample_size=32		,		in_channels=4		,		out_channels=4		,		down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")		,		up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""")		,		cross_attention_dim=32		,		)
								return model





	@property
	def  _lowercase(  self    )			->			Union[str, Any]:
								torch.manual_seed(0    )
								UpperCAmelCase     :		Dict							     =		AutoencoderKL(
								    block_out_channels=[32, 64]		,		in_channels=3		,		out_channels=3		,		down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""]		,		up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""]		,		latent_channels=4		,		)
								return model





	@property
	def  _lowercase(  self    )			->			Any:
								torch.manual_seed(0    )
								UpperCAmelCase     :		int							     =		CLIPTextConfig(
								    bos_token_id=0		,		eos_token_id=2		,		hidden_size=32		,		intermediate_size=37		,		layer_norm_eps=1e-05		,		num_attention_heads=4		,		num_hidden_layers=5		,		pad_token_id=1		,		vocab_size=1000		,		)
								return CLIPTextModel(A    )





	@property
	def  _lowercase(  self    )			->			Dict:
								def extract(*A		,		**A    ):

															class 			UpperCamelCase_ :





																def __init__(  self    )			->			Optional[Any]:
																							UpperCAmelCase     :		str							     =		torch.ones([0]    )






																def  _lowercase(  self		,		A    )			->			int:
																							self.pixel_values.to(A    )
																							return self




															return Out()

								return extract





	def  _lowercase(  self    )			->			str:
								UpperCAmelCase     :		Optional[int]							     =		"""cpu"""  # ensure determinism for the device-dependent torch.Generator
								UpperCAmelCase     :		Any							     =		self.dummy_cond_unet
								UpperCAmelCase     :		Tuple							     =		DDIMScheduler(
								    beta_start=0.0_0_0_8_5		,		beta_end=0.0_1_2		,		beta_schedule="""scaled_linear"""		,		clip_sample=A		,		set_alpha_to_one=A		,		)

								UpperCAmelCase     :		List[Any]							     =		self.dummy_vae
								UpperCAmelCase     :		Union[str, Any]							     =		self.dummy_text_encoder
								UpperCAmelCase     :		Optional[int]							     =		CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""    )

								# make sure here that pndm scheduler skips prk
								UpperCAmelCase     :		int							     =		StableDiffusionPipeline(
								    unet=A		,		scheduler=A		,		vae=A		,		text_encoder=A		,		tokenizer=A		,		safety_checker=A		,		feature_extractor=self.dummy_extractor		,		)
								UpperCAmelCase     :		Tuple							     =		sd_pipe.to(A    )
								sd_pipe.set_progress_bar_config(disable=A    )

								UpperCAmelCase     :		List[str]							     =		"""A painting of a squirrel eating a burger"""

								UpperCAmelCase     :		Any							     =		torch.Generator(device=A    ).manual_seed(0    )
								UpperCAmelCase     :		Tuple							     =		sd_pipe([prompt]		,		generator=A		,		guidance_scale=6.0		,		num_inference_steps=2		,		output_type="""np"""    )
								UpperCAmelCase     :		Union[str, Any]							     =		output.images

								UpperCAmelCase     :		Union[str, Any]							     =		torch.Generator(device=A    ).manual_seed(0    )
								UpperCAmelCase     :		int							     =		sd_pipe(
								    [prompt]		,		generator=A		,		guidance_scale=6.0		,		num_inference_steps=2		,		output_type="""np"""		,		return_dict=A		,		)[0]

								UpperCAmelCase     :		Any							     =		image[0, -3:, -3:, -1]
								UpperCAmelCase     :		Optional[int]							     =		image_from_tuple[0, -3:, -3:, -1]

								assert image.shape == (1, 64, 64, 3)
								UpperCAmelCase     :		Optional[Any]							     =		np.array([0.5_7_5_6, 0.6_1_1_8, 0.5_0_0_5, 0.5_0_4_1, 0.5_4_7_1, 0.4_7_2_6, 0.4_9_7_6, 0.4_8_6_5, 0.4_8_6_4]    )

								assert np.abs(image_slice.flatten() - expected_slice    ).max() < 1e-2
								assert np.abs(image_from_tuple_slice.flatten() - expected_slice    ).max() < 1e-2





	def  _lowercase(  self    )			->			Dict:
								UpperCAmelCase     :		Union[str, Any]							     =		"""cpu"""  # ensure determinism for the device-dependent torch.Generator
								UpperCAmelCase     :		Any							     =		self.dummy_cond_unet
								UpperCAmelCase     :		Dict							     =		PNDMScheduler(skip_prk_steps=A    )
								UpperCAmelCase     :		Union[str, Any]							     =		self.dummy_vae
								UpperCAmelCase     :		Any							     =		self.dummy_text_encoder
								UpperCAmelCase     :		int							     =		CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""    )

								# make sure here that pndm scheduler skips prk
								UpperCAmelCase     :		Tuple							     =		StableDiffusionPipeline(
								    unet=A		,		scheduler=A		,		vae=A		,		text_encoder=A		,		tokenizer=A		,		safety_checker=A		,		feature_extractor=self.dummy_extractor		,		)
								UpperCAmelCase     :		Union[str, Any]							     =		sd_pipe.to(A    )
								sd_pipe.set_progress_bar_config(disable=A    )

								UpperCAmelCase     :		Any							     =		"""A painting of a squirrel eating a burger"""
								UpperCAmelCase     :		int							     =		torch.Generator(device=A    ).manual_seed(0    )
								UpperCAmelCase     :		Dict							     =		sd_pipe([prompt]		,		generator=A		,		guidance_scale=6.0		,		num_inference_steps=2		,		output_type="""np"""    )

								UpperCAmelCase     :		Optional[Any]							     =		output.images

								UpperCAmelCase     :		List[str]							     =		torch.Generator(device=A    ).manual_seed(0    )
								UpperCAmelCase     :		List[Any]							     =		sd_pipe(
								    [prompt]		,		generator=A		,		guidance_scale=6.0		,		num_inference_steps=2		,		output_type="""np"""		,		return_dict=A		,		)[0]

								UpperCAmelCase     :		Tuple							     =		image[0, -3:, -3:, -1]
								UpperCAmelCase     :		List[Any]							     =		image_from_tuple[0, -3:, -3:, -1]

								assert image.shape == (1, 64, 64, 3)
								UpperCAmelCase     :		Optional[Any]							     =		np.array([0.5_1_2_5, 0.5_7_1_6, 0.4_8_2_8, 0.5_0_6_0, 0.5_6_5_0, 0.4_7_6_8, 0.5_1_8_5, 0.4_8_9_5, 0.4_9_9_3]    )

								assert np.abs(image_slice.flatten() - expected_slice    ).max() < 1e-2
								assert np.abs(image_from_tuple_slice.flatten() - expected_slice    ).max() < 1e-2





	def  _lowercase(  self    )			->			Optional[int]:
								UpperCAmelCase     :		Any							     =		StableDiffusionPipeline.from_pretrained(
								    """hf-internal-testing/tiny-stable-diffusion-lms-pipe"""		,		safety_checker=A    )
								assert isinstance(A		,		A    )
								assert isinstance(pipe.scheduler		,		A    )
								assert pipe.safety_checker is None

								UpperCAmelCase     :		Optional[int]							     =		pipe("""example prompt"""		,		num_inference_steps=2    ).images[0]
								assert image is not None

								# check that there's no error when saving a pipeline with one of the models being None
								with tempfile.TemporaryDirectory() as tmpdirname:
															pipe.save_pretrained(A    )
															UpperCAmelCase     :		Optional[int]							     =		StableDiffusionPipeline.from_pretrained(A    )

								# sanity check that the pipeline still works
								assert pipe.safety_checker is None
								UpperCAmelCase     :		Tuple							     =		pipe("""example prompt"""		,		num_inference_steps=2    ).images[0]
								assert image is not None






	@unittest.skipIf(torch_device != """cuda"""		,		"""This test requires a GPU"""    )
	def  _lowercase(  self    )			->			List[Any]:
								UpperCAmelCase     :		Optional[int]							     =		self.dummy_cond_unet
								UpperCAmelCase     :		List[Any]							     =		PNDMScheduler(skip_prk_steps=A    )
								UpperCAmelCase     :		Optional[Any]							     =		self.dummy_vae
								UpperCAmelCase     :		int							     =		self.dummy_text_encoder
								UpperCAmelCase     :		int							     =		CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""    )

								# put models in fp16
								UpperCAmelCase     :		List[str]							     =		unet.half()
								UpperCAmelCase     :		Optional[int]							     =		vae.half()
								UpperCAmelCase     :		int							     =		bert.half()

								# make sure here that pndm scheduler skips prk
								UpperCAmelCase     :		List[str]							     =		StableDiffusionPipeline(
								    unet=A		,		scheduler=A		,		vae=A		,		text_encoder=A		,		tokenizer=A		,		safety_checker=A		,		feature_extractor=self.dummy_extractor		,		)
								UpperCAmelCase     :		List[Any]							     =		sd_pipe.to(A    )
								sd_pipe.set_progress_bar_config(disable=A    )

								UpperCAmelCase     :		Any							     =		"""A painting of a squirrel eating a burger"""
								UpperCAmelCase     :		Tuple							     =		sd_pipe([prompt]		,		num_inference_steps=2		,		output_type="""np"""    ).images

								assert image.shape == (1, 64, 64, 3)




@nightly
@require_torch_gpu
class 			UpperCamelCase_ (							unittest.TestCase			):





	def  _lowercase(  self    )			->			Union[str, Any]:
								# clean up the VRAM after each test
								super().tearDown()
								gc.collect()
								torch.cuda.empty_cache()





	def  _lowercase(  self    )			->			int:
								UpperCAmelCase     :		Optional[Any]							     =		StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5"""		,		safety_checker=A    )
								UpperCAmelCase     :		str							     =		LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config    )
								UpperCAmelCase     :		Tuple							     =		sd_pipe.to(A    )
								sd_pipe.set_progress_bar_config(disable=A    )

								UpperCAmelCase     :		str							     =		(
								    """portrait of girl with smokey eyes makeup in abandoned hotel, grange clothes, redshift, wide high angle"""
								    """ coloured polaroid photograph with flash, kodak film, hyper real, stunning moody cinematography, with"""
								    """ anamorphic lenses, by maripol, fallen angels by wong kar - wai, style of suspiria and neon demon and"""
								    """ children from bahnhof zoo, detailed """
								)
								UpperCAmelCase     :		Dict							     =		4003660346
								UpperCAmelCase     :		Any							     =		7

								# without safety guidance (sld_guidance_scale = 0)
								UpperCAmelCase     :		int							     =		torch.manual_seed(A    )
								UpperCAmelCase     :		Optional[Any]							     =		sd_pipe(
								    [prompt]		,		generator=A		,		guidance_scale=A		,		num_inference_steps=50		,		output_type="""np"""		,		width=512		,		height=512		,		sld_guidance_scale=0		,		)

								UpperCAmelCase     :		Any							     =		output.images
								UpperCAmelCase     :		str							     =		image[0, -3:, -3:, -1]
								UpperCAmelCase     :		Tuple							     =		[0.2_2_7_8, 0.2_2_3_1, 0.2_2_4_9, 0.2_3_3_3, 0.2_3_0_3, 0.1_8_8_5, 0.2_2_7_3, 0.2_1_4_4, 0.2_1_7_6]

								assert image.shape == (1, 512, 512, 3)

								assert np.abs(image_slice.flatten() - expected_slice    ).max() < 1e-2

								# without safety guidance (strong configuration)
								UpperCAmelCase     :		List[Any]							     =		torch.manual_seed(A    )
								UpperCAmelCase     :		str							     =		sd_pipe(
								    [prompt]		,		generator=A		,		guidance_scale=A		,		num_inference_steps=50		,		output_type="""np"""		,		width=512		,		height=512		,		sld_guidance_scale=2000		,		sld_warmup_steps=7		,		sld_threshold=0.0_2_5		,		sld_momentum_scale=0.5		,		sld_mom_beta=0.7		,		)

								UpperCAmelCase     :		str							     =		output.images
								UpperCAmelCase     :		Any							     =		image[0, -3:, -3:, -1]
								UpperCAmelCase     :		str							     =		[0.2_3_8_3, 0.2_2_7_6, 0.2_3_6, 0.2_1_9_2, 0.2_1_8_6, 0.2_0_5_3, 0.1_9_7_1, 0.1_9_0_1, 0.1_7_1_9]

								assert image.shape == (1, 512, 512, 3)

								assert np.abs(image_slice.flatten() - expected_slice    ).max() < 1e-2





	def  _lowercase(  self    )			->			List[Any]:
								UpperCAmelCase     :		Optional[Any]							     =		StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5"""		,		safety_checker=A    )
								UpperCAmelCase     :		int							     =		LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config    )
								UpperCAmelCase     :		Optional[Any]							     =		sd_pipe.to(A    )
								sd_pipe.set_progress_bar_config(disable=A    )

								UpperCAmelCase     :		Union[str, Any]							     =		"""padme amidala taking a bath artwork, safe for work, no nudity"""
								UpperCAmelCase     :		Union[str, Any]							     =		2734971755
								UpperCAmelCase     :		Optional[Any]							     =		7

								UpperCAmelCase     :		List[Any]							     =		torch.manual_seed(A    )
								UpperCAmelCase     :		List[str]							     =		sd_pipe(
								    [prompt]		,		generator=A		,		guidance_scale=A		,		num_inference_steps=50		,		output_type="""np"""		,		width=512		,		height=512		,		sld_guidance_scale=0		,		)

								UpperCAmelCase     :		int							     =		output.images
								UpperCAmelCase     :		Optional[Any]							     =		image[0, -3:, -3:, -1]
								UpperCAmelCase     :		Optional[int]							     =		[0.3_5_0_2, 0.3_6_2_2, 0.3_3_9_6, 0.3_6_4_2, 0.3_4_7_8, 0.3_3_1_8, 0.3_5, 0.3_3_4_8, 0.3_2_9_7]

								assert image.shape == (1, 512, 512, 3)

								assert np.abs(image_slice.flatten() - expected_slice    ).max() < 1e-2

								UpperCAmelCase     :		Dict							     =		torch.manual_seed(A    )
								UpperCAmelCase     :		str							     =		sd_pipe(
								    [prompt]		,		generator=A		,		guidance_scale=A		,		num_inference_steps=50		,		output_type="""np"""		,		width=512		,		height=512		,		sld_guidance_scale=2000		,		sld_warmup_steps=7		,		sld_threshold=0.0_2_5		,		sld_momentum_scale=0.5		,		sld_mom_beta=0.7		,		)

								UpperCAmelCase     :		List[Any]							     =		output.images
								UpperCAmelCase     :		int							     =		image[0, -3:, -3:, -1]
								UpperCAmelCase     :		Union[str, Any]							     =		[0.5_5_3_1, 0.5_2_0_6, 0.4_8_9_5, 0.5_1_5_6, 0.5_1_8_2, 0.4_7_5_1, 0.4_8_0_2, 0.4_8_0_3, 0.4_4_4_3]

								assert image.shape == (1, 512, 512, 3)

								assert np.abs(image_slice.flatten() - expected_slice    ).max() < 1e-2






	def  _lowercase(  self    )			->			Union[str, Any]:
								UpperCAmelCase     :		str							     =		StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5"""    )
								UpperCAmelCase     :		str							     =		sd_pipe.to(A    )
								sd_pipe.set_progress_bar_config(disable=A    )

								UpperCAmelCase     :		Optional[int]							     =		(
								    """the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c."""
								    """ leyendecker"""
								)
								UpperCAmelCase     :		Tuple							     =		1044355234
								UpperCAmelCase     :		int							     =		12

								UpperCAmelCase     :		Optional[Any]							     =		torch.manual_seed(A    )
								UpperCAmelCase     :		Tuple							     =		sd_pipe(
								    [prompt]		,		generator=A		,		guidance_scale=A		,		num_inference_steps=50		,		output_type="""np"""		,		width=512		,		height=512		,		sld_guidance_scale=0		,		)

								UpperCAmelCase     :		Tuple							     =		output.images
								UpperCAmelCase     :		Optional[int]							     =		image[0, -3:, -3:, -1]
								UpperCAmelCase     :		Tuple							     =		np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]    )

								assert image.shape == (1, 512, 512, 3)

								assert np.abs(image_slice.flatten() - expected_slice    ).max() < 1e-7

								UpperCAmelCase     :		int							     =		torch.manual_seed(A    )
								UpperCAmelCase     :		str							     =		sd_pipe(
								    [prompt]		,		generator=A		,		guidance_scale=A		,		num_inference_steps=50		,		output_type="""np"""		,		width=512		,		height=512		,		sld_guidance_scale=2000		,		sld_warmup_steps=7		,		sld_threshold=0.0_2_5		,		sld_momentum_scale=0.5		,		sld_mom_beta=0.7		,		)

								UpperCAmelCase     :		Optional[Any]							     =		output.images
								UpperCAmelCase     :		int							     =		image[0, -3:, -3:, -1]
								UpperCAmelCase     :		Dict							     =		np.array([0.5_8_1_8, 0.6_2_8_5, 0.6_8_3_5, 0.6_0_1_9, 0.6_2_5, 0.6_7_5_4, 0.6_0_9_6, 0.6_3_3_4, 0.6_5_6_1]    )
								assert image.shape == (1, 512, 512, 3)

								assert np.abs(image_slice.flatten() - expected_slice    ).max() < 1e-2






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

