'''simple docstring'''





import argparse
import gc
import json
import os
import shutil
import warnings

import torch

from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer


try:
 from transformers import LlamaTokenizerFast
except ImportError as e:
 warnings.warn(e)
 warnings.warn(
     """The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion"""
 )
 _lowerCAmelCase  :List[str]  				=    None
_lowerCAmelCase  :Dict  				=    {
    """7B""": 11_008,
    """13B""": 13_824,
    """30B""": 17_920,
    """65B""": 22_016,
    """70B""": 28_672,
}
_lowerCAmelCase  :Optional[Any]  				=    {
    """7B""": 1,
    """7Bf""": 1,
    """13B""": 2,
    """13Bf""": 2,
    """30B""": 4,
    """65B""": 8,
    """70B""": 8,
    """70Bf""": 8,
}


def     __lowerCAmelCase						(       a_       ,      a_=1       ,      a_=256		)      ->	List[Any]:





     '''simple docstring'''





     return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3		)		) + multiple_of - 1) // multiple_of)


def     __lowerCAmelCase						(       a_		)      ->	List[str]:





     '''simple docstring'''





     with open(a_       ,      'r'		) as f:
          return json.load(a_		)


def     __lowerCAmelCase						(       a_       ,      a_		)      ->	Union[str, Any]:





     '''simple docstring'''





     with open(a_       ,      'w'		) as f:
          json.dump(a_       ,      a_		)


def     __lowerCAmelCase						(       a_       ,      a_       ,      a_       ,      a_=True		)      ->	Optional[int]:





     '''simple docstring'''





     os.makedirs(a_       ,      exist_ok=a_		)
     SCREAMING_SNAKE_CASE					:			List[str]    	=       os.path.join(a_       ,      'tmp'		)
     os.makedirs(a_       ,      exist_ok=a_		)

     SCREAMING_SNAKE_CASE					:			str    	=       read_json(os.path.join(a_       ,      'params.json'		)		)
     SCREAMING_SNAKE_CASE					:			Any    	=       NUM_SHARDS[model_size]
     SCREAMING_SNAKE_CASE					:			int    	=       params['n_layers']
     SCREAMING_SNAKE_CASE					:			Dict    	=       params['n_heads']
     SCREAMING_SNAKE_CASE					:			List[Any]    	=       n_heads // num_shards
     SCREAMING_SNAKE_CASE					:			List[str]    	=       params['dim']
     SCREAMING_SNAKE_CASE					:			Optional[Any]    	=       dim // n_heads
     SCREAMING_SNAKE_CASE					:			Tuple    	=       1_0000.0
     SCREAMING_SNAKE_CASE					:			Optional[Any]    	=       1.0 / (base ** (torch.arange(0       ,      a_       ,      2		).float() / dims_per_head))

     if "n_kv_heads" in params:
          SCREAMING_SNAKE_CASE					:			Optional[Any]    	=       params['n_kv_heads']  # for GQA / MQA
          SCREAMING_SNAKE_CASE					:			List[str]    	=       n_heads_per_shard // num_key_value_heads
          SCREAMING_SNAKE_CASE					:			int    	=       dim // num_key_value_heads
     else:  # compatibility with other checkpoints
          SCREAMING_SNAKE_CASE					:			Tuple    	=       n_heads
          SCREAMING_SNAKE_CASE					:			List[Any]    	=       n_heads_per_shard
          SCREAMING_SNAKE_CASE					:			List[str]    	=       dim

     # permute for sliced rotary
     def permute(a_       ,      a_=n_heads       ,      a_=dim       ,      a_=dim		):
          return w.view(a_       ,      dima // n_heads // 2       ,      2       ,      a_		).transpose(1       ,      2		).reshape(a_       ,      a_		)

     print(f"""Fetching all parameters from the checkpoint at {input_base_path}."""		)
     # Load weights
     if model_size == "7B":
          # Not sharded
          # (The sharded implementation would also work, but this is simpler.)
          SCREAMING_SNAKE_CASE					:			Tuple    	=       torch.load(os.path.join(a_       ,      'consolidated.00.pth'		)       ,      map_location='cpu'		)
     else:
          # Sharded
          SCREAMING_SNAKE_CASE					:			Optional[int]    	=       [
              torch.load(os.path.join(a_       ,      f"""consolidated.{i:02d}.pth"""		)       ,      map_location='cpu'		)
              for i in range(a_		)
          ]
     SCREAMING_SNAKE_CASE					:			Optional[int]    	=       0
     SCREAMING_SNAKE_CASE					:			Union[str, Any]    	=       {'weight_map': {}}
     for layer_i in range(a_		):
          SCREAMING_SNAKE_CASE					:			Optional[int]    	=       f"""pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin"""
          if model_size == "7B":
               # Unsharded
               SCREAMING_SNAKE_CASE					:			List[Any]    	=       {
                   f"""model.layers.{layer_i}.self_attn.q_proj.weight""": permute(
                       loaded[f"""layers.{layer_i}.attention.wq.weight"""]		),
                   f"""model.layers.{layer_i}.self_attn.k_proj.weight""": permute(
                       loaded[f"""layers.{layer_i}.attention.wk.weight"""]		),
                   f"""model.layers.{layer_i}.self_attn.v_proj.weight""": loaded[f"""layers.{layer_i}.attention.wv.weight"""],
                   f"""model.layers.{layer_i}.self_attn.o_proj.weight""": loaded[f"""layers.{layer_i}.attention.wo.weight"""],
                   f"""model.layers.{layer_i}.mlp.gate_proj.weight""": loaded[f"""layers.{layer_i}.feed_forward.w1.weight"""],
                   f"""model.layers.{layer_i}.mlp.down_proj.weight""": loaded[f"""layers.{layer_i}.feed_forward.w2.weight"""],
                   f"""model.layers.{layer_i}.mlp.up_proj.weight""": loaded[f"""layers.{layer_i}.feed_forward.w3.weight"""],
                   f"""model.layers.{layer_i}.input_layernorm.weight""": loaded[f"""layers.{layer_i}.attention_norm.weight"""],
                   f"""model.layers.{layer_i}.post_attention_layernorm.weight""": loaded[f"""layers.{layer_i}.ffn_norm.weight"""],
               }
          else:
               # Sharded
               # Note that attention.w{q,k,v,o}, feed_fordward.w[1,2,3], attention_norm.weight and ffn_norm.weight share
               # the same storage object, saving attention_norm and ffn_norm will save other weights too, which is
               # redundant as other weights will be stitched from multiple shards. To avoid that, they are cloned.

               SCREAMING_SNAKE_CASE					:			str    	=       {
                   f"""model.layers.{layer_i}.input_layernorm.weight""": loaded[0][
                       f"""layers.{layer_i}.attention_norm.weight"""
                   ].clone(),
                   f"""model.layers.{layer_i}.post_attention_layernorm.weight""": loaded[0][
                       f"""layers.{layer_i}.ffn_norm.weight"""
                   ].clone(),
               }
               SCREAMING_SNAKE_CASE					:			Any    	=       permute(
                   torch.cat(
                       [
                           loaded[i][f"""layers.{layer_i}.attention.wq.weight"""].view(a_       ,      a_       ,      a_		)
                           for i in range(a_		)
                       ]       ,      dim=0       ,      ).reshape(a_       ,      a_		)		)
               SCREAMING_SNAKE_CASE					:			int    	=       permute(
                   torch.cat(
                       [
                           loaded[i][f"""layers.{layer_i}.attention.wk.weight"""].view(
                               a_       ,      a_       ,      a_		)
                           for i in range(a_		)
                       ]       ,      dim=0       ,      ).reshape(a_       ,      a_		)       ,      a_       ,      a_       ,      a_       ,      )
               SCREAMING_SNAKE_CASE					:			Optional[int]    	=       torch.cat(
                   [
                       loaded[i][f"""layers.{layer_i}.attention.wv.weight"""].view(
                           a_       ,      a_       ,      a_		)
                       for i in range(a_		)
                   ]       ,      dim=0       ,      ).reshape(a_       ,      a_		)

               SCREAMING_SNAKE_CASE					:			List[Any]    	=       torch.cat(
                   [loaded[i][f"""layers.{layer_i}.attention.wo.weight"""] for i in range(a_		)]       ,      dim=1		)
               SCREAMING_SNAKE_CASE					:			List[Any]    	=       torch.cat(
                   [loaded[i][f"""layers.{layer_i}.feed_forward.w1.weight"""] for i in range(a_		)]       ,      dim=0		)
               SCREAMING_SNAKE_CASE					:			int    	=       torch.cat(
                   [loaded[i][f"""layers.{layer_i}.feed_forward.w2.weight"""] for i in range(a_		)]       ,      dim=1		)
               SCREAMING_SNAKE_CASE					:			List[Any]    	=       torch.cat(
                   [loaded[i][f"""layers.{layer_i}.feed_forward.w3.weight"""] for i in range(a_		)]       ,      dim=0		)

          SCREAMING_SNAKE_CASE					:			Optional[Any]    	=       inv_freq
          for k, v in state_dict.items():
               SCREAMING_SNAKE_CASE					:			Tuple    	=       filename
               param_count += v.numel()
          torch.save(a_       ,      os.path.join(a_       ,      a_		)		)

     SCREAMING_SNAKE_CASE					:			Dict    	=       f"""pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin"""
     if model_size == "7B":
          # Unsharded
          SCREAMING_SNAKE_CASE					:			str    	=       {
              'model.embed_tokens.weight': loaded['tok_embeddings.weight'],
              'model.norm.weight': loaded['norm.weight'],
              'lm_head.weight': loaded['output.weight'],
          }
     else:
          SCREAMING_SNAKE_CASE					:			Dict    	=       {
              'model.norm.weight': loaded[0]['norm.weight'],
              'model.embed_tokens.weight': torch.cat(
                  [loaded[i]['tok_embeddings.weight'] for i in range(a_		)]       ,      dim=1		),
              'lm_head.weight': torch.cat([loaded[i]['output.weight'] for i in range(a_		)]       ,      dim=0		),
          }

     for k, v in state_dict.items():
          SCREAMING_SNAKE_CASE					:			Dict    	=       filename
          param_count += v.numel()
     torch.save(a_       ,      os.path.join(a_       ,      a_		)		)

     # Write configs
     SCREAMING_SNAKE_CASE					:			Optional[int]    	=       {'total_size': param_count * 2}
     write_json(a_       ,      os.path.join(a_       ,      'pytorch_model.bin.index.json'		)		)
     SCREAMING_SNAKE_CASE					:			Any    	=       params['ffn_dim_multiplier'] if 'ffn_dim_multiplier' in params else 1
     SCREAMING_SNAKE_CASE					:			List[str]    	=       params['multiple_of'] if 'multiple_of' in params else 256
     SCREAMING_SNAKE_CASE					:			List[str]    	=       LlamaConfig(
         hidden_size=a_       ,      intermediate_size=compute_intermediate_size(a_       ,      a_       ,      a_		)       ,      num_attention_heads=params['n_heads']       ,      num_hidden_layers=params['n_layers']       ,      rms_norm_eps=params['norm_eps']       ,      num_key_value_heads=a_       ,      )
     config.save_pretrained(a_		)

     # Make space so we can load the model properly now.
     del state_dict
     del loaded
     gc.collect()

     print('Loading the checkpoint in a Llama model.'		)
     SCREAMING_SNAKE_CASE					:			Optional[int]    	=       LlamaForCausalLM.from_pretrained(a_       ,      torch_dtype=torch.floataa       ,      low_cpu_mem_usage=a_		)
     # Avoid saving this as part of the config.
     del model.config._name_or_path

     print('Saving in the Transformers format.'		)
     model.save_pretrained(a_       ,      safe_serialization=a_		)
     shutil.rmtree(a_		)


def     __lowerCAmelCase						(       a_       ,      a_		)      ->	Optional[int]:





     '''simple docstring'''





     SCREAMING_SNAKE_CASE					:			Dict    	=       LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast
     print(f"""Saving a {tokenizer_class.__name__} to {tokenizer_path}."""		)
     SCREAMING_SNAKE_CASE					:			Optional[int]    	=       tokenizer_class(a_		)
     tokenizer.save_pretrained(a_		)


def     __lowerCAmelCase						(       )      ->	str:





     '''simple docstring'''





     SCREAMING_SNAKE_CASE					:			Any    	=       argparse.ArgumentParser()
     parser.add_argument(
         '--input_dir'       ,      help='Location of LLaMA weights, which contains tokenizer.model and model folders'       ,      )
     parser.add_argument(
         '--model_size'       ,      choices=['7B', '7Bf', '13B', '13Bf', '30B', '65B', '70B', '70Bf', 'tokenizer_only']       ,      )
     parser.add_argument(
         '--output_dir'       ,      help='Location to write HF model and tokenizer'       ,      )
     parser.add_argument('--safe_serialization'       ,      type=a_       ,      help='Whether or not to save using `safetensors`.'		)
     SCREAMING_SNAKE_CASE					:			Optional[int]    	=       parser.parse_args()
     if args.model_size != "tokenizer_only":
          write_model(
              model_path=args.output_dir       ,      input_base_path=os.path.join(args.input_dir       ,      args.model_size		)       ,      model_size=args.model_size       ,      safe_serialization=args.safe_serialization       ,      )
     SCREAMING_SNAKE_CASE					:			Optional[int]    	=       os.path.join(args.input_dir       ,      'tokenizer.model'		)
     write_tokenizer(args.output_dir       ,      a_		)


if __name__ == "__main__":
 main()




'''simple docstring'''





import warnings
from typing import List, Optional, Tuple, Union

import numpy as np
import PIL
import torch

from ...models import UNetaDModel
from ...schedulers import RePaintScheduler
from ...utils import PIL_INTERPOLATION, logging, randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput


_lowerCAmelCase  :Union[str, Any]  				=    logging.get_logger(__name__)  # pylint: disable=invalid-name


def     __lowerCAmelCase						(       a_		)      ->	List[Any]:





     '''simple docstring'''





     warnings.warn(
         'The preprocess method is deprecated and will be removed in a future version. Please'
         ' use VaeImageProcessor.preprocess instead'       ,      a_       ,      )
     if isinstance(a_       ,      torch.Tensor		):
          return image
     elif isinstance(a_       ,      PIL.Image.Image		):
          SCREAMING_SNAKE_CASE					:			str    	=       [image]

     if isinstance(image[0]       ,      PIL.Image.Image		):
          SCREAMING_SNAKE_CASE	,   SCREAMING_SNAKE_CASE					:			List[str]    	=       image[0].size
          SCREAMING_SNAKE_CASE	,   SCREAMING_SNAKE_CASE					:			str    	=       (x - x % 8 for x in (w, h))  # resize to integer multiple of 8

          SCREAMING_SNAKE_CASE					:			Any    	=       [np.array(i.resize((w, h)       ,      resample=PIL_INTERPOLATION['lanczos']		)		)[None, :] for i in image]
          SCREAMING_SNAKE_CASE					:			List[Any]    	=       np.concatenate(a_       ,      axis=0		)
          SCREAMING_SNAKE_CASE					:			Tuple    	=       np.array(a_		).astype(np.floataa		) / 255.0
          SCREAMING_SNAKE_CASE					:			Tuple    	=       image.transpose(0       ,      3       ,      1       ,      2		)
          SCREAMING_SNAKE_CASE					:			Dict    	=       2.0 * image - 1.0
          SCREAMING_SNAKE_CASE					:			int    	=       torch.from_numpy(a_		)
     elif isinstance(image[0]       ,      torch.Tensor		):
          SCREAMING_SNAKE_CASE					:			Tuple    	=       torch.cat(a_       ,      dim=0		)
     return image


def     __lowerCAmelCase						(       a_		)      ->	List[Any]:





     '''simple docstring'''





     if isinstance(a_       ,      torch.Tensor		):
          return mask
     elif isinstance(a_       ,      PIL.Image.Image		):
          SCREAMING_SNAKE_CASE					:			Optional[int]    	=       [mask]

     if isinstance(mask[0]       ,      PIL.Image.Image		):
          SCREAMING_SNAKE_CASE	,   SCREAMING_SNAKE_CASE					:			List[Any]    	=       mask[0].size
          SCREAMING_SNAKE_CASE	,   SCREAMING_SNAKE_CASE					:			Optional[Any]    	=       (x - x % 32 for x in (w, h))  # resize to integer multiple of 32
          SCREAMING_SNAKE_CASE					:			Tuple    	=       [np.array(m.convert('L'		).resize((w, h)       ,      resample=PIL_INTERPOLATION['nearest']		)		)[None, :] for m in mask]
          SCREAMING_SNAKE_CASE					:			Union[str, Any]    	=       np.concatenate(a_       ,      axis=0		)
          SCREAMING_SNAKE_CASE					:			List[Any]    	=       mask.astype(np.floataa		) / 255.0
          SCREAMING_SNAKE_CASE					:			Optional[Any]    	=       0
          SCREAMING_SNAKE_CASE					:			Optional[Any]    	=       1
          SCREAMING_SNAKE_CASE					:			str    	=       torch.from_numpy(a_		)
     elif isinstance(mask[0]       ,      torch.Tensor		):
          SCREAMING_SNAKE_CASE					:			List[Any]    	=       torch.cat(a_       ,      dim=0		)
     return mask






class 				UpperCAmelCase (       _SCREAMING_SNAKE_CASE ):




    '''simple docstring'''







    snake_case__							:   UNetaDModel
    snake_case__							:   RePaintScheduler






    def __init__(       self    ,							lowercase__    ,							lowercase__ )							-> Union[str, Any]:
         super().__init__()
         self.register_modules(unet=lowercase__    ,							scheduler=lowercase__ )






    @torch.no_grad()
    def __call__(       self    ,							lowercase__    ,							lowercase__    ,							lowercase__ = 250    ,							lowercase__ = 0.0    ,							lowercase__ = 10    ,							lowercase__ = 10    ,							lowercase__ = None    ,							lowercase__ = "pil"    ,							lowercase__ = True    ,							)							-> Union[ImagePipelineOutput, Tuple]:
         SCREAMING_SNAKE_CASE					:			Optional[int]    	=       image

         SCREAMING_SNAKE_CASE					:			List[str]    	=       _preprocess_image(lowercase__ )
         SCREAMING_SNAKE_CASE					:			List[str]    	=       original_image.to(device=self.device    ,							dtype=self.unet.dtype )
         SCREAMING_SNAKE_CASE					:			Any    	=       _preprocess_mask(lowercase__ )
         SCREAMING_SNAKE_CASE					:			str    	=       mask_image.to(device=self.device    ,							dtype=self.unet.dtype )

         SCREAMING_SNAKE_CASE					:			int    	=       original_image.shape[0]

         # sample gaussian noise to begin the loop
         if isinstance(lowercase__    ,							lowercase__ ) and len(lowercase__ ) != batch_size:
              raise ValueError(
                  F"""You have passed a list of generators of length {len(lowercase__ )}, but requested an effective batch"""
                  F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""" )

         SCREAMING_SNAKE_CASE					:			Dict    	=       original_image.shape
         SCREAMING_SNAKE_CASE					:			Any    	=       randn_tensor(lowercase__    ,							generator=lowercase__    ,							device=self.device    ,							dtype=self.unet.dtype )

         # set step values
         self.scheduler.set_timesteps(lowercase__    ,							lowercase__    ,							lowercase__    ,							self.device )
         SCREAMING_SNAKE_CASE					:			Optional[Any]    	=       eta

         SCREAMING_SNAKE_CASE					:			List[Any]    	=       self.scheduler.timesteps[0] + 1
         SCREAMING_SNAKE_CASE					:			Tuple    	=       generator[0] if isinstance(lowercase__    ,							lowercase__ ) else generator
         for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ):
              if t < t_last:
                   # predict the noise residual
                   SCREAMING_SNAKE_CASE					:			Optional[int]    	=       self.unet(lowercase__    ,							lowercase__ ).sample
                   # compute previous image: x_t -> x_t-1
                   SCREAMING_SNAKE_CASE					:			Tuple    	=       self.scheduler.step(lowercase__    ,							lowercase__    ,							lowercase__    ,							lowercase__    ,							lowercase__    ,							lowercase__ ).prev_sample

              else:
                   # compute the reverse: x_t-1 -> x_t
                   SCREAMING_SNAKE_CASE					:			List[str]    	=       self.scheduler.undo_step(lowercase__    ,							lowercase__    ,							lowercase__ )
              SCREAMING_SNAKE_CASE					:			int    	=       t

         SCREAMING_SNAKE_CASE					:			List[Any]    	=       (image / 2 + 0.5).clamp(0    ,							1 )
         SCREAMING_SNAKE_CASE					:			Tuple    	=       image.cpu().permute(0    ,							2    ,							3    ,							1 ).numpy()
         if output_type == "pil":
              SCREAMING_SNAKE_CASE					:			Dict    	=       self.numpy_to_pil(lowercase__ )

         if not return_dict:
              return (image,)

         return ImagePipelineOutput(images=lowercase__ )



