





from .constants import (
    MODEL_NAME,
    OPTIMIZER_NAME,
    RNG_STATE_NAME,
    SAFE_WEIGHTS_INDEX_NAME,
    SAFE_WEIGHTS_NAME,
    SCALER_NAME,
    SCHEDULER_NAME,
    TORCH_LAUNCH_PARAMS,
    WEIGHTS_INDEX_NAME,
    WEIGHTS_NAME,
)
from .dataclasses import (
    BnbQuantizationConfig,
    ComputeEnvironment,
    CustomDtype,
    DeepSpeedPlugin,
    DistributedDataParallelKwargs,
    DistributedType,
    DynamoBackend,
    FPaRecipeKwargs,
    FullyShardedDataParallelPlugin,
    GradientAccumulationPlugin,
    GradScalerKwargs,
    InitProcessGroupKwargs,
    KwargsHandler,
    LoggerType,
    MegatronLMPlugin,
    PrecisionType,
    ProjectConfiguration,
    RNGType,
    SageMakerDistributedType,
    TensorInformation,
    TorchDynamoPlugin,
)
from .environment import get_int_from_env, parse_choice_from_env, parse_flag_from_env
from .imports import (
    get_ccl_version,
    is_abit_bnb_available,
    is_abit_bnb_available,
    is_aim_available,
    is_bfaa_available,
    is_bnb_available,
    is_botoa_available,
    is_ccl_available,
    is_comet_ml_available,
    is_datasets_available,
    is_deepspeed_available,
    is_fpa_available,
    is_ipex_available,
    is_megatron_lm_available,
    is_mlflow_available,
    is_mps_available,
    is_npu_available,
    is_rich_available,
    is_safetensors_available,
    is_sagemaker_available,
    is_tensorboard_available,
    is_tpu_available,
    is_transformers_available,
    is_wandb_available,
    is_xpu_available,
)
from .modeling import (
    check_device_map,
    check_tied_parameters_in_config,
    check_tied_parameters_on_same_device,
    compute_module_sizes,
    convert_file_size_to_int,
    dtype_byte_size,
    find_tied_parameters,
    get_balanced_memory,
    get_max_layer_size,
    get_max_memory,
    get_mixed_precision_context_manager,
    id_tensor_storage,
    infer_auto_device_map,
    load_checkpoint_in_model,
    load_offloaded_weights,
    load_state_dict,
    named_module_tensors,
    retie_parameters,
    set_module_tensor_to_device,
    shard_checkpoint,
)
from .offload import (
    OffloadedWeightsLoader,
    PrefixedDataset,
    extract_submodules_state_dict,
    load_offloaded_weight,
    offload_state_dict,
    offload_weight,
    save_offload_index,
)
from .operations import (
    broadcast,
    broadcast_object_list,
    concatenate,
    convert_outputs_to_fpaa,
    convert_to_fpaa,
    find_batch_size,
    find_device,
    gather,
    gather_object,
    get_data_structure,
    honor_type,
    initialize_tensors,
    is_namedtuple,
    is_tensor_information,
    is_torch_tensor,
    listify,
    pad_across_processes,
    recursively_apply,
    reduce,
    send_to_device,
    slice_tensors,
)
from .versions import compare_versions, is_torch_version


if is_deepspeed_available():
					from .deepspeed import (
					    DeepSpeedEngineWrapper,
					    DeepSpeedOptimizerWrapper,
					    DeepSpeedSchedulerWrapper,
					    DummyOptim,
					    DummyScheduler,
					    HfDeepSpeedConfig,
					)

from .bnb import has_abit_bnb_layers, load_and_quantize_model
from .fsdp_utils import load_fsdp_model, load_fsdp_optimizer, save_fsdp_model, save_fsdp_optimizer
from .launch import (
    PrepareForLaunch,
    _filter_args,
    prepare_deepspeed_cmd_env,
    prepare_multi_gpu_env,
    prepare_sagemager_args_inputs,
    prepare_simple_launcher_cmd_env,
    prepare_tpu,
)
from .megatron_lm import (
    AbstractTrainStep,
    BertTrainStep,
    GPTTrainStep,
    MegatronEngine,
    MegatronLMDummyDataLoader,
    MegatronLMDummyScheduler,
    MegatronLMOptimizerWrapper,
    MegatronLMSchedulerWrapper,
    TaTrainStep,
    avg_losses_across_data_parallel_group,
    gather_across_data_parallel_groups,
)
from .megatron_lm import initialize as megatron_lm_initialize
from .megatron_lm import prepare_data_loader as megatron_lm_prepare_data_loader
from .megatron_lm import prepare_model as megatron_lm_prepare_model
from .megatron_lm import prepare_optimizer as megatron_lm_prepare_optimizer
from .megatron_lm import prepare_scheduler as megatron_lm_prepare_scheduler
from .memory import find_executable_batch_size, release_memory
from .other import (
    extract_model_from_parallel,
    get_pretty_name,
    is_port_in_use,
    merge_dicts,
    patch_environment,
    save,
    wait_for_everyone,
    write_basic_config,
)
from .random import set_seed, synchronize_rng_state, synchronize_rng_states
from .torch_xla import install_xla
from .tqdm import tqdm
from .transformer_engine import convert_model, has_transformer_engine_layers











import argparse
import json

import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image

from transformers import ViTImageProcessor, ViTMSNConfig, ViTMSNModel
from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD


torch.set_grad_enabled(False)





def      _UpperCamelCase  (a__ :Tuple ,      a__ :List[str]=False							):






							"""simple docstring"""





							UpperCamelCase__					  =      []
							for i in range(config.num_hidden_layers							):
														# encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
														rename_keys.append((f"""module.blocks.{i}.norm1.weight""", f"""vit.encoder.layer.{i}.layernorm_before.weight""")							)
														rename_keys.append((f"""module.blocks.{i}.norm1.bias""", f"""vit.encoder.layer.{i}.layernorm_before.bias""")							)
														rename_keys.append(
														    (f"""module.blocks.{i}.attn.proj.weight""", f"""vit.encoder.layer.{i}.attention.output.dense.weight""")							)
														rename_keys.append((f"""module.blocks.{i}.attn.proj.bias""", f"""vit.encoder.layer.{i}.attention.output.dense.bias""")							)
														rename_keys.append((f"""module.blocks.{i}.norm2.weight""", f"""vit.encoder.layer.{i}.layernorm_after.weight""")							)
														rename_keys.append((f"""module.blocks.{i}.norm2.bias""", f"""vit.encoder.layer.{i}.layernorm_after.bias""")							)
														rename_keys.append((f"""module.blocks.{i}.mlp.fc1.weight""", f"""vit.encoder.layer.{i}.intermediate.dense.weight""")							)
														rename_keys.append((f"""module.blocks.{i}.mlp.fc1.bias""", f"""vit.encoder.layer.{i}.intermediate.dense.bias""")							)
														rename_keys.append((f"""module.blocks.{i}.mlp.fc2.weight""", f"""vit.encoder.layer.{i}.output.dense.weight""")							)
														rename_keys.append((f"""module.blocks.{i}.mlp.fc2.bias""", f"""vit.encoder.layer.{i}.output.dense.bias""")							)

							# projection layer + position embeddings
							rename_keys.extend(
							    [
							        ("""module.cls_token""", """vit.embeddings.cls_token"""),
							        ("""module.patch_embed.proj.weight""", """vit.embeddings.patch_embeddings.projection.weight"""),
							        ("""module.patch_embed.proj.bias""", """vit.embeddings.patch_embeddings.projection.bias"""),
							        ("""module.pos_embed""", """vit.embeddings.position_embeddings"""),
							    ]							)

							if base_model:
														# layernorm + pooler
														rename_keys.extend(
														    [
														        ("""module.norm.weight""", """layernorm.weight"""),
														        ("""module.norm.bias""", """layernorm.bias"""),
														    ]							)

														# if just the base model, we should remove "vit" from all keys that start with "vit"
														UpperCamelCase__					  =      [(pair[0], pair[1][4:]) if pair[1].startswith("""vit"""							) else pair for pair in rename_keys]
							else:
														# layernorm + classification head
														rename_keys.extend(
														    [
														        ("""norm.weight""", """vit.layernorm.weight"""),
														        ("""norm.bias""", """vit.layernorm.bias"""),
														        ("""head.weight""", """classifier.weight"""),
														        ("""head.bias""", """classifier.bias"""),
														    ]							)

							return rename_keys





def      _UpperCamelCase  (a__ :int ,      a__ :Tuple ,      a__ :Union[str, Any]=False							):






							"""simple docstring"""





							for i in range(config.num_hidden_layers							):
														if base_model:
																					UpperCamelCase__					  =      """"""
														else:
																					UpperCamelCase__					  =      """vit."""
														# read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
														UpperCamelCase__					  =      state_dict.pop(f"""module.blocks.{i}.attn.qkv.weight"""							)
														UpperCamelCase__					  =      state_dict.pop(f"""module.blocks.{i}.attn.qkv.bias"""							)
														# next, add query, keys and values (in that order) to the state dict
														UpperCamelCase__					  =      in_proj_weight[
														    : config.hidden_size, :
														]
														UpperCamelCase__					  =      in_proj_bias[: config.hidden_size]
														UpperCamelCase__					  =      in_proj_weight[
														    config.hidden_size : config.hidden_size * 2, :
														]
														UpperCamelCase__					  =      in_proj_bias[
														    config.hidden_size : config.hidden_size * 2
														]
														UpperCamelCase__					  =      in_proj_weight[
														    -config.hidden_size :, :
														]
														UpperCamelCase__					  =      in_proj_bias[-config.hidden_size :]





def      _UpperCamelCase  (a__ :int							):






							"""simple docstring"""





							UpperCamelCase__					  =      ["""head.weight""", """head.bias"""]
							for k in ignore_keys:
														state_dict.pop(a__ ,      a__							)





def      _UpperCamelCase  (a__ :Optional[int]							):






							"""simple docstring"""





							UpperCamelCase__					  =      [
							    """module.fc.fc1.weight""",
							    """module.fc.fc1.bias""",
							    """module.fc.bn1.weight""",
							    """module.fc.bn1.bias""",
							    """module.fc.bn1.running_mean""",
							    """module.fc.bn1.running_var""",
							    """module.fc.bn1.num_batches_tracked""",
							    """module.fc.fc2.weight""",
							    """module.fc.fc2.bias""",
							    """module.fc.bn2.weight""",
							    """module.fc.bn2.bias""",
							    """module.fc.bn2.running_mean""",
							    """module.fc.bn2.running_var""",
							    """module.fc.bn2.num_batches_tracked""",
							    """module.fc.fc3.weight""",
							    """module.fc.fc3.bias""",
							]
							for k in ignore_keys:
														state_dict.pop(a__ ,      a__							)





def      _UpperCamelCase  (a__ :List[str] ,      a__ :Any ,      a__ :str							):






							"""simple docstring"""





							UpperCamelCase__					  =      dct.pop(a__							)
							UpperCamelCase__					  =      val





def      _UpperCamelCase  (a__ :Dict ,      a__ :Dict							):






							"""simple docstring"""





							UpperCamelCase__					  =      ViTMSNConfig()
							UpperCamelCase__					  =      1000

							UpperCamelCase__					  =      """datasets/huggingface/label-files"""
							UpperCamelCase__					  =      """imagenet-1k-id2label.json"""
							UpperCamelCase__					  =      json.load(open(hf_hub_download(a__ ,      a__							) ,      """r"""							)							)
							UpperCamelCase__					  =      {int(a__							): v for k, v in idalabel.items()}
							UpperCamelCase__					  =      idalabel
							UpperCamelCase__					  =      {v: k for k, v in idalabel.items()}

							if "s16" in checkpoint_url:
														UpperCamelCase__					  =      384
														UpperCamelCase__					  =      1536
														UpperCamelCase__					  =      6
							elif "l16" in checkpoint_url:
														UpperCamelCase__					  =      1024
														UpperCamelCase__					  =      4096
														UpperCamelCase__					  =      24
														UpperCamelCase__					  =      16
														UpperCamelCase__					  =      0.1
							elif "b4" in checkpoint_url:
														UpperCamelCase__					  =      4
							elif "l7" in checkpoint_url:
														UpperCamelCase__					  =      7
														UpperCamelCase__					  =      1024
														UpperCamelCase__					  =      4096
														UpperCamelCase__					  =      24
														UpperCamelCase__					  =      16
														UpperCamelCase__					  =      0.1

							UpperCamelCase__					  =      ViTMSNModel(a__							)

							UpperCamelCase__					  =      torch.hub.load_state_dict_from_url(a__ ,      map_location="""cpu"""							)["""target_encoder"""]

							UpperCamelCase__					  =      ViTImageProcessor(size=config.image_size							)

							remove_projection_head(a__							)
							UpperCamelCase__					  =      create_rename_keys(a__ ,      base_model=a__							)

							for src, dest in rename_keys:
														rename_key(a__ ,      a__ ,      a__							)
							read_in_q_k_v(a__ ,      a__ ,      base_model=a__							)

							model.load_state_dict(a__							)
							model.eval()

							UpperCamelCase__					  =      """http://images.cocodataset.org/val2017/000000039769.jpg"""

							UpperCamelCase__					  =      Image.open(requests.get(a__ ,      stream=a__							).raw							)
							UpperCamelCase__					  =      ViTImageProcessor(
							    size=config.image_size ,      image_mean=a__ ,      image_std=a__							)
							UpperCamelCase__					  =      image_processor(images=a__ ,      return_tensors="""pt"""							)

							# forward pass
							torch.manual_seed(2							)
							UpperCamelCase__					  =      model(**a__							)
							UpperCamelCase__					  =      outputs.last_hidden_state

							# The following Colab Notebook was used to generate these outputs:
							# https://colab.research.google.com/gist/sayakpaul/3672419a04f5997827503fd84079bdd1/scratchpad.ipynb
							if "s16" in checkpoint_url:
														UpperCamelCase__					  =      torch.tensor([[-1.0915, -1.4876, -1.1809]]							)
							elif "b16" in checkpoint_url:
														UpperCamelCase__					  =      torch.tensor([[14.2889, -18.9045, 11.7281]]							)
							elif "l16" in checkpoint_url:
														UpperCamelCase__					  =      torch.tensor([[41.5028, -22.8681, 45.6475]]							)
							elif "b4" in checkpoint_url:
														UpperCamelCase__					  =      torch.tensor([[-4.3868, 5.2932, -0.4137]]							)
							else:
														UpperCamelCase__					  =      torch.tensor([[-0.1792, -0.6465, 2.4263]]							)

							# verify logits
							assert torch.allclose(last_hidden_state[:, 0, :3] ,      a__ ,      atol=1e-4							)

							print(f"""Saving model to {pytorch_dump_folder_path}"""							)
							model.save_pretrained(a__							)

							print(f"""Saving image processor to {pytorch_dump_folder_path}"""							)
							image_processor.save_pretrained(a__							)


if __name__ == "__main__":
					UpperCamelCase__           =			argparse.ArgumentParser()
					# Required parameters
					parser.add_argument(
					    "--checkpoint_url",
					    default="https://dl.fbaipublicfiles.com/msn/vits16_800ep.pth.tar",
					    type=str,
					    help="URL of the checkpoint you'd like to convert.",
					)
					parser.add_argument(
					    "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory."
					)

					UpperCamelCase__           =			parser.parse_args()
					convert_vit_msn_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)




