


'''simple docstring'''






import functools
import operator

from ...configuration_utils import PretrainedConfig
from ...utils import logging


__UpperCAmelCase       =							logging.get_logger(__name__)

__UpperCAmelCase       =							{
    '''asapp/sew-tiny-100k''': '''https://huggingface.co/asapp/sew-tiny-100k/resolve/main/config.json''',
    # See all SEW models at https://huggingface.co/models?filter=sew
}




class 		a__    (							a__  ):





							'''simple docstring'''






							lowercase__      :       Dict     						=				"sew"







							def __init__(		self ,   lowerCamelCase_=32 ,   lowerCamelCase_=7_68 ,   lowerCamelCase_=12 ,   lowerCamelCase_=12 ,   lowerCamelCase_=30_72 ,   lowerCamelCase_=2 ,   lowerCamelCase_="gelu" ,   lowerCamelCase_=0.1 ,   lowerCamelCase_=0.1 ,   lowerCamelCase_=0.1 ,   lowerCamelCase_=0.0 ,   lowerCamelCase_=0.1 ,   lowerCamelCase_=0.1 ,   lowerCamelCase_=0.02 ,   lowerCamelCase_=1e-5 ,   lowerCamelCase_="group" ,   lowerCamelCase_="gelu" ,   lowerCamelCase_=(64, 1_28, 1_28, 1_28, 1_28, 2_56, 2_56, 2_56, 2_56, 5_12, 5_12, 5_12, 5_12) ,   lowerCamelCase_=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) ,   lowerCamelCase_=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) ,   lowerCamelCase_=False ,   lowerCamelCase_=1_28 ,   lowerCamelCase_=16 ,   lowerCamelCase_=True ,   lowerCamelCase_=0.05 ,   lowerCamelCase_=10 ,   lowerCamelCase_=2 ,   lowerCamelCase_=0.0 ,   lowerCamelCase_=10 ,   lowerCamelCase_=0 ,   lowerCamelCase_="mean" ,   lowerCamelCase_=False ,   lowerCamelCase_=False ,   lowerCamelCase_=2_56 ,   lowerCamelCase_=0 ,   lowerCamelCase_=1 ,   lowerCamelCase_=2 ,   **lowerCamelCase_ ,   )	->							List[Any]:
														super().__init__(**lowerCamelCase_ ,   pad_token_id=lowerCamelCase_ ,   bos_token_id=lowerCamelCase_ ,   eos_token_id=lowerCamelCase_       )
														lowerCAmelCase__	       =     hidden_size
														lowerCAmelCase__	       =     feat_extract_norm
														lowerCAmelCase__	       =     feat_extract_activation
														lowerCAmelCase__	       =     list(lowerCamelCase_       )
														lowerCAmelCase__	       =     list(lowerCamelCase_       )
														lowerCAmelCase__	       =     list(lowerCamelCase_       )
														lowerCAmelCase__	       =     conv_bias
														lowerCAmelCase__	       =     num_conv_pos_embeddings
														lowerCAmelCase__	       =     num_conv_pos_embedding_groups
														lowerCAmelCase__	       =     len(self.conv_dim       )
														lowerCAmelCase__	       =     num_hidden_layers
														lowerCAmelCase__	       =     intermediate_size
														lowerCAmelCase__	       =     squeeze_factor
														lowerCAmelCase__	       =     hidden_act
														lowerCAmelCase__	       =     num_attention_heads
														lowerCAmelCase__	       =     hidden_dropout
														lowerCAmelCase__	       =     attention_dropout
														lowerCAmelCase__	       =     activation_dropout
														lowerCAmelCase__	       =     feat_proj_dropout
														lowerCAmelCase__	       =     final_dropout
														lowerCAmelCase__	       =     layerdrop
														lowerCAmelCase__	       =     layer_norm_eps
														lowerCAmelCase__	       =     initializer_range
														lowerCAmelCase__	       =     vocab_size

														if (
														    (len(self.conv_stride       ) != self.num_feat_extract_layers)
														    or (len(self.conv_kernel       ) != self.num_feat_extract_layers)
														    or (len(self.conv_dim       ) != self.num_feat_extract_layers)
														):
																					raise ValueError(
																					    '''Configuration for convolutional layers is incorrect.'''
																					    '''It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,'''
																					    F"""but is `len(config.conv_dim) = {len(self.conv_dim       )}`, `len(config.conv_stride)"""
																					    F"""= {len(self.conv_stride       )}`, `len(config.conv_kernel) = {len(self.conv_kernel       )}`."""       )

														# fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
														lowerCAmelCase__	       =     apply_spec_augment
														lowerCAmelCase__	       =     mask_time_prob
														lowerCAmelCase__	       =     mask_time_length
														lowerCAmelCase__	       =     mask_time_min_masks
														lowerCAmelCase__	       =     mask_feature_prob
														lowerCAmelCase__	       =     mask_feature_length
														lowerCAmelCase__	       =     mask_feature_min_masks

														# ctc loss
														lowerCAmelCase__	       =     ctc_loss_reduction
														lowerCAmelCase__	       =     ctc_zero_infinity

														# sequence classification
														lowerCAmelCase__	       =     use_weighted_layer_sum
														lowerCAmelCase__	       =     classifier_proj_size







							@property
							def   __SCREAMING_SNAKE_CASE							(		self       )	->							Dict:
														return functools.reduce(operator.mul ,   self.conv_stride ,   1       )



'''simple docstring'''






import argparse
import json
import os
import re

import torch

from transformers import BloomConfig, BloomModel
from transformers.file_utils import CONFIG_NAME, WEIGHTS_NAME
from transformers.utils import logging


logging.set_verbosity_info()

__UpperCAmelCase       =							[
    '''word_embeddings_layernorm.weight''',
    '''word_embeddings_layernorm.bias''',
    '''input_layernorm.weight''',
    '''input_layernorm.bias''',
    '''post_attention_layernorm.weight''',
    '''post_attention_layernorm.bias''',
    '''self_attention.dense.bias''',
    '''mlp.dense_4h_to_h.bias''',
    '''ln_f.weight''',
    '''ln_f.bias''',
]

__UpperCAmelCase       =							[
    '''mlp.dense_4h_to_h.weight''',
    '''self_attention.dense.weight''',
]


def  _snake_case       (					A			,   A	)						->   Optional[Any]:
							lowerCAmelCase__	       =     {
							    '''word_embeddings.weight''': '''word_embeddings.weight''',
							    '''word_embeddings.norm.weight''': '''word_embeddings_layernorm.weight''',
							    '''word_embeddings.norm.bias''': '''word_embeddings_layernorm.bias''',
							    '''weight''': '''ln_f.weight''',
							    '''bias''': '''ln_f.bias''',
							}

							if key in layer_rename_map:
														return layer_rename_map[key]

							# Handle transformer blocks
							lowerCAmelCase__	       =     int(re.match(R'''.*layer_(\d*).*'''			,   A	)[1]	)
							layer_number -= 3
							return F"""h.{layer_number}.""" + key


def  _snake_case       (					A	)						->   Optional[int]:
							if dtype == torch.bool:
														return 1 / 8
							lowerCAmelCase__	       =     re.search(R'''[^\d](\d+)$'''			,   str(A	)	)
							if bit_search is None:
														raise ValueError(F"""`dtype` is not a valid dtype: {dtype}."""	)
							lowerCAmelCase__	       =     int(bit_search.groups()[0]	)
							return bit_size // 8


def  _snake_case       (					A			,   A			,   A			,   A			,   A	)						->   Dict:
							# Construct model
							if bloom_config_file == "":
														lowerCAmelCase__	       =     BloomConfig()
							else:
														lowerCAmelCase__	       =     BloomConfig.from_json_file(A	)

							if shard_model:
														lowerCAmelCase__	       =     os.listdir(A	)
														lowerCAmelCase__	       =     sorted(filter(lambda A	: s.startswith('''layer'''	) and "model_00" in s			,   A	)	)

														lowerCAmelCase__	       =     {'''weight_map''': {}, '''metadata''': {}}
														lowerCAmelCase__	       =     0

														lowerCAmelCase__	       =     None

														lowerCAmelCase__	       =     BloomConfig()

														for j, file in enumerate(A	):
																					print('''Processing file: {}'''.format(A	)	)
																					lowerCAmelCase__	       =     None

																					for i in range(A	):
																												# load all TP files
																												lowerCAmelCase__	       =     file.replace('''model_00'''			,   F"""model_0{i}"""	)
																												lowerCAmelCase__	       =     torch.load(os.path.join(A			,   A	)			,   map_location='''cpu'''	)

																												# Rename keys in the transformers names
																												lowerCAmelCase__	       =     list(temp.keys()	)
																												for key in keys:
																																			lowerCAmelCase__	       =     temp.pop(A	)

																												if tensors is None:
																																			lowerCAmelCase__	       =     temp
																												else:
																																			for key in tensors.keys():
																																										if any(key.endswith(A	) for end in WEIGHTS_TO_AVERAGE_ENDSWITH	):
																																																	# We average (sum and then divide) some weights accross TP ranks (see https://github.com/bigscience-workshop/Megatron-DeepSpeed/blob/olruwase/sync_layer_norms/megatron/training.py#L425)
																																																	tensors[key] += temp[key]
																																										else:
																																																	# Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel
																																																	lowerCAmelCase__	       =     1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN	) else 0
																																																	# We concatenate these weights accross TP ranks
																																																	lowerCAmelCase__	       =     torch.cat([tensors[key], temp[key]]			,   dim=A	)

            # Divide by the number of TP the weights we want to average
																					for key in tensors.keys():
																												if any(key.endswith(A	) for end in WEIGHTS_TO_AVERAGE_ENDSWITH	):
																																			lowerCAmelCase__	       =     tensors[key] / pretraining_tp
																					torch.save(
																					    A			,   os.path.join(
																					        A			,   '''pytorch_model_{}-of-{}.bin'''.format(str(j + 1	).zfill(5	)			,   str(len(A	)	).zfill(5	)	)			,   )			,   )

																					for key in tensors.keys():
																												lowerCAmelCase__	       =     tensors[key]
																												total_size += value.numel() * get_dtype_size(value.dtype	)
																												if key not in index_dict["weight_map"]:
																																			lowerCAmelCase__	       =     '''pytorch_model_{}-of-{}.bin'''.format(
																																			    str(j + 1	).zfill(5	)			,   str(len(A	)	).zfill(5	)	)

														lowerCAmelCase__	       =     BloomConfig()
														lowerCAmelCase__	       =     pytorch_dump_folder_path + '''/''' + CONFIG_NAME
														lowerCAmelCase__	       =     total_size
														with open(A			,   '''w'''			,   encoding='''utf-8'''	) as f:
																					f.write(config.to_json_string()	)
														with open(os.path.join(A			,   WEIGHTS_NAME + '''.index.json'''	)			,   '''w'''			,   encoding='''utf-8'''	) as f:
																					lowerCAmelCase__	       =     json.dumps(A			,   indent=2			,   sort_keys=A	) + '''\n'''
																					f.write(A	)
							else:
														lowerCAmelCase__	       =     BloomModel(A	)

														lowerCAmelCase__	       =     os.listdir(A	)
														lowerCAmelCase__	       =     sorted(filter(lambda A	: s.startswith('''layer'''	) and "model_00" in s			,   A	)	)

														lowerCAmelCase__	       =     None
														for i, file in enumerate(A	):
																					lowerCAmelCase__	       =     None
																					for i in range(A	):
																												# load all TP files
																												lowerCAmelCase__	       =     file.replace('''model_00'''			,   F"""model_0{i}"""	)
																												lowerCAmelCase__	       =     torch.load(os.path.join(A			,   A	)			,   map_location='''cpu'''	)

																												# Rename keys in the transformers names
																												lowerCAmelCase__	       =     list(temp.keys()	)
																												for key in keys:
																																			lowerCAmelCase__	       =     temp.pop(A	)

																												if tensors is None:
																																			lowerCAmelCase__	       =     temp
																												else:
																																			for key in tensors.keys():
																																										# We average (sum and then divide) some weights accross TP ranks (see https://github.com/bigscience-workshop/Megatron-DeepSpeed/blob/olruwase/sync_layer_norms/megatron/training.py#L425)
																																										if any(key.endswith(A	) for end in WEIGHTS_TO_AVERAGE_ENDSWITH	):
																																																	tensors[key] += temp[key]
																																										else:
																																																	# Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel
																																																	lowerCAmelCase__	       =     1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN	) else 0
																																																	# We concatenate these weights accross TP ranks
																																																	lowerCAmelCase__	       =     torch.cat([tensors[key], temp[key]]			,   dim=A	)

            # Divide by the number of TP the weights we want to average
																					for key in tensors.keys():
																												if any(key.endswith(A	) for end in WEIGHTS_TO_AVERAGE_ENDSWITH	):
																																			lowerCAmelCase__	       =     tensors[key] / pretraining_tp

																					lowerCAmelCase__	       =     model.load_state_dict(A			,   strict=A	)
																					assert not other_keys.unexpected_keys, F"""The keys {other_keys.unexpected_keys} are unexpected"""
																					if missing_keys is None:
																												lowerCAmelCase__	       =     set(other_keys.missing_keys	)
																					else:
																												lowerCAmelCase__	       =     missing_keys.intersection(set(other_keys.missing_keys	)	)

														assert not missing_keys, F"""The keys {missing_keys} are missing"""

														# Save pytorch-model
														os.makedirs(A			,   exist_ok=A	)
														lowerCAmelCase__	       =     pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME
														lowerCAmelCase__	       =     pytorch_dump_folder_path + '''/''' + CONFIG_NAME
														print(F"""Save PyTorch model to {pytorch_weights_dump_path} with dtype {config.torch_dtype}"""	)
														if config.torch_dtype is not None:
																					lowerCAmelCase__	       =     model.to(config.torch_dtype	)
														torch.save(model.state_dict()			,   A	)
														print(F"""Save configuration file to {pytorch_config_dump_path}"""	)
														with open(A			,   '''w'''			,   encoding='''utf-8'''	) as f:
																					f.write(config.to_json_string()	)


if __name__ == "__main__":
		__UpperCAmelCase       =							argparse.ArgumentParser()
		# Required parameters
		parser.add_argument(
		    '''--bloom_checkpoint_path''',
		    default=None,
		    type=str,
		    required=True,
		    help='''Path to the Megatron-LM checkpoint path.''',
		)
		parser.add_argument(
		    '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.'''
		)
		parser.add_argument(
		    '''--bloom_config_file''',
		    default='''''',
		    type=str,
		    help=(
		        '''An optional config json file corresponding to the pre-trained model. \n'''
		        '''This specifies the model architecture.'''
		    ),
		)
		parser.add_argument(
		    '''--shard_model''',
		    action='''store_true''',
		    help='''An optional setting to shard the output model \nThis enables sharding the converted checkpoint''',
		)
		parser.add_argument(
		    '''--pretraining_tp''',
		    default=4,
		    type=int,
		    help='''Pretraining TP rank that has been used when training the model in Megatron-LM \n''',
		)
		__UpperCAmelCase       =							parser.parse_args()
		convert_bloom_checkpoint_to_pytorch(
		    args.bloom_checkpoint_path,
		    args.bloom_config_file,
		    args.pytorch_dump_folder_path,
		    args.shard_model,
		    args.pretraining_tp,
		)