



'''simple docstring'''



import argparse
import os

import jax as jnp
import numpy as onp
import torch
import torch.nn as nn
from music_spectrogram_diffusion import inference
from tax import checkpoints

from diffusers import DDPMScheduler, OnnxRuntimeModel, SpectrogramDiffusionPipeline
from diffusers.pipelines.spectrogram_diffusion import SpectrogramContEncoder, SpectrogramNotesEncoder, TaFilmDecoder


lowerCAmelCase	:		List[str]				=   'base_with_context'



def   __lowerCAmelCase	(							lowerCamelCase   :						Optional[int]				,		lowerCamelCase   :						Optional[Any]					):






	'''simple docstring'''




	__lowerCAmelCase												=  nn.Parameter(torch.FloatTensor(weights["token_embedder"]["embedding"]					)					)
	__lowerCAmelCase												=  nn.Parameter(
	    torch.FloatTensor(weights["Embed_0"]["embedding"]					)				,		requires_grad=_lowercase					)
	for lyr_num, lyr in enumerate(model.encoders					):
		__lowerCAmelCase												=  weights[f'''layers_{lyr_num}''']
		__lowerCAmelCase												=  nn.Parameter(
		    torch.FloatTensor(ly_weight["pre_attention_layer_norm"]["scale"]					)					)

		__lowerCAmelCase												=  ly_weight['''attention''']
		__lowerCAmelCase												=  nn.Parameter(torch.FloatTensor(attention_weights["query"]["kernel"].T					)					)
		__lowerCAmelCase												=  nn.Parameter(torch.FloatTensor(attention_weights["key"]["kernel"].T					)					)
		__lowerCAmelCase												=  nn.Parameter(torch.FloatTensor(attention_weights["value"]["kernel"].T					)					)
		__lowerCAmelCase												=  nn.Parameter(torch.FloatTensor(attention_weights["out"]["kernel"].T					)					)

		__lowerCAmelCase												=  nn.Parameter(torch.FloatTensor(ly_weight["pre_mlp_layer_norm"]["scale"]					)					)

		__lowerCAmelCase												=  nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wi_0"]["kernel"].T					)					)
		__lowerCAmelCase												=  nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wi_1"]["kernel"].T					)					)
		__lowerCAmelCase												=  nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wo"]["kernel"].T					)					)

	__lowerCAmelCase												=  nn.Parameter(torch.FloatTensor(weights["encoder_norm"]["scale"]					)					)
	return model



def   __lowerCAmelCase	(							lowerCamelCase   :						Tuple				,		lowerCamelCase   :						str					):






	'''simple docstring'''




	__lowerCAmelCase												=  nn.Parameter(torch.FloatTensor(weights["input_proj"]["kernel"].T					)					)

	__lowerCAmelCase												=  nn.Parameter(
	    torch.FloatTensor(weights["Embed_0"]["embedding"]					)				,		requires_grad=_lowercase					)

	for lyr_num, lyr in enumerate(model.encoders					):
		__lowerCAmelCase												=  weights[f'''layers_{lyr_num}''']
		__lowerCAmelCase												=  ly_weight['''attention''']

		__lowerCAmelCase												=  nn.Parameter(torch.FloatTensor(attention_weights["query"]["kernel"].T					)					)
		__lowerCAmelCase												=  nn.Parameter(torch.FloatTensor(attention_weights["key"]["kernel"].T					)					)
		__lowerCAmelCase												=  nn.Parameter(torch.FloatTensor(attention_weights["value"]["kernel"].T					)					)
		__lowerCAmelCase												=  nn.Parameter(torch.FloatTensor(attention_weights["out"]["kernel"].T					)					)
		__lowerCAmelCase												=  nn.Parameter(
		    torch.FloatTensor(ly_weight["pre_attention_layer_norm"]["scale"]					)					)

		__lowerCAmelCase												=  nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wi_0"]["kernel"].T					)					)
		__lowerCAmelCase												=  nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wi_1"]["kernel"].T					)					)
		__lowerCAmelCase												=  nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wo"]["kernel"].T					)					)
		__lowerCAmelCase												=  nn.Parameter(torch.FloatTensor(ly_weight["pre_mlp_layer_norm"]["scale"]					)					)

	__lowerCAmelCase												=  nn.Parameter(torch.FloatTensor(weights["encoder_norm"]["scale"]					)					)

	return model



def   __lowerCAmelCase	(							lowerCamelCase   :						List[str]				,		lowerCamelCase   :						int					):






	'''simple docstring'''




	__lowerCAmelCase												=  nn.Parameter(torch.FloatTensor(weights["time_emb_dense0"]["kernel"].T					)					)
	__lowerCAmelCase												=  nn.Parameter(torch.FloatTensor(weights["time_emb_dense1"]["kernel"].T					)					)

	__lowerCAmelCase												=  nn.Parameter(
	    torch.FloatTensor(weights["Embed_0"]["embedding"]					)				,		requires_grad=_lowercase					)

	__lowerCAmelCase												=  nn.Parameter(
	    torch.FloatTensor(weights["continuous_inputs_projection"]["kernel"].T					)					)

	for lyr_num, lyr in enumerate(model.decoders					):
		__lowerCAmelCase												=  weights[f'''layers_{lyr_num}''']
		__lowerCAmelCase												=  nn.Parameter(
		    torch.FloatTensor(ly_weight["pre_self_attention_layer_norm"]["scale"]					)					)

		__lowerCAmelCase												=  nn.Parameter(
		    torch.FloatTensor(ly_weight["FiLMLayer_0"]["DenseGeneral_0"]["kernel"].T					)					)

		__lowerCAmelCase												=  ly_weight['''self_attention''']
		__lowerCAmelCase												=  nn.Parameter(torch.FloatTensor(attention_weights["query"]["kernel"].T					)					)
		__lowerCAmelCase												=  nn.Parameter(torch.FloatTensor(attention_weights["key"]["kernel"].T					)					)
		__lowerCAmelCase												=  nn.Parameter(torch.FloatTensor(attention_weights["value"]["kernel"].T					)					)
		__lowerCAmelCase												=  nn.Parameter(torch.FloatTensor(attention_weights["out"]["kernel"].T					)					)

		__lowerCAmelCase												=  ly_weight['''MultiHeadDotProductAttention_0''']
		__lowerCAmelCase												=  nn.Parameter(torch.FloatTensor(attention_weights["query"]["kernel"].T					)					)
		__lowerCAmelCase												=  nn.Parameter(torch.FloatTensor(attention_weights["key"]["kernel"].T					)					)
		__lowerCAmelCase												=  nn.Parameter(torch.FloatTensor(attention_weights["value"]["kernel"].T					)					)
		__lowerCAmelCase												=  nn.Parameter(torch.FloatTensor(attention_weights["out"]["kernel"].T					)					)
		__lowerCAmelCase												=  nn.Parameter(
		    torch.FloatTensor(ly_weight["pre_cross_attention_layer_norm"]["scale"]					)					)

		__lowerCAmelCase												=  nn.Parameter(torch.FloatTensor(ly_weight["pre_mlp_layer_norm"]["scale"]					)					)
		__lowerCAmelCase												=  nn.Parameter(
		    torch.FloatTensor(ly_weight["FiLMLayer_1"]["DenseGeneral_0"]["kernel"].T					)					)
		__lowerCAmelCase												=  nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wi_0"]["kernel"].T					)					)
		__lowerCAmelCase												=  nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wi_1"]["kernel"].T					)					)
		__lowerCAmelCase												=  nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wo"]["kernel"].T					)					)

	__lowerCAmelCase												=  nn.Parameter(torch.FloatTensor(weights["decoder_norm"]["scale"]					)					)

	__lowerCAmelCase												=  nn.Parameter(torch.FloatTensor(weights["spec_out_dense"]["kernel"].T					)					)

	return model



def   __lowerCAmelCase	(							lowerCamelCase   :						Tuple					):






	'''simple docstring'''




	__lowerCAmelCase												=  checkpoints.load_tax_checkpoint(args.checkpoint_path					)
	__lowerCAmelCase												=  jnp.tree_util.tree_map(onp.array				,		_lowercase					)

	__lowerCAmelCase												=  [
	    '''from __gin__ import dynamic_registration''',
	    '''from music_spectrogram_diffusion.models.diffusion import diffusion_utils''',
	    '''diffusion_utils.ClassifierFreeGuidanceConfig.eval_condition_weight = 2.0''',
	    '''diffusion_utils.DiffusionConfig.classifier_free_guidance = @diffusion_utils.ClassifierFreeGuidanceConfig()''',
	]

	__lowerCAmelCase												=  os.path.join(args.checkpoint_path				,		".."				,		"config.gin"					)
	__lowerCAmelCase												=  inference.parse_training_gin_file(_lowercase				,		_lowercase					)
	__lowerCAmelCase												=  inference.InferenceModel(args.checkpoint_path				,		_lowercase					)

	__lowerCAmelCase												=  DDPMScheduler(beta_schedule="squaredcos_cap_v2"				,		variance_type="fixed_large"					)

	__lowerCAmelCase												=  SpectrogramNotesEncoder(
	    max_length=synth_model.sequence_length["inputs"]				,		vocab_size=synth_model.model.module.config.vocab_size				,		d_model=synth_model.model.module.config.emb_dim				,		dropout_rate=synth_model.model.module.config.dropout_rate				,		num_layers=synth_model.model.module.config.num_encoder_layers				,		num_heads=synth_model.model.module.config.num_heads				,		d_kv=synth_model.model.module.config.head_dim				,		d_ff=synth_model.model.module.config.mlp_dim				,		feed_forward_proj="gated-gelu"				,		)

	__lowerCAmelCase												=  SpectrogramContEncoder(
	    input_dims=synth_model.audio_codec.n_dims				,		targets_context_length=synth_model.sequence_length["targets_context"]				,		d_model=synth_model.model.module.config.emb_dim				,		dropout_rate=synth_model.model.module.config.dropout_rate				,		num_layers=synth_model.model.module.config.num_encoder_layers				,		num_heads=synth_model.model.module.config.num_heads				,		d_kv=synth_model.model.module.config.head_dim				,		d_ff=synth_model.model.module.config.mlp_dim				,		feed_forward_proj="gated-gelu"				,		)

	__lowerCAmelCase												=  TaFilmDecoder(
	    input_dims=synth_model.audio_codec.n_dims				,		targets_length=synth_model.sequence_length["targets_context"]				,		max_decoder_noise_time=synth_model.model.module.config.max_decoder_noise_time				,		d_model=synth_model.model.module.config.emb_dim				,		num_layers=synth_model.model.module.config.num_decoder_layers				,		num_heads=synth_model.model.module.config.num_heads				,		d_kv=synth_model.model.module.config.head_dim				,		d_ff=synth_model.model.module.config.mlp_dim				,		dropout_rate=synth_model.model.module.config.dropout_rate				,		)

	__lowerCAmelCase												=  load_notes_encoder(ta_checkpoint["target"]["token_encoder"]				,		_lowercase					)
	__lowerCAmelCase												=  load_continuous_encoder(ta_checkpoint["target"]["continuous_encoder"]				,		_lowercase					)
	__lowerCAmelCase												=  load_decoder(ta_checkpoint["target"]["decoder"]				,		_lowercase					)

	__lowerCAmelCase												=  OnnxRuntimeModel.from_pretrained("kashif/soundstream_mel_decoder"					)

	__lowerCAmelCase												=  SpectrogramDiffusionPipeline(
	    notes_encoder=_lowercase				,		continuous_encoder=_lowercase				,		decoder=_lowercase				,		scheduler=_lowercase				,		melgan=_lowercase				,		)
	if args.save:
		pipe.save_pretrained(args.output_path					)


if __name__ == "__main__":
	lowerCAmelCase	:		Dict				=   argparse.ArgumentParser()

	parser.add_argument('''--output_path''', default=None, type=str, required=True, help='''Path to the converted model.''')
	parser.add_argument(
	    '''--save''', default=True, type=bool, required=False, help='''Whether to save the converted model or not.'''
	)
	parser.add_argument(
	    '''--checkpoint_path''',
	    default=f'{MODEL}/checkpoint_500000',
	    type=str,
	    required=False,
	    help='''Path to the original jax model checkpoint.''',
	)
	lowerCAmelCase	:		List[str]				=   parser.parse_args()

	main(args)




'''simple docstring'''



import argparse
import json

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

from transformers import BitImageProcessor, FocalNetConfig, FocalNetForImageClassification
from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling



def   __lowerCAmelCase					(							lowerCamelCase   :						Any					):






	'''simple docstring'''




	__lowerCAmelCase												=  [2, 2, 6, 2] if "tiny" in model_name else [2, 2, 18, 2]
	__lowerCAmelCase												=  True if "large" in model_name or "huge" in model_name else False
	__lowerCAmelCase												=  True if "large" in model_name or "huge" in model_name else False
	__lowerCAmelCase												=  True if "large" in model_name or "huge" in model_name else False

	if "large" in model_name or "xlarge" in model_name or "huge" in model_name:
		if "fl3" in model_name:
			__lowerCAmelCase												=  [3, 3, 3, 3]
			__lowerCAmelCase												=  [5, 5, 5, 5]
		elif "fl4" in model_name:
			__lowerCAmelCase												=  [4, 4, 4, 4]
			__lowerCAmelCase												=  [3, 3, 3, 3]

	if "tiny" in model_name or "small" in model_name or "base" in model_name:
		__lowerCAmelCase												=  [3, 3, 3, 3]
		if "lrf" in model_name:
			__lowerCAmelCase												=  [3, 3, 3, 3]
		else:
			__lowerCAmelCase												=  [2, 2, 2, 2]

	if "tiny" in model_name:
		__lowerCAmelCase												=  96
	elif "small" in model_name:
		__lowerCAmelCase												=  96
	elif "base" in model_name:
		__lowerCAmelCase												=  1_28
	elif "large" in model_name:
		__lowerCAmelCase												=  1_92
	elif "xlarge" in model_name:
		__lowerCAmelCase												=  2_56
	elif "huge" in model_name:
		__lowerCAmelCase												=  3_52

	# set label information
	__lowerCAmelCase												=  "huggingface/label-files"
	if "large" in model_name or "huge" in model_name:
		__lowerCAmelCase												=  "imagenet-22k-id2label.json"
	else:
		__lowerCAmelCase												=  "imagenet-1k-id2label.json"

	__lowerCAmelCase												=  json.load(open(hf_hub_download(lowerCamelCase				,		lowerCamelCase				,		repo_type="dataset"					)				,		"r"					)					)
	__lowerCAmelCase												=  {int(lowerCamelCase					): v for k, v in idalabel.items()}
	__lowerCAmelCase												=  {v: k for k, v in idalabel.items()}

	__lowerCAmelCase												=  FocalNetConfig(
	    embed_dim=lowerCamelCase				,		depths=lowerCamelCase				,		focal_levels=lowerCamelCase				,		focal_windows=lowerCamelCase				,		use_conv_embed=lowerCamelCase				,		idalabel=lowerCamelCase				,		labelaid=lowerCamelCase				,		use_post_layernorm=lowerCamelCase				,		use_layerscale=lowerCamelCase				,		)

	return config



def   __lowerCAmelCase					(							lowerCamelCase   :						Union[str, Any]					):






	'''simple docstring'''




	if "patch_embed.proj" in name:
		__lowerCAmelCase												=  name.replace("patch_embed.proj"				,		"embeddings.patch_embeddings.projection"					)
	if "patch_embed.norm" in name:
		__lowerCAmelCase												=  name.replace("patch_embed.norm"				,		"embeddings.norm"					)
	if "layers" in name:
		__lowerCAmelCase												=  "encoder." + name
	if "encoder.layers" in name:
		__lowerCAmelCase												=  name.replace("encoder.layers"				,		"encoder.stages"					)
	if "downsample.proj" in name:
		__lowerCAmelCase												=  name.replace("downsample.proj"				,		"downsample.projection"					)
	if "blocks" in name:
		__lowerCAmelCase												=  name.replace("blocks"				,		"layers"					)
	if "modulation.f.weight" in name or "modulation.f.bias" in name:
		__lowerCAmelCase												=  name.replace("modulation.f"				,		"modulation.projection_in"					)
	if "modulation.h.weight" in name or "modulation.h.bias" in name:
		__lowerCAmelCase												=  name.replace("modulation.h"				,		"modulation.projection_context"					)
	if "modulation.proj.weight" in name or "modulation.proj.bias" in name:
		__lowerCAmelCase												=  name.replace("modulation.proj"				,		"modulation.projection_out"					)

	if name == "norm.weight":
		__lowerCAmelCase												=  "layernorm.weight"
	if name == "norm.bias":
		__lowerCAmelCase												=  "layernorm.bias"

	if "head" in name:
		__lowerCAmelCase												=  name.replace("head"				,		"classifier"					)
	else:
		__lowerCAmelCase												=  "focalnet." + name

	return name



def   __lowerCAmelCase					(							lowerCamelCase   :						int				,		lowerCamelCase   :						Any				,		lowerCamelCase   :						Union[str, Any]=False					):






	'''simple docstring'''




	__lowerCAmelCase												=  {
	    "focalnet-tiny": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_srf.pth",
	    "focalnet-tiny-lrf": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_lrf.pth",
	    "focalnet-small": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_srf.pth",
	    "focalnet-small-lrf": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_lrf.pth",
	    "focalnet-base": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_srf.pth",
	    "focalnet-base-lrf": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_lrf.pth",
	    "focalnet-large-lrf-fl3": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384.pth",
	    "focalnet-large-lrf-fl4": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384_fl4.pth",
	    "focalnet-xlarge-lrf-fl3": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384.pth",
	    "focalnet-xlarge-lrf-fl4": "https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384_fl4.pth",
	}
	# fmt: on

	__lowerCAmelCase												=  model_name_to_url[model_name]
	print("Checkpoint URL: "				,		lowerCamelCase					)
	__lowerCAmelCase												=  torch.hub.load_state_dict_from_url(lowerCamelCase				,		map_location="cpu"					)["model"]

	# rename keys
	for key in state_dict.copy().keys():
		__lowerCAmelCase												=  state_dict.pop(lowerCamelCase					)
		__lowerCAmelCase												=  val

	__lowerCAmelCase												=  get_focalnet_config(lowerCamelCase					)
	__lowerCAmelCase												=  FocalNetForImageClassification(lowerCamelCase					)
	model.eval()

	# load state dict
	model.load_state_dict(lowerCamelCase					)

	# verify conversion
	__lowerCAmelCase												=  "http://images.cocodataset.org/val2017/000000039769.jpg"

	__lowerCAmelCase												=  BitImageProcessor(
	    do_resize=lowerCamelCase				,		size={"shortest_edge": 2_56}				,		resample=PILImageResampling.BILINEAR				,		do_center_crop=lowerCamelCase				,		crop_size=2_24				,		do_normalize=lowerCamelCase				,		image_mean=lowerCamelCase				,		image_std=lowerCamelCase				,		)
	__lowerCAmelCase												=  Image.open(requests.get(lowerCamelCase				,		stream=lowerCamelCase					).raw					)
	__lowerCAmelCase												=  processor(images=lowerCamelCase				,		return_tensors="pt"					)

	__lowerCAmelCase												=  transforms.Compose(
	    [
	        transforms.Resize(2_56					),
	        transforms.CenterCrop(2_24					),
	        transforms.ToTensor(),
	        transforms.Normalize(mean=[0.4_8_5, 0.4_5_6, 0.4_0_6]				,		std=[0.2_2_9, 0.2_2_4, 0.2_2_5]					),
	    ]					)

	__lowerCAmelCase												=  image_transforms(lowerCamelCase					).unsqueeze(0					)

	# verify pixel_values
	assert torch.allclose(inputs.pixel_values				,		lowerCamelCase				,		atol=1e-4					)

	__lowerCAmelCase												=  model(**lowerCamelCase					)

	__lowerCAmelCase												=  outputs.logits.argmax(-1					).item()
	print("Predicted class:"				,		model.config.idalabel[predicted_class_idx]					)

	print("First values of logits:"				,		outputs.logits[0, :3]					)

	if model_name == "focalnet-tiny":
		__lowerCAmelCase												=  torch.tensor([0.2_1_6_6, -0.4_3_6_8, 0.2_1_9_1]					)
	elif model_name == "focalnet-tiny-lrf":
		__lowerCAmelCase												=  torch.tensor([1.1_6_6_9, 0.0_1_2_5, -0.1_6_9_5]					)
	elif model_name == "focalnet-small":
		__lowerCAmelCase												=  torch.tensor([0.4_9_1_7, -0.0_4_3_0, 0.1_3_4_1]					)
	elif model_name == "focalnet-small-lrf":
		__lowerCAmelCase												=  torch.tensor([-0.2_5_8_8, -0.5_3_4_2, -0.2_3_3_1]					)
	elif model_name == "focalnet-base":
		__lowerCAmelCase												=  torch.tensor([-0.1_6_5_5, -0.4_0_9_0, -0.1_7_3_0]					)
	elif model_name == "focalnet-base-lrf":
		__lowerCAmelCase												=  torch.tensor([0.5_3_0_6, -0.0_4_8_3, -0.3_9_2_8]					)
	assert torch.allclose(outputs.logits[0, :3]				,		lowerCamelCase				,		atol=1e-4					)
	print("Looks ok!"					)

	if pytorch_dump_folder_path is not None:
		print(f'''Saving model and processor of {model_name} to {pytorch_dump_folder_path}'''					)
		model.save_pretrained(lowerCamelCase					)
		processor.save_pretrained(lowerCamelCase					)

	if push_to_hub:
		print(f'''Pushing model and processor of {model_name} to the hub...'''					)
		model.push_to_hub(f'''{model_name}'''					)
		processor.push_to_hub(f'''{model_name}'''					)


if __name__ == "__main__":
	lowerCAmelCase	:		Tuple				=   argparse.ArgumentParser()
	# Required parameters
	parser.add_argument(
	    '''--model_name''',
	    default='''focalnet-tiny''',
	    type=str,
	    help='''Name of the FocalNet model you\'d like to convert.''',
	)
	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 to push the model and processor to the hub.''',
	)

	lowerCAmelCase	:		Optional[int]				=   parser.parse_args()
	convert_focalnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)