



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

A_		:     Tuple        =     [
    "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",
]

A_		:     Dict        =     [
    "mlp.dense_4h_to_h.weight",
    "self_attention.dense.weight",
]


def 	UpperCAmelCase__      (      UpperCAmelCase__ :str ,					UpperCAmelCase__ :Tuple					):






 '''simple docstring'''

 a						=		{
     '''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
 a						=		int(re.match(r".*layer_(\d*).*" ,					a_					)[1]					)
 layer_number -= 3
 return F"""h.{layer_number}.""" + key


def 	UpperCAmelCase__      (      UpperCAmelCase__ :Optional[Any]					):






 '''simple docstring'''

 if dtype == torch.bool:
  return 1 / 8
 a						=		re.search(r"[^\d](\d+)$" ,					str(a_					)					)
 if bit_search is None:
  raise ValueError(F"""`dtype` is not a valid dtype: {dtype}."""					)
 a						=		int(bit_search.groups()[0]					)
 return bit_size // 8


def 	UpperCAmelCase__      (      UpperCAmelCase__ :str ,					UpperCAmelCase__ :Dict ,					UpperCAmelCase__ :Dict ,					UpperCAmelCase__ :List[str] ,					UpperCAmelCase__ :int					):






 '''simple docstring'''

 if bloom_config_file == "":
  a						=		BloomConfig()
 else:
  a						=		BloomConfig.from_json_file(a_					)

 if shard_model:
  a						=		os.listdir(a_					)
  a						=		sorted(filter(lambda UpperCAmelCase__					: s.startswith("layer"					) and "model_00" in s ,					a_					)					)

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

  a						=		None

  a						=		BloomConfig()

  for j, file in enumerate(a_					):
   print("Processing file: {}".format(a_					)					)
   a						=		None

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

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

    if tensors is None:
     a						=		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
       a						=		1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN					) else 0
       # We concatenate these weights accross TP ranks
       a						=		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					):
     a						=		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():
    a						=		tensors[key]
    total_size += value.numel() * get_dtype_size(value.dtype					)
    if key not in index_dict["weight_map"]:
     a						=		'''pytorch_model_{}-of-{}.bin'''.format(
         str(j + 1					).zfill(5					) ,					str(len(a_					)					).zfill(5					)					)

  a						=		BloomConfig()
  a						=		pytorch_dump_folder_path + '''/''' + CONFIG_NAME
  a						=		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:
   a						=		json.dumps(a_ ,					indent=2 ,					sort_keys=a_					) + '''\n'''
   f.write(a_					)
 else:
  a						=		BloomModel(a_					)

  a						=		os.listdir(a_					)
  a						=		sorted(filter(lambda UpperCAmelCase__					: s.startswith("layer"					) and "model_00" in s ,					a_					)					)

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

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

    if tensors is None:
     a						=		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
       a						=		1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN					) else 0
       # We concatenate these weights accross TP ranks
       a						=		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					):
     a						=		tensors[key] / pretraining_tp

   a						=		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:
    a						=		set(other_keys.missing_keys					)
   else:
    a						=		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_					)
  a						=		pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME
  a						=		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:
   a						=		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__":
     A_		:     Any        =     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''',
     )
     A_		:     str        =     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,
     )









from math import ceil
from typing import List, Optional, Union

import numpy as np

from ...audio_utils import mel_filter_bank, spectrogram, window_function
from ...feature_extraction_sequence_utils import BatchFeature, SequenceFeatureExtractor
from ...utils import TensorType, logging


A_		:     List[str]        =     logging.get_logger(__name__)



class 		_lowercase		(       UpperCAmelCase__	):
   _UpperCAmelCase     	=			['''audio_values''', '''audio_mask''']

   def __init__(      self			:       List[Any]							,   __lowerCAmelCase			:       Dict=2048							,   __lowerCAmelCase			:       List[Any]=1							,   __lowerCAmelCase			:       Dict=[16, 16]							,   __lowerCAmelCase			:       str=128							,   __lowerCAmelCase			:       Optional[int]=4_4100							,   __lowerCAmelCase			:       int=86							,   __lowerCAmelCase			:       Optional[Any]=2048							,   __lowerCAmelCase			:       str=0.0							,   **__lowerCAmelCase			:       Optional[int]							,   )       ->				Union[str, Any]:


    """simple docstring"""






    super().__init__(
        feature_size=__lowerCAmelCase							,   sampling_rate=__lowerCAmelCase							,   padding_value=__lowerCAmelCase							,   **__lowerCAmelCase							,   )

    a						=		spectrogram_length
    a						=		num_channels
    a						=		patch_size
    a						=		feature_size // self.patch_size[1]
    a						=		n_fft
    a						=		sampling_rate // hop_length_to_sampling_rate
    a						=		sampling_rate
    a						=		padding_value
    a						=		mel_filter_bank(
        num_frequency_bins=1 + n_fft // 2							,   num_mel_filters=__lowerCAmelCase							,   min_frequency=0.0							,   max_frequency=2_2_0_5_0.0							,   sampling_rate=__lowerCAmelCase							,   norm="slaney"							,   mel_scale="slaney"							,   ).T

   def 		A							(      self			:       List[str]							,   __lowerCAmelCase			:       np.array							)       ->				np.ndarray:


    """simple docstring"""






    a						=		spectrogram(
        __lowerCAmelCase							,   window_function(self.n_fft							,   "hann"							)							,   frame_length=self.n_fft							,   hop_length=self.hop_length							,   power=2.0							,   mel_filters=self.mel_filters.T							,   log_mel="dB"							,   db_range=8_0.0							,   )
    a						=		log_spec[:, :-1]
    a						=		log_spec - 2_0.0
    a						=		np.clip(log_spec / 4_0.0							,   -2.0							,   0.0							) + 1.0
    return log_spec




   def __call__(      self			:       Union[str, Any]							,   __lowerCAmelCase			:       Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]							,   __lowerCAmelCase			:       Optional[Union[str, TensorType]] = None							,   __lowerCAmelCase			:       Optional[bool] = True							,   __lowerCAmelCase			:       Optional[int] = None							,   __lowerCAmelCase			:       bool = False							,   __lowerCAmelCase			:       bool = False							,   **__lowerCAmelCase			:       Optional[int]							,   )       ->				BatchFeature:


    """simple docstring"""






    if sampling_rate is not None:
     if sampling_rate != self.sampling_rate:
      raise ValueError(
          "This feature extractor is set to support sampling rate"
          f""" of {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled"""
          f""" with {self.sampling_rate} and not {sampling_rate}."""							)
    else:
     logger.warning(
         "It is strongly recommended to pass the `sampling_rate` argument to this function. "
         "Failing to do so can result in silent errors that might be hard to debug."							)

    a						=		isinstance(__lowerCAmelCase							,   np.ndarray							) and len(raw_speech.shape							) > 1
    if is_batched_numpy and len(raw_speech.shape							) > 2:
     raise ValueError(f"""Only mono-channel audio is supported for input to {self}"""							)
    a						=		is_batched_numpy or (
        isinstance(__lowerCAmelCase							,   (list, tuple)							) and (isinstance(raw_speech[0]							,   (np.ndarray, tuple, list)							))
    )
    if is_batched:
     a						=		[np.asarray([speech]							,   dtype=np.floataa							).T for speech in raw_speech]
    elif not is_batched and not isinstance(__lowerCAmelCase							,   np.ndarray							):
     a						=		np.asarray(__lowerCAmelCase							,   dtype=np.floataa							)
    elif isinstance(__lowerCAmelCase							,   np.ndarray							) and raw_speech.dtype is np.dtype(np.floataa							):
     a						=		raw_speech.astype(np.floataa							)
    # always return batch
    if not is_batched:
     a						=		[np.asarray([raw_speech]							).T]

    # Convert audio signals to log mel spectrograms, truncate by time axis
    a						=		[
        self._np_extract_fbank_features(waveform.squeeze()							).T[: self.spectrogram_length] for waveform in raw_speech
    ]
    if isinstance(audio_features[0]							,   __lowerCAmelCase							):
     a						=		[np.asarray(__lowerCAmelCase							,   dtype=np.floataa							) for feature in audio_features]

    # Create audio attention mask
    a						=		max(
        [ceil(feature.shape[0] / self.patch_size[0]							) * self.freq_len for feature in audio_features]							)  # The maximum number of audio patches in a batch
    if return_attention_mask:
     a						=		[
         (ceil(feature.shape[0] / self.patch_size[0]							) * self.freq_len) * [1]
         + (max_patch_len - ceil(feature.shape[0] / self.patch_size[0]							) * self.freq_len) * [0]
         for feature in audio_features
     ]
     a						=		np.array(__lowerCAmelCase							).astype(np.floataa							)

    # convert into correct format for padding
    a						=		max_patch_len // self.freq_len * self.patch_size[0]  # The maximum audio size in a batch
    a						=		np.ones([len(__lowerCAmelCase							), 1, max_time_len, self.feature_size]							).astype(np.floataa							)
    a						=		padded_audio_features * self.padding_value
    for i in range(len(__lowerCAmelCase							)							):
     a						=		audio_features[i]
     a						=		feature

    # return as BatchFeature
    if return_attention_mask:
     a						=		{"audio_values": padded_audio_features, "audio_mask": audio_mask}
    else:
     a						=		{"audio_values": padded_audio_features}

    a						=		BatchFeature(data=__lowerCAmelCase							,   tensor_type=__lowerCAmelCase							)
    return encoded_inputs

