




"""simple docstring"""







# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


import warnings
from typing import List
from unittest.mock import Mock

import torch
from torch.utils.data import DataLoader, IterableDataset, TensorDataset

from accelerate.accelerator import Accelerator
from accelerate.utils.dataclasses import DistributedType

class 				snake_case_			(					lowerCamelCase_			):







   """simple docstring"""




   def __init__(		self       ,					lowerCamelCase_)				->   Optional[int]:
       UpperCamelCase              =	data







   def __iter__(		self)				->   Tuple:
       for element in self.data:
           yield element





def      __snake_case (				_lowercase=True    ):


    """simple docstring"""







    UpperCamelCase              =	Accelerator(even_batches=_lowercase    )
    assert accelerator.num_processes == 2, "this script expects that two GPUs are available"
    return accelerator





def      __snake_case (				_lowercase			,_lowercase			,_lowercase			,_lowercase = False    ):


    """simple docstring"""







    if iterable:
        UpperCamelCase              =	DummyIterableDataset(torch.as_tensor(range(_lowercase    )    )    )
    else:
        UpperCamelCase              =	TensorDataset(torch.as_tensor(range(_lowercase    )    )    )

    UpperCamelCase              =	DataLoader(_lowercase			,batch_size=_lowercase    )
    UpperCamelCase              =	accelerator.prepare(_lowercase    )

    return dl





def      __snake_case (				_lowercase			,_lowercase			,_lowercase			,_lowercase			,_lowercase			,):


    """simple docstring"""







    UpperCamelCase              =	create_dataloader(accelerator=_lowercase			,dataset_size=_lowercase			,batch_size=_lowercase    )

    UpperCamelCase              =	[len(batch[0]    ) for batch in dl]

    if accelerator.process_index == 0:
        assert batch_sizes == process_0_expected_batch_sizes
    elif accelerator.process_index == 1:
        assert batch_sizes == process_1_expected_batch_sizes





def      __snake_case (				):


    """simple docstring"""







    UpperCamelCase              =	create_accelerator()

    # without padding, we would expect a different number of batches
    verify_dataloader_batch_sizes(
        _lowercase			,dataset_size=3			,batch_size=1			,process_0_expected_batch_sizes=[1, 1]			,process_1_expected_batch_sizes=[1, 1]			,)

    # without padding, we would expect the same number of batches, but different sizes
    verify_dataloader_batch_sizes(
        _lowercase			,dataset_size=7			,batch_size=2			,process_0_expected_batch_sizes=[2, 2]			,process_1_expected_batch_sizes=[2, 2]			,)





def      __snake_case (				):


    """simple docstring"""







    UpperCamelCase              =	create_accelerator(even_batches=_lowercase    )

    verify_dataloader_batch_sizes(
        _lowercase			,dataset_size=3			,batch_size=1			,process_0_expected_batch_sizes=[1, 1]			,process_1_expected_batch_sizes=[1]			,)

    verify_dataloader_batch_sizes(
        _lowercase			,dataset_size=7			,batch_size=2			,process_0_expected_batch_sizes=[2, 2]			,process_1_expected_batch_sizes=[2, 1]			,)





def      __snake_case (				):


    """simple docstring"""







    UpperCamelCase              =	create_accelerator(even_batches=_lowercase    )

    UpperCamelCase              =	torch.nn.Linear(1			,1    )
    UpperCamelCase              =	accelerator.prepare(_lowercase    )

    UpperCamelCase              =	create_dataloader(_lowercase			,dataset_size=3			,batch_size=1    )

    UpperCamelCase              =	[]
    with accelerator.join_uneven_inputs([ddp_model]    ):
        for batch_idx, batch in enumerate(_lowercase    ):
            UpperCamelCase              =	ddp_model(batch[0].float()    )
            UpperCamelCase              =	output.sum()
            loss.backward()
            batch_idxs.append(_lowercase    )

    accelerator.wait_for_everyone()

    if accelerator.process_index == 0:
        assert batch_idxs == [0, 1]
    elif accelerator.process_index == 1:
        assert batch_idxs == [0]





def      __snake_case (				_lowercase    ):


    """simple docstring"""







    with warnings.catch_warnings(record=_lowercase    ) as w:
        with accelerator.join_uneven_inputs([Mock()]    ):
            pass

        assert issubclass(w[-1].category			,_lowercase    )
        assert "only supported for multi-GPU" in str(w[-1].message    )





def      __snake_case (				):


    """simple docstring"""







    UpperCamelCase              =	True
    UpperCamelCase              =	False
    UpperCamelCase              =	create_accelerator(even_batches=_lowercase    )
    UpperCamelCase              =	torch.nn.Linear(1			,1    )
    UpperCamelCase              =	accelerator.prepare(_lowercase    )
    UpperCamelCase              =	create_dataloader(_lowercase			,dataset_size=3			,batch_size=1    )
    UpperCamelCase              =	create_dataloader(_lowercase			,dataset_size=3			,batch_size=1    )

    with accelerator.join_uneven_inputs([ddp_model]			,even_batches=_lowercase    ):
        UpperCamelCase              =	train_dl.batch_sampler.even_batches
        UpperCamelCase              =	valid_dl.batch_sampler.even_batches

    assert train_dl_overridden_value == overridden_even_batches
    assert valid_dl_overridden_value == overridden_even_batches
    assert train_dl.batch_sampler.even_batches == default_even_batches
    assert valid_dl.batch_sampler.even_batches == default_even_batches





def      __snake_case (				):


    """simple docstring"""







    UpperCamelCase              =	True
    UpperCamelCase              =	False
    UpperCamelCase              =	create_accelerator(even_batches=_lowercase    )
    UpperCamelCase              =	torch.nn.Linear(1			,1    )
    UpperCamelCase              =	accelerator.prepare(_lowercase    )
    create_dataloader(_lowercase			,dataset_size=3			,batch_size=1			,iterable=_lowercase    )
    UpperCamelCase              =	create_dataloader(_lowercase			,dataset_size=3			,batch_size=1    )

    with warnings.catch_warnings():
        warnings.filterwarnings('''ignore'''    )
        try:
            with accelerator.join_uneven_inputs([ddp_model]			,even_batches=_lowercase    ):
                UpperCamelCase              =	batch_dl.batch_sampler.even_batches
        except AttributeError:
            # ensure attribute error is not raised when processing iterable dl
            raise AssertionError

    assert batch_dl_overridden_value == overridden_even_batches
    assert batch_dl.batch_sampler.even_batches == default_even_batches





def      __snake_case (				):


    """simple docstring"""







    UpperCamelCase              =	create_accelerator()
    UpperCamelCase              =	torch.nn.Linear(1			,1    )
    UpperCamelCase              =	accelerator.prepare(_lowercase    )
    create_dataloader(_lowercase			,dataset_size=3			,batch_size=1			,iterable=_lowercase    )

    with warnings.catch_warnings(record=_lowercase    ) as w:
        with accelerator.join_uneven_inputs([ddp_model]			,even_batches=_lowercase    ):
            pass

        assert issubclass(w[-1].category			,_lowercase    )
        assert "only supported for map-style datasets" in str(w[-1].message    )





def      __snake_case (				):


    """simple docstring"""







    UpperCamelCase              =	create_accelerator()

    accelerator.print('''Test that even_batches variable ensures uniform batches across processes'''    )
    test_default_ensures_even_batch_sizes()

    accelerator.print('''Run tests with even_batches disabled'''    )
    test_can_disable_even_batches()

    accelerator.print('''Test joining uneven inputs'''    )
    test_can_join_uneven_inputs()

    accelerator.print('''Test overriding even_batches when joining uneven inputs'''    )
    test_join_can_override_even_batches()

    accelerator.print('''Test overriding even_batches for mixed dataloader types'''    )
    test_join_can_override_for_mixed_type_dataloaders()

    accelerator.print('''Test overriding even_batches raises a warning for iterable dataloaders'''    )
    test_join_raises_warning_for_iterable_when_overriding_even_batches()

    accelerator.print('''Test join with non DDP distributed raises warning'''    )
    UpperCamelCase              =	accelerator.state.distributed_type
    UpperCamelCase              =	DistributedType.FSDP
    test_join_raises_warning_for_non_ddp_distributed(_lowercase    )
    UpperCamelCase              =	original_state


if __name__ == "__main__":
  main()





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							     =					[
    '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							     =					[
    'mlp.dense_4h_to_h.weight',
    'self_attention.dense.weight',
]







def lowerCamelCase__  (     _lowercase					,		_lowercase ):

     '''simple docstring'''


     UpperCAmelCase_     :				List[Any]  =     {
         '''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
     UpperCAmelCase_     :				Union[str, Any]  =     int(re.match(r'''.*layer_(\d*).*'''					,		_lowercase )[1] )
     layer_number -= 3
     return f'''h.{layer_number}.''' + key







def lowerCamelCase__  (     _lowercase ):

     '''simple docstring'''


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







def lowerCamelCase__  (     _lowercase					,		_lowercase					,		_lowercase					,		_lowercase					,		_lowercase ):

     '''simple docstring'''


     if bloom_config_file == "":
          UpperCAmelCase_     :				Tuple  =     BloomConfig()
     else:
          UpperCAmelCase_     :				Optional[int]  =     BloomConfig.from_json_file(_lowercase )

     if shard_model:
          UpperCAmelCase_     :				Any  =     os.listdir(_lowercase )
          UpperCAmelCase_     :				Union[str, Any]  =     sorted(filter(lambda _lowercase : s.startswith('''layer''' ) and "model_00" in s					,		_lowercase ) )

          UpperCAmelCase_     :				Any  =     {'''weight_map''': {}, '''metadata''': {}}
          UpperCAmelCase_     :				List[str]  =     0

          UpperCAmelCase_     :				Any  =     None

          UpperCAmelCase_     :				Optional[int]  =     BloomConfig()

          for j, file in enumerate(_lowercase ):
               print('''Processing file: {}'''.format(_lowercase ) )
               UpperCAmelCase_     :				Optional[Any]  =     None

               for i in range(_lowercase ):
                    # load all TP files
                    UpperCAmelCase_     :				Tuple  =     file.replace('''model_00'''					,		f'''model_0{i}''' )
                    UpperCAmelCase_     :				Any  =     torch.load(os.path.join(_lowercase					,		_lowercase )					,		map_location='''cpu''' )

                    # Rename keys in the transformers names
                    UpperCAmelCase_     :				Dict  =     list(temp.keys() )
                    for key in keys:
                         UpperCAmelCase_     :				Union[str, Any]  =     temp.pop(_lowercase )

                    if tensors is None:
                         UpperCAmelCase_     :				Union[str, Any]  =     temp
                    else:
                         for key in tensors.keys():
                              if any(key.endswith(_lowercase ) 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
                                   UpperCAmelCase_     :				int  =     1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN ) else 0
                                   # We concatenate these weights accross TP ranks
                                   UpperCAmelCase_     :				Tuple  =     torch.cat([tensors[key], temp[key]]					,		dim=_lowercase )

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

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

          UpperCAmelCase_     :				List[Any]  =     BloomConfig()
          UpperCAmelCase_     :				Tuple  =     pytorch_dump_folder_path + '''/''' + CONFIG_NAME
          UpperCAmelCase_     :				List[str]  =     total_size
          with open(_lowercase					,		'''w'''					,		encoding='''utf-8''' ) as f:
               f.write(config.to_json_string() )
          with open(os.path.join(_lowercase					,		WEIGHTS_NAME + '''.index.json''' )					,		'''w'''					,		encoding='''utf-8''' ) as f:
               UpperCAmelCase_     :				Optional[Any]  =     json.dumps(_lowercase					,		indent=2					,		sort_keys=_lowercase ) + '''\n'''
               f.write(_lowercase )
     else:
          UpperCAmelCase_     :				Any  =     BloomModel(_lowercase )

          UpperCAmelCase_     :				Tuple  =     os.listdir(_lowercase )
          UpperCAmelCase_     :				Union[str, Any]  =     sorted(filter(lambda _lowercase : s.startswith('''layer''' ) and "model_00" in s					,		_lowercase ) )

          UpperCAmelCase_     :				Any  =     None
          for i, file in enumerate(_lowercase ):
               UpperCAmelCase_     :				Optional[Any]  =     None
               for i in range(_lowercase ):
                    # load all TP files
                    UpperCAmelCase_     :				List[Any]  =     file.replace('''model_00'''					,		f'''model_0{i}''' )
                    UpperCAmelCase_     :				Optional[int]  =     torch.load(os.path.join(_lowercase					,		_lowercase )					,		map_location='''cpu''' )

                    # Rename keys in the transformers names
                    UpperCAmelCase_     :				str  =     list(temp.keys() )
                    for key in keys:
                         UpperCAmelCase_     :				Dict  =     temp.pop(_lowercase )

                    if tensors is None:
                         UpperCAmelCase_     :				int  =     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(_lowercase ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ):
                                   tensors[key] += temp[key]
                              else:
                                   # Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel
                                   UpperCAmelCase_     :				Optional[int]  =     1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN ) else 0
                                   # We concatenate these weights accross TP ranks
                                   UpperCAmelCase_     :				List[str]  =     torch.cat([tensors[key], temp[key]]					,		dim=_lowercase )

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

               UpperCAmelCase_     :				Tuple  =     model.load_state_dict(_lowercase					,		strict=_lowercase )
               assert not other_keys.unexpected_keys, f'''The keys {other_keys.unexpected_keys} are unexpected'''
               if missing_keys is None:
                    UpperCAmelCase_     :				Union[str, Any]  =     set(other_keys.missing_keys )
               else:
                    UpperCAmelCase_     :				Dict  =     missing_keys.intersection(set(other_keys.missing_keys ) )

          assert not missing_keys, f'''The keys {missing_keys} are missing'''

          # Save pytorch-model
          os.makedirs(_lowercase					,		exist_ok=_lowercase )
          UpperCAmelCase_     :				str  =     pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME
          UpperCAmelCase_     :				Dict  =     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:
               UpperCAmelCase_     :				Optional[int]  =     model.to(config.torch_dtype )
          torch.save(model.state_dict()					,		_lowercase )
          print(f'''Save configuration file to {pytorch_config_dump_path}''' )
          with open(_lowercase					,		'''w'''					,		encoding='''utf-8''' ) as f:
               f.write(config.to_json_string() )


if __name__ == "__main__":
     __a							     =					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							     =					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,
     )