



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



def       _lowerCAmelCase			(_lowerCAmelCase      ,		_lowerCAmelCase):
					UpperCamelCase_						     =      {
					    "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_						     =      int(re.match(r".*layer_(\d*).*"      ,		__UpperCamelCase)[1])
					layer_number -= 3
					return f"""h.{layer_number}.""" + key



def       _lowerCAmelCase			(_lowerCAmelCase):





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



def       _lowerCAmelCase			(_lowerCAmelCase      ,		_lowerCAmelCase      ,		_lowerCAmelCase      ,		_lowerCAmelCase      ,		_lowerCAmelCase):





					if bloom_config_file == "":
										UpperCamelCase_						     =      BloomConfig()
					else:
										UpperCamelCase_						     =      BloomConfig.from_json_file(__UpperCamelCase)

					if shard_model:
										UpperCamelCase_						     =      os.listdir(__UpperCamelCase)
										UpperCamelCase_						     =      sorted(filter(lambda _lowerCAmelCase: s.startswith("layer") and "model_00" in s      ,		__UpperCamelCase))

										UpperCamelCase_						     =      {"weight_map": {}, "metadata": {}}
										UpperCamelCase_						     =      0

										UpperCamelCase_						     =      None

										UpperCamelCase_						     =      BloomConfig()

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

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

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

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

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

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

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

										UpperCamelCase_						     =      os.listdir(__UpperCamelCase)
										UpperCamelCase_						     =      sorted(filter(lambda _lowerCAmelCase: s.startswith("layer") and "model_00" in s      ,		__UpperCamelCase))

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

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

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

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

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

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

										# Save pytorch-model
										os.makedirs(__UpperCamelCase      ,		exist_ok=__UpperCamelCase)
										UpperCamelCase_						     =      pytorch_dump_folder_path + "/" + WEIGHTS_NAME
										UpperCamelCase_						     =      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_						     =      model.to(config.torch_dtype)
										torch.save(model.state_dict()      ,		__UpperCamelCase)
										print(f"""Save configuration file to {pytorch_config_dump_path}""")
										with open(__UpperCamelCase      ,		"w"      ,		encoding="utf-8") as f:
															f.write(config.to_json_string())


if __name__ == "__main__":
	UpperCAmelCase      :							List[str]							       =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      :							Tuple							       =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 typing import Callable, List, Optional, Union

import PIL
import torch
from transformers import (
    CLIPImageProcessor,
    CLIPSegForImageSegmentation,
    CLIPSegProcessor,
    CLIPTextModel,
    CLIPTokenizer,
)

from diffusers import DiffusionPipeline
from diffusers.configuration_utils import FrozenDict
from diffusers.models import AutoencoderKL, UNetaDConditionModel
from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
from diffusers.utils import deprecate, is_accelerate_available, logging


__lowerCamelCase			: str							   =		logging.get_logger(__name__)  # pylint: disable=invalid-name







class __snake_case				(						lowerCamelCase_		):




   def __init__(    self			:				Dict       ,	_lowercase			:				CLIPSegForImageSegmentation       ,	_lowercase			:				CLIPSegProcessor       ,	_lowercase			:				AutoencoderKL       ,	_lowercase			:				CLIPTextModel       ,	_lowercase			:				CLIPTokenizer       ,	_lowercase			:				UNetaDConditionModel       ,	_lowercase			:				Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]       ,	_lowercase			:				StableDiffusionSafetyChecker       ,	_lowercase			:				CLIPImageProcessor       ,	):



     """simple docstring"""






     super().__init__()

     if hasattr(scheduler.config       ,	"""steps_offset"""      ) and scheduler.config.steps_offset != 1:
       SCREAMING_SNAKE_CASE__										=      (
           f"""The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"""
           f""" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure """
           """to update the config accordingly as leaving `steps_offset` might led to incorrect results"""
           """ in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"""
           """ it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"""
           """ file"""
       )
       deprecate("""steps_offset!=1"""       ,	"""1.0.0"""       ,	_lowercase       ,	standard_warn=_lowercase      )
       SCREAMING_SNAKE_CASE__										=      dict(scheduler.config      )
       SCREAMING_SNAKE_CASE__										=      1
       SCREAMING_SNAKE_CASE__										=      FrozenDict(_lowercase      )

     if hasattr(scheduler.config       ,	"""skip_prk_steps"""      ) and scheduler.config.skip_prk_steps is False:
       SCREAMING_SNAKE_CASE__										=      (
           f"""The configuration file of this scheduler: {scheduler} has not set the configuration"""
           """ `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make"""
           """ sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to"""
           """ incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face"""
           """ Hub, it would be very nice if you could open a Pull request for the"""
           """ `scheduler/scheduler_config.json` file"""
       )
       deprecate("""skip_prk_steps not set"""       ,	"""1.0.0"""       ,	_lowercase       ,	standard_warn=_lowercase      )
       SCREAMING_SNAKE_CASE__										=      dict(scheduler.config      )
       SCREAMING_SNAKE_CASE__										=      True
       SCREAMING_SNAKE_CASE__										=      FrozenDict(_lowercase      )

     if safety_checker is None:
       logger.warning(
           f"""You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"""
           """ that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"""
           """ results in services or applications open to the public. Both the diffusers team and Hugging Face"""
           """ strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"""
           """ it only for use-cases that involve analyzing network behavior or auditing its results. For more"""
           """ information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."""      )

     self.register_modules(
         segmentation_model=_lowercase       ,	segmentation_processor=_lowercase       ,	vae=_lowercase       ,	text_encoder=_lowercase       ,	tokenizer=_lowercase       ,	unet=_lowercase       ,	scheduler=_lowercase       ,	safety_checker=_lowercase       ,	feature_extractor=_lowercase       ,	)




   def 	__a						(    self			:				List[Any]       ,	_lowercase			:				Optional[Union[str, int]] = "auto"      ):



     """simple docstring"""






     if slice_size == "auto":
       # half the attention head size is usually a good trade-off between
       # speed and memory
       SCREAMING_SNAKE_CASE__										=      self.unet.config.attention_head_dim // 2
     self.unet.set_attention_slice(_lowercase      )




   def 	__a						(    self			:				Any      ):



     """simple docstring"""






     self.enable_attention_slicing(_lowercase      )




   def 	__a						(    self			:				Optional[int]      ):



     """simple docstring"""






     if is_accelerate_available():
       from accelerate import cpu_offload
     else:
       raise ImportError("""Please install accelerate via `pip install accelerate`"""      )

     SCREAMING_SNAKE_CASE__										=      torch.device("""cuda"""      )

     for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]:
       if cpu_offloaded_model is not None:
         cpu_offload(_lowercase       ,	_lowercase      )




   @property
   # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
   def 	__a						(    self			:				Optional[int]      ):



     """simple docstring"""






     if self.device != torch.device("""meta"""      ) or not hasattr(self.unet       ,	"""_hf_hook"""      ):
       return self.device
     for module in self.unet.modules():
       if (
           hasattr(_lowercase       ,	"""_hf_hook"""      )
           and hasattr(module._hf_hook       ,	"""execution_device"""      )
           and module._hf_hook.execution_device is not None
       ):
         return torch.device(module._hf_hook.execution_device      )
     return self.device




   @torch.no_grad()
   def __call__(    self			:				Optional[Any]       ,	_lowercase			:				Union[str, List[str]]       ,	_lowercase			:				Union[torch.FloatTensor, PIL.Image.Image]       ,	_lowercase			:				str       ,	_lowercase			:				int = 5_12       ,	_lowercase			:				int = 5_12       ,	_lowercase			:				int = 50       ,	_lowercase			:				float = 7.5       ,	_lowercase			:				Optional[Union[str, List[str]]] = None       ,	_lowercase			:				Optional[int] = 1       ,	_lowercase			:				float = 0.0       ,	_lowercase			:				Optional[torch.Generator] = None       ,	_lowercase			:				Optional[torch.FloatTensor] = None       ,	_lowercase			:				Optional[str] = "pil"       ,	_lowercase			:				bool = True       ,	_lowercase			:				Optional[Callable[[int, int, torch.FloatTensor], None]] = None       ,	_lowercase			:				int = 1       ,	**_lowercase			:				str       ,	):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__										=      self.segmentation_processor(
         text=[text]       ,	images=[image]       ,	padding="""max_length"""       ,	return_tensors="""pt"""      ).to(self.device      )
     SCREAMING_SNAKE_CASE__										=      self.segmentation_model(**_lowercase      )
     SCREAMING_SNAKE_CASE__										=      torch.sigmoid(outputs.logits      ).cpu().detach().unsqueeze(-1      ).numpy()
     SCREAMING_SNAKE_CASE__										=      self.numpy_to_pil(_lowercase      )[0].resize(image.size      )

     # Run inpainting pipeline with the generated mask
     SCREAMING_SNAKE_CASE__										=      StableDiffusionInpaintPipeline(
         vae=self.vae       ,	text_encoder=self.text_encoder       ,	tokenizer=self.tokenizer       ,	unet=self.unet       ,	scheduler=self.scheduler       ,	safety_checker=self.safety_checker       ,	feature_extractor=self.feature_extractor       ,	)
     return inpainting_pipeline(
         prompt=_lowercase       ,	image=_lowercase       ,	mask_image=_lowercase       ,	height=_lowercase       ,	width=_lowercase       ,	num_inference_steps=_lowercase       ,	guidance_scale=_lowercase       ,	negative_prompt=_lowercase       ,	num_images_per_prompt=_lowercase       ,	eta=_lowercase       ,	generator=_lowercase       ,	latents=_lowercase       ,	output_type=_lowercase       ,	return_dict=_lowercase       ,	callback=_lowercase       ,	callback_steps=_lowercase       ,	)
