






import argparse

import requests
import torch
from PIL import Image

from transformers import (
    CLIPSegConfig,
    CLIPSegForImageSegmentation,
    CLIPSegProcessor,
    CLIPSegTextConfig,
    CLIPSegVisionConfig,
    CLIPTokenizer,
    ViTImageProcessor,
)
def    a__    (	A       ):
   lowercase__    :						Tuple       =			CLIPSegTextConfig()
   lowercase__    :						List[Any]       =			CLIPSegVisionConfig(patch_size=16       )

   lowercase__    :						Dict       =			True if """refined""" in model_name else False
   lowercase__    :						Tuple       =			16 if """rd16""" in model_name else 64

   lowercase__    :						Optional[int]       =			CLIPSegConfig.from_text_vision_configs(
       A		,					A		,					use_complex_transposed_convolution=A		,					reduce_dim=A		,					)
   return config
def    a__    (	A       ):
   # update prefixes
   if "clip_model" in name:
      lowercase__    :						List[str]       =			name.replace("""clip_model"""		,					"""clip"""       )
   if "transformer" in name:
      if "visual" in name:
         lowercase__    :						Dict       =			name.replace("""visual.transformer"""		,					"""vision_model"""       )
      else:
         lowercase__    :						List[str]       =			name.replace("""transformer"""		,					"""text_model"""       )
   if "resblocks" in name:
      lowercase__    :						Optional[int]       =			name.replace("""resblocks"""		,					"""encoder.layers"""       )
   if "ln_1" in name:
      lowercase__    :						str       =			name.replace("""ln_1"""		,					"""layer_norm1"""       )
   if "ln_2" in name:
      lowercase__    :						Union[str, Any]       =			name.replace("""ln_2"""		,					"""layer_norm2"""       )
   if "c_fc" in name:
      lowercase__    :						Optional[Any]       =			name.replace("""c_fc"""		,					"""fc1"""       )
   if "c_proj" in name:
      lowercase__    :						Any       =			name.replace("""c_proj"""		,					"""fc2"""       )
   if "attn" in name and "self" not in name:
      lowercase__    :						List[str]       =			name.replace("""attn"""		,					"""self_attn"""       )
   # text encoder
   if "token_embedding" in name:
      lowercase__    :						Optional[Any]       =			name.replace("""token_embedding"""		,					"""text_model.embeddings.token_embedding"""       )
   if "positional_embedding" in name and "visual" not in name:
      lowercase__    :						List[str]       =			name.replace("""positional_embedding"""		,					"""text_model.embeddings.position_embedding.weight"""       )
   if "ln_final" in name:
      lowercase__    :						Optional[Any]       =			name.replace("""ln_final"""		,					"""text_model.final_layer_norm"""       )
   # vision encoder
   if "visual.class_embedding" in name:
      lowercase__    :						Optional[Any]       =			name.replace("""visual.class_embedding"""		,					"""vision_model.embeddings.class_embedding"""       )
   if "visual.conv1" in name:
      lowercase__    :						Optional[Any]       =			name.replace("""visual.conv1"""		,					"""vision_model.embeddings.patch_embedding"""       )
   if "visual.positional_embedding" in name:
      lowercase__    :						Dict       =			name.replace("""visual.positional_embedding"""		,					"""vision_model.embeddings.position_embedding.weight"""       )
   if "visual.ln_pre" in name:
      lowercase__    :						Union[str, Any]       =			name.replace("""visual.ln_pre"""		,					"""vision_model.pre_layrnorm"""       )
   if "visual.ln_post" in name:
      lowercase__    :						List[str]       =			name.replace("""visual.ln_post"""		,					"""vision_model.post_layernorm"""       )
   # projection layers
   if "visual.proj" in name:
      lowercase__    :						Optional[Any]       =			name.replace("""visual.proj"""		,					"""visual_projection.weight"""       )
   if "text_projection" in name:
      lowercase__    :						Optional[Any]       =			name.replace("""text_projection"""		,					"""text_projection.weight"""       )
   # decoder
   if "trans_conv" in name:
      lowercase__    :						List[Any]       =			name.replace("""trans_conv"""		,					"""transposed_convolution"""       )
   if "film_mul" in name or "film_add" in name or "reduce" in name or "transposed_convolution" in name:
      lowercase__    :						Dict       =			"""decoder.""" + name
   if "blocks" in name:
      lowercase__    :						Union[str, Any]       =			name.replace("""blocks"""		,					"""decoder.layers"""       )
   if "linear1" in name:
      lowercase__    :						str       =			name.replace("""linear1"""		,					"""mlp.fc1"""       )
   if "linear2" in name:
      lowercase__    :						Any       =			name.replace("""linear2"""		,					"""mlp.fc2"""       )
   if "norm1" in name and "layer_" not in name:
      lowercase__    :						List[str]       =			name.replace("""norm1"""		,					"""layer_norm1"""       )
   if "norm2" in name and "layer_" not in name:
      lowercase__    :						Dict       =			name.replace("""norm2"""		,					"""layer_norm2"""       )

   return name
def    a__    (	A		,					A       ):
   for key in orig_state_dict.copy().keys():
      lowercase__    :						Dict       =			orig_state_dict.pop(A       )

      if key.startswith("""clip_model"""       ) and "attn.in_proj" in key:
         lowercase__    :						int       =			key.split("""."""       )
         if "visual" in key:
            lowercase__    :						str       =			int(key_split[4]       )
            lowercase__    :						List[Any]       =			config.vision_config.hidden_size
            lowercase__    :						Tuple       =			"""vision_model"""
         else:
            lowercase__    :						int       =			int(key_split[3]       )
            lowercase__    :						Union[str, Any]       =			config.text_config.hidden_size
            lowercase__    :						Dict       =			"""text_model"""

         if "weight" in key:
            lowercase__    :						List[Any]       =			val[:dim, :]
            lowercase__    :						List[Any]       =			val[
                dim : dim * 2, :
            ]
            lowercase__    :						Dict       =			val[-dim:, :]
         else:
            lowercase__    :						Optional[Any]       =			val[:dim]
            lowercase__    :						Any       =			val[dim : dim * 2]
            lowercase__    :						Union[str, Any]       =			val[-dim:]
      elif "self_attn" in key and "out_proj" not in key:
         lowercase__    :						Optional[Any]       =			key.split("""."""       )
         lowercase__    :						Optional[int]       =			int(key_split[1]       )
         lowercase__    :						Dict       =			config.reduce_dim
         if "weight" in key:
            lowercase__    :						int       =			val[:dim, :]
            lowercase__    :						Optional[Any]       =			val[dim : dim * 2, :]
            lowercase__    :						Tuple       =			val[-dim:, :]
         else:
            lowercase__    :						Dict       =			val[:dim]
            lowercase__    :						Optional[Any]       =			val[dim : dim * 2]
            lowercase__    :						Optional[Any]       =			val[-dim:]
      else:
         lowercase__    :						Union[str, Any]       =			rename_key(A       )
         if "visual_projection" in new_name or "text_projection" in new_name:
            lowercase__    :						Optional[int]       =			val.T
         lowercase__    :						int       =			val

   return orig_state_dict
def    a__    (	):
   lowercase__    :						List[Any]       =			"""http://images.cocodataset.org/val2017/000000039769.jpg"""
   lowercase__    :						Tuple       =			Image.open(requests.get(A		,					stream=A       ).raw       )
   return image
def    a__    (	A		,					A		,					A		,					A       ):
   lowercase__    :						Optional[int]       =			get_clipseg_config(A       )
   lowercase__    :						int       =			CLIPSegForImageSegmentation(A       )
   model.eval()

   lowercase__    :						Optional[Any]       =			torch.load(A		,					map_location="""cpu"""       )

   # remove some keys
   for key in state_dict.copy().keys():
      if key.startswith("""model"""       ):
         state_dict.pop(A		,					A       )

    # rename some keys
   lowercase__    :						Tuple       =			convert_state_dict(A		,					A       )
   lowercase__  ,       lowercase__    :						str       =			model.load_state_dict(A		,					strict=A       )

   if missing_keys != ["clip.text_model.embeddings.position_ids", "clip.vision_model.embeddings.position_ids"]:
      raise ValueError("""Missing keys that are not expected: {}""".format(A       )       )
   if unexpected_keys != ["decoder.reduce.weight", "decoder.reduce.bias"]:
      raise ValueError(F'''Unexpected keys: {unexpected_keys}'''       )

   lowercase__    :						Dict       =			ViTImageProcessor(size=352       )
   lowercase__    :						Optional[int]       =			CLIPTokenizer.from_pretrained("""openai/clip-vit-base-patch32"""       )
   lowercase__    :						List[Any]       =			CLIPSegProcessor(image_processor=A		,					tokenizer=A       )

   lowercase__    :						str       =			prepare_img()
   lowercase__    :						Optional[int]       =			["""a glass""", """something to fill""", """wood""", """a jar"""]

   lowercase__    :						Union[str, Any]       =			processor(text=A		,					images=[image] * len(A       )		,					padding="""max_length"""		,					return_tensors="""pt"""       )

   with torch.no_grad():
      lowercase__    :						Tuple       =			model(**A       )

   # verify values
   lowercase__    :						List[Any]       =			torch.tensor([0.1_1_1_0, -0.1_8_8_2, 0.1_6_4_5]       )
   lowercase__    :						Dict       =			torch.tensor([0.2_6_9_2, -0.7_1_9_7, -0.1_3_2_8]       )
   if model_name == "clipseg-rd64-refined":
      lowercase__    :						Any       =			torch.tensor(
          [[-1_0.0_4_0_7, -9.9_4_3_1, -1_0.2_6_4_6], [-9.9_7_5_1, -9.7_0_6_4, -9.9_5_8_6], [-9.6_8_9_1, -9.5_6_4_5, -9.9_6_1_8]]       )
   elif model_name == "clipseg-rd64":
      lowercase__    :						Any       =			torch.tensor(
          [[-7.2_8_7_7, -7.2_7_1_1, -7.2_4_6_3], [-7.2_6_5_2, -7.2_7_8_0, -7.2_5_2_0], [-7.2_2_3_9, -7.2_2_0_4, -7.2_0_0_1]]       )
   elif model_name == "clipseg-rd16":
      lowercase__    :						int       =			torch.tensor(
          [[-6.3_9_5_5, -6.4_0_5_5, -6.4_1_5_1], [-6.3_9_1_1, -6.4_0_3_3, -6.4_1_0_0], [-6.3_4_7_4, -6.3_7_0_2, -6.3_7_6_2]]       )
   else:
      raise ValueError(F'''Model name {model_name} not supported.'''       )

   assert torch.allclose(outputs.logits[0, :3, :3]		,					A		,					atol=1e-3       )
   assert torch.allclose(outputs.conditional_embeddings[0, :3]		,					A		,					atol=1e-3       )
   assert torch.allclose(outputs.pooled_output[0, :3]		,					A		,					atol=1e-3       )
   print("""Looks ok!"""       )

   if pytorch_dump_folder_path is not None:
      print(F'''Saving model and processor to {pytorch_dump_folder_path}'''       )
      model.save_pretrained(A       )
      processor.save_pretrained(A       )

   if push_to_hub:
      print(F'''Pushing model and processor for {model_name} to the hub'''       )
      model.push_to_hub(F'''CIDAS/{model_name}'''       )
      processor.push_to_hub(F'''CIDAS/{model_name}'''       )


if __name__ == "__main__":
 a 			=							argparse.ArgumentParser()
 # Required parameters
 parser.add_argument(
     '--model_name',
     default='clipseg-rd64',
     type=str,
     choices=['clipseg-rd16', 'clipseg-rd64', 'clipseg-rd64-refined'],
     help=(
         'Name of the model. Supported models are: clipseg-rd64, clipseg-rd16 and clipseg-rd64-refined (rd meaning'
         ' reduce dimension)'
     ),
 )
 parser.add_argument(
     '--checkpoint_path',
     default='/Users/nielsrogge/Documents/CLIPSeg/clip_plus_rd64-uni.pth',
     type=str,
     help=(
         'Path to the original checkpoint. Note that the script assumes that the checkpoint includes both CLIP and'
         ' the decoder weights.'
     ),
 )
 parser.add_argument(
     '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.'
 )
 parser.add_argument(
     '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.'
 )

 a 			=							parser.parse_args()
 convert_clipseg_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)










import argparse

import torch
from saprl.hub import distilhubert

from transformers import HubertConfig, HubertModel, WavaVecaFeatureExtractor, logging


logging.set_verbosity_info()
a 			=							logging.get_logger(__name__)

a 			=							{
    'post_extract_proj': 'feature_projection.projection',
    'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv',
    'self_attn.k_proj': 'encoder.layers.*.attention.k_proj',
    'self_attn.v_proj': 'encoder.layers.*.attention.v_proj',
    'self_attn.q_proj': 'encoder.layers.*.attention.q_proj',
    'self_attn.out_proj': 'encoder.layers.*.attention.out_proj',
    'self_attn_layer_norm': 'encoder.layers.*.layer_norm',
    'fc1': 'encoder.layers.*.feed_forward.intermediate_dense',
    'fc2': 'encoder.layers.*.feed_forward.output_dense',
    'final_layer_norm': 'encoder.layers.*.final_layer_norm',
    'encoder.layer_norm': 'encoder.layer_norm',
    'mask_emb': 'masked_spec_embed',
}
def    a__    (	A		,					A		,					A		,					A		,					A       ):
   for attribute in key.split("""."""       ):
      lowercase__    :						Dict       =			getattr(A		,					A       )

   if weight_type is not None:
      lowercase__    :						List[Any]       =			getattr(A		,					A       ).shape
   else:
      lowercase__    :						Tuple       =			hf_pointer.shape

   assert hf_shape == value.shape, (
       F'''Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be'''
       F''' {value.shape} for {full_name}'''
   )

   if weight_type == "weight":
      lowercase__    :						Dict       =			value
   elif weight_type == "weight_g":
      lowercase__    :						Any       =			value
   elif weight_type == "weight_v":
      lowercase__    :						Dict       =			value
   elif weight_type == "bias":
      lowercase__    :						Any       =			value
   else:
      lowercase__    :						Tuple       =			value

   logger.info(F'''{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.'''       )
def    a__    (	A		,					A       ):
   lowercase__    :						str       =			[]
   lowercase__    :						int       =			fairseq_model.state_dict()

   lowercase__    :						Tuple       =			hf_model.feature_extractor

   for name, value in fairseq_dict.items():
      lowercase__    :						Optional[int]       =			False
      if "conv_layers" in name:
         load_conv_layer(
             A		,					A		,					A		,					A		,					hf_model.config.feat_extract_norm == """group"""		,					)
         lowercase__    :						Optional[int]       =			True
      else:
         for key, mapped_key in MAPPING.items():
            lowercase__    :						Dict       =			mapped_key

            if key in name:
               lowercase__    :						int       =			True
               if "*" in mapped_key:
                  lowercase__    :						Any       =			name.split(A       )[0].split("""."""       )[-2]
                  lowercase__    :						int       =			mapped_key.replace("""*"""		,					A       )
               if "weight_g" in name:
                  lowercase__    :						Dict       =			"""weight_g"""
               elif "weight_v" in name:
                  lowercase__    :						Dict       =			"""weight_v"""
               elif "weight" in name:
                  lowercase__    :						Union[str, Any]       =			"""weight"""
               elif "bias" in name:
                  lowercase__    :						Optional[int]       =			"""bias"""
               else:
                  lowercase__    :						List[str]       =			None
               set_recursively(A		,					A		,					A		,					A		,					A       )
            continue
      if not is_used:
         unused_weights.append(A       )

   logger.warning(F'''Unused weights: {unused_weights}'''       )
def    a__    (	A		,					A		,					A		,					A		,					A       ):
   lowercase__    :						Optional[int]       =			full_name.split("""conv_layers."""       )[-1]
   lowercase__    :						int       =			name.split("""."""       )
   lowercase__    :						Optional[Any]       =			int(items[0]       )
   lowercase__    :						Optional[int]       =			int(items[1]       )

   if type_id == 0:
      if "bias" in name:
         assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, (
             F'''{full_name} has size {value.shape}, but'''
             F''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.'''
         )
         lowercase__    :						int       =			value
         logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.'''       )
      elif "weight" in name:
         assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, (
             F'''{full_name} has size {value.shape}, but'''
             F''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.'''
         )
         lowercase__    :						str       =			value
         logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.'''       )
   elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
      if "bias" in name:
         assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, (
             F'''{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was'''
             " found."
         )
         lowercase__    :						Any       =			value
         logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.'''       )
      elif "weight" in name:
         assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, (
             F'''{full_name} has size {value.shape}, but'''
             F''' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.'''
         )
         lowercase__    :						int       =			value
         logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.'''       )
   else:
      unused_weights.append(A       )
def    a__    (	A       ):
   lowercase__    :						Optional[Any]       =			HubertConfig()
   lowercase__    :						List[str]       =			model.config

   lowercase__    :						int       =			fs_config.activation_dropout
   lowercase__    :						Tuple       =			False
   lowercase__    :						Optional[Any]       =			fs_config.attention_dropout
   lowercase__    :						str       =			False
   lowercase__    :						List[Any]       =			eval(fs_config.extractor_conv_feature_layers       )
   lowercase__    :						Union[str, Any]       =			[x[0] for x in conv_layers]
   lowercase__    :						str       =			[x[1] for x in conv_layers]
   lowercase__    :						str       =			[x[2] for x in conv_layers]
   lowercase__    :						Any       =			"""gelu"""
   lowercase__    :						Optional[int]       =			"""layer""" if fs_config.extractor_mode == """layer_norm""" else """group"""
   lowercase__    :						Optional[int]       =			False
   lowercase__    :						Tuple       =			0.0
   lowercase__    :						Optional[Any]       =			0.0
   lowercase__    :						Optional[Any]       =			fs_config.activation_fn
   lowercase__    :						Optional[Any]       =			fs_config.dropout
   lowercase__    :						Any       =			fs_config.encoder_embed_dim
   lowercase__    :						List[Any]       =			0.0_2
   lowercase__    :						List[Any]       =			fs_config.encoder_ffn_embed_dim
   lowercase__    :						List[Any]       =			1e-5
   lowercase__    :						Dict       =			0.0
   lowercase__    :						List[Any]       =			fs_config.encoder_attention_heads
   lowercase__    :						List[str]       =			fs_config.conv_pos_groups
   lowercase__    :						List[Any]       =			fs_config.conv_pos
   lowercase__    :						Union[str, Any]       =			len(A       )
   lowercase__    :						List[str]       =			fs_config.encoder_layers

   return config
@torch.no_grad()
def    a__    (	A		,					A=None       ):
   lowercase__    :						List[str]       =			distilhubert().model.model

   if config_path is not None:
      lowercase__    :						List[str]       =			HubertConfig.from_pretrained(A       )
   else:
      lowercase__    :						List[str]       =			convert_config(A       )
   lowercase__    :						List[Any]       =			model.eval()

   lowercase__    :						Optional[Any]       =			WavaVecaFeatureExtractor(
       feature_size=1		,					sampling_rate=16_000		,					padding_value=0		,					do_normalize=A		,					return_attention_mask=A		,					)
   lowercase__    :						Union[str, Any]       =			HubertModel(A       )

   recursively_load_weights(A		,					A       )

   feature_extractor.save_pretrained(A       )
   hf_model.save_pretrained(A       )


if __name__ == "__main__":
 a 			=							argparse.ArgumentParser()
 parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.')
 parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert')
 a 			=							parser.parse_args()
 convert_hubert_checkpoint(args.pytorch_dump_folder_path, args.config_path)


