





'''simple docstring'''







import importlib.metadata
import warnings
from copy import deepcopy

from packaging import version

from ..utils import logging
from .import_utils import is_accelerate_available, is_bitsandbytes_available


if is_bitsandbytes_available():
					import bitsandbytes as bnb
					import torch
					import torch.nn as nn

					from ..pytorch_utils import ConvaD

if is_accelerate_available():
					from accelerate import init_empty_weights
					from accelerate.utils import find_tied_parameters

snake_case_   :				int		=     logging.get_logger(__name__)





def 				lowerCamelCase_					(     SCREAMING_SNAKE_CASE__					:	Optional[int],	SCREAMING_SNAKE_CASE__					:	Tuple,	SCREAMING_SNAKE_CASE__					:	Optional[int],	SCREAMING_SNAKE_CASE__					:	Optional[int]=None,	SCREAMING_SNAKE_CASE__					:	str=None      )       ->		Tuple:





						if "." in tensor_name:
												UpperCAmelCase_	:					Optional[int]     =     tensor_name.split('''.'''      )
												for split in splits[:-1]:
																		UpperCAmelCase_	:					Dict     =     getattr(_snake_case,	_snake_case      )
																		if new_module is None:
																								raise ValueError(F"""{module} has no attribute {split}."""      )
																		UpperCAmelCase_	:					Tuple     =     new_module
												UpperCAmelCase_	:					List[Any]     =     splits[-1]

						if tensor_name not in module._parameters and tensor_name not in module._buffers:
												raise ValueError(F"""{module} does not have a parameter or a buffer named {tensor_name}."""      )
						UpperCAmelCase_	:					str     =     tensor_name in module._buffers
						UpperCAmelCase_	:					Dict     =     getattr(_snake_case,	_snake_case      )

						if old_value.device == torch.device('''meta'''      ) and device not in ["meta", torch.device('''meta'''      )] and value is None:
												raise ValueError(F"""{tensor_name} is on the meta device, we need a `value` to put in on {device}."""      )

						UpperCAmelCase_	:					List[str]     =     False
						UpperCAmelCase_	:					Any     =     False
						if is_buffer or not is_bitsandbytes_available():
												UpperCAmelCase_	:					Dict     =     False
												UpperCAmelCase_	:					int     =     False
						else:
												UpperCAmelCase_	:					List[str]     =     hasattr(bnb.nn,	'''Params4bit'''      ) and isinstance(module._parameters[tensor_name],	bnb.nn.Paramsabit      )
												UpperCAmelCase_	:					Optional[Any]     =     isinstance(module._parameters[tensor_name],	bnb.nn.IntaParams      )

						if is_abit or is_abit:
												UpperCAmelCase_	:					int     =     module._parameters[tensor_name]
												if param.device.type != "cuda":
																		if value is None:
																								UpperCAmelCase_	:					Optional[int]     =     old_value.to(_snake_case      )
																		elif isinstance(_snake_case,	torch.Tensor      ):
																								UpperCAmelCase_	:					Any     =     value.to('''cpu'''      )
																								if value.dtype == torch.inta:
																														UpperCAmelCase_	:					List[Any]     =     version.parse(importlib.metadata.version('''bitsandbytes'''      )      ) > version.parse(
																														    '''0.37.2'''      )
																														if not is_abit_serializable:
																																				raise ValueError(
																																				    '''Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. '''
																																				    '''Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.'''      )
																		else:
																								UpperCAmelCase_	:					Any     =     torch.tensor(_snake_case,	device='''cpu'''      )

																		# Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization.
																		# Since weights are saved in the correct "orientation", we skip transposing when loading.
																		if issubclass(module.source_cls,	_snake_case      ) and fpaa_statistics is None:
																								UpperCAmelCase_	:					Optional[int]     =     new_value.T

																		UpperCAmelCase_	:					str     =     old_value.__dict__
																		if is_abit:
																								UpperCAmelCase_	:					Optional[Any]     =     bnb.nn.IntaParams(_snake_case,	requires_grad=_snake_case,	**_snake_case      ).to(_snake_case      )
																		elif is_abit:
																								UpperCAmelCase_	:					Dict     =     bnb.nn.Paramsabit(_snake_case,	requires_grad=_snake_case,	**_snake_case      ).to(_snake_case      )

																		UpperCAmelCase_	:					Union[str, Any]     =     new_value
																		if fpaa_statistics is not None:
																								setattr(module.weight,	'''SCB''',	fpaa_statistics.to(_snake_case      )      )

						else:
												if value is None:
																		UpperCAmelCase_	:					Optional[Any]     =     old_value.to(_snake_case      )
												elif isinstance(_snake_case,	torch.Tensor      ):
																		UpperCAmelCase_	:					Union[str, Any]     =     value.to(_snake_case      )
												else:
																		UpperCAmelCase_	:					List[Any]     =     torch.tensor(_snake_case,	device=_snake_case      )

												if is_buffer:
																		UpperCAmelCase_	:					Union[str, Any]     =     new_value
												else:
																		UpperCAmelCase_	:					List[Any]     =     nn.Parameter(_snake_case,	requires_grad=old_value.requires_grad      )
																		UpperCAmelCase_	:					List[str]     =     new_value





def 				lowerCamelCase_					(     SCREAMING_SNAKE_CASE__					:	List[Any],	SCREAMING_SNAKE_CASE__					:	Tuple=None,	SCREAMING_SNAKE_CASE__					:	List[str]=None,	SCREAMING_SNAKE_CASE__					:	Optional[int]=None,	SCREAMING_SNAKE_CASE__					:	List[str]=False      )       ->		List[Any]:





						for name, module in model.named_children():
												if current_key_name is None:
																		UpperCAmelCase_	:					Optional[int]     =     []
												current_key_name.append(_snake_case      )

												if (isinstance(_snake_case,	nn.Linear      ) or isinstance(_snake_case,	_snake_case      )) and name not in modules_to_not_convert:
																		# Check if the current key is not in the `modules_to_not_convert`
																		if not any(key in '''.'''.join(_snake_case      ) for key in modules_to_not_convert      ):
																								with init_empty_weights():
																														if isinstance(_snake_case,	_snake_case      ):
																																				UpperCAmelCase_	:					List[Any]     =     module.weight.shape
																														else:
																																				UpperCAmelCase_	:					List[Any]     =     module.in_features
																																				UpperCAmelCase_	:					Any     =     module.out_features

																														if quantization_config.quantization_method() == "llm_int8":
																																				UpperCAmelCase_	:					Any     =     bnb.nn.LinearabitLt(
																																				    _snake_case,	_snake_case,	module.bias is not None,	has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight,	threshold=quantization_config.llm_inta_threshold,	)
																																				UpperCAmelCase_	:					List[str]     =     True
																														else:
																																				if (
																																				    quantization_config.llm_inta_skip_modules is not None
																																				    and name in quantization_config.llm_inta_skip_modules
																																				):
																																										pass
																																				else:
																																										UpperCAmelCase_	:					Optional[int]     =     bnb.nn.Linearabit(
																																										    _snake_case,	_snake_case,	module.bias is not None,	quantization_config.bnb_abit_compute_dtype,	compress_statistics=quantization_config.bnb_abit_use_double_quant,	quant_type=quantization_config.bnb_abit_quant_type,	)
																																										UpperCAmelCase_	:					str     =     True
                    # Store the module class in case we need to transpose the weight later
																														UpperCAmelCase_	:					List[Any]     =     type(_snake_case      )
																														# Force requires grad to False to avoid unexpected errors
																														model._modules[name].requires_grad_(_snake_case      )
												if len(list(module.children()      )      ) > 0:
																		UpperCAmelCase_	:					Union[str, Any]     =     _replace_with_bnb_linear(
																		    _snake_case,	_snake_case,	_snake_case,	_snake_case,	has_been_replaced=_snake_case,	)
												# Remove the last key for recursion
												current_key_name.pop(-1      )
						return model, has_been_replaced





def 				lowerCamelCase_					(     SCREAMING_SNAKE_CASE__					:	Dict,	SCREAMING_SNAKE_CASE__					:	Union[str, Any]=None,	SCREAMING_SNAKE_CASE__					:	List[str]=None,	SCREAMING_SNAKE_CASE__					:	Any=None      )       ->		int:
						UpperCAmelCase_	:					str     =     ['''lm_head'''] if modules_to_not_convert is None else modules_to_not_convert
						UpperCAmelCase_	:					Optional[Any]     =     _replace_with_bnb_linear(
						    _snake_case,	_snake_case,	_snake_case,	_snake_case      )

						if not has_been_replaced:
												logger.warning(
												    '''You are loading your model in 8bit or 4bit but no linear modules were found in your model.'''
												    ''' Please double check your model architecture, or submit an issue on github if you think this is'''
												    ''' a bug.'''      )

						return model





def 				lowerCamelCase_					(     *SCREAMING_SNAKE_CASE__					:	Optional[Any],	**SCREAMING_SNAKE_CASE__					:	List[str]      )       ->		List[Any]:
						warnings.warn(
						    '''`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead''',	_snake_case,	)
						return replace_with_bnb_linear(*_snake_case,	**_snake_case      )





def 				lowerCamelCase_					(     *SCREAMING_SNAKE_CASE__					:	Any,	**SCREAMING_SNAKE_CASE__					:	Dict      )       ->		List[Any]:
						warnings.warn(
						    '''`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead''',	_snake_case,	)
						return set_module_quantized_tensor_to_device(*_snake_case,	**_snake_case      )





def 				lowerCamelCase_					(     SCREAMING_SNAKE_CASE__					:	Union[str, Any]      )       ->		Optional[int]:
						UpperCAmelCase_	:					List[str]     =     deepcopy(_snake_case      )  # this has 0 cost since it is done inside `init_empty_weights` context manager`
						tied_model.tie_weights()

						UpperCAmelCase_	:					Optional[int]     =     find_tied_parameters(_snake_case      )
						# For compatibility with Accelerate < 0.18
						if isinstance(_snake_case,	_snake_case      ):
												UpperCAmelCase_	:					str     =     sum(list(tied_params.values()      ),	[]      ) + list(tied_params.keys()      )
						else:
												UpperCAmelCase_	:					str     =     sum(_snake_case,	[]      )
						UpperCAmelCase_	:					Tuple     =     len(_snake_case      ) > 0

						# Check if it is a base model
						UpperCAmelCase_	:					List[str]     =     not hasattr(_snake_case,	model.base_model_prefix      )

						# Ignore this for base models (BertModel, GPT2Model, etc.)
						if (not has_tied_params) and is_base_model:
												return []

						# otherwise they have an attached head
						UpperCAmelCase_	:					List[str]     =     list(model.named_children()      )
						UpperCAmelCase_	:					Optional[int]     =     [list_modules[-1][0]]

						# add last module together with tied weights
						UpperCAmelCase_	:					Optional[int]     =     set(_snake_case      ) - set(_snake_case      )
						UpperCAmelCase_	:					List[str]     =     list(set(_snake_case      )      ) + list(_snake_case      )

						# remove ".weight" from the keys
						UpperCAmelCase_	:					int     =     ['''.weight''', '''.bias''']
						UpperCAmelCase_	:					str     =     []
						for name in list_untouched:
												for name_to_remove in names_to_remove:
																		if name_to_remove in name:
																								UpperCAmelCase_	:					Dict     =     name.replace(_snake_case,	''''''      )
												filtered_module_names.append(_snake_case      )

						return filtered_module_names









"""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 		lowercase							(     _snake_case						:      Any     )     ->Union[str, Any]:
	"""simple docstring"""





	__snake_case	:						Tuple						=				[2, 2, 6, 2] if '''tiny''' in model_name else [2, 2, 18, 2]
	__snake_case	:						Dict						=				True if '''large''' in model_name or '''huge''' in model_name else False
	__snake_case	:						Optional[int]						=				True if '''large''' in model_name or '''huge''' in model_name else False
	__snake_case	:						Optional[int]						=				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:
			__snake_case	:						Tuple						=				[3, 3, 3, 3]
			__snake_case	:						Dict						=				[5, 5, 5, 5]
		elif "fl4" in model_name:
			__snake_case	:						Any						=				[4, 4, 4, 4]
			__snake_case	:						List[str]						=				[3, 3, 3, 3]

	if "tiny" in model_name or "small" in model_name or "base" in model_name:
		__snake_case	:						Optional[int]						=				[3, 3, 3, 3]
		if "lrf" in model_name:
			__snake_case	:						Any						=				[3, 3, 3, 3]
		else:
			__snake_case	:						int						=				[2, 2, 2, 2]

	if "tiny" in model_name:
		__snake_case	:						str						=				96
	elif "small" in model_name:
		__snake_case	:						Optional[int]						=				96
	elif "base" in model_name:
		__snake_case	:						Any						=				128
	elif "large" in model_name:
		__snake_case	:						Optional[Any]						=				192
	elif "xlarge" in model_name:
		__snake_case	:						List[Any]						=				256
	elif "huge" in model_name:
		__snake_case	:						Union[str, Any]						=				352

	# set label information
	__snake_case	:						Union[str, Any]						=				'''huggingface/label-files'''
	if "large" in model_name or "huge" in model_name:
		__snake_case	:						int						=				'''imagenet-22k-id2label.json'''
	else:
		__snake_case	:						Optional[Any]						=				'''imagenet-1k-id2label.json'''

	__snake_case	:						int						=				json.load(open(hf_hub_download(_snake_case     ,   _snake_case     ,   repo_type='''dataset'''     )     ,   '''r'''     )     )
	__snake_case	:						Dict						=				{int(_snake_case     ): v for k, v in idalabel.items()}
	__snake_case	:						Optional[int]						=				{v: k for k, v in idalabel.items()}

	__snake_case	:						Optional[Any]						=				FocalNetConfig(
	    embed_dim=_snake_case     ,   depths=_snake_case     ,   focal_levels=_snake_case     ,   focal_windows=_snake_case     ,   use_conv_embed=_snake_case     ,   idalabel=_snake_case     ,   labelaid=_snake_case     ,   use_post_layernorm=_snake_case     ,   use_layerscale=_snake_case     ,   )

	return config






def 		lowercase							(     _snake_case						:      Dict     )     ->List[Any]:
	"""simple docstring"""





	if "patch_embed.proj" in name:
		__snake_case	:						Tuple						=				name.replace('''patch_embed.proj'''     ,   '''embeddings.patch_embeddings.projection'''     )
	if "patch_embed.norm" in name:
		__snake_case	:						Tuple						=				name.replace('''patch_embed.norm'''     ,   '''embeddings.norm'''     )
	if "layers" in name:
		__snake_case	:						List[Any]						=				'''encoder.''' + name
	if "encoder.layers" in name:
		__snake_case	:						Optional[Any]						=				name.replace('''encoder.layers'''     ,   '''encoder.stages'''     )
	if "downsample.proj" in name:
		__snake_case	:						Any						=				name.replace('''downsample.proj'''     ,   '''downsample.projection'''     )
	if "blocks" in name:
		__snake_case	:						List[str]						=				name.replace('''blocks'''     ,   '''layers'''     )
	if "modulation.f.weight" in name or "modulation.f.bias" in name:
		__snake_case	:						Any						=				name.replace('''modulation.f'''     ,   '''modulation.projection_in'''     )
	if "modulation.h.weight" in name or "modulation.h.bias" in name:
		__snake_case	:						List[Any]						=				name.replace('''modulation.h'''     ,   '''modulation.projection_context'''     )
	if "modulation.proj.weight" in name or "modulation.proj.bias" in name:
		__snake_case	:						int						=				name.replace('''modulation.proj'''     ,   '''modulation.projection_out'''     )

	if name == "norm.weight":
		__snake_case	:						Optional[Any]						=				'''layernorm.weight'''
	if name == "norm.bias":
		__snake_case	:						List[str]						=				'''layernorm.bias'''

	if "head" in name:
		__snake_case	:						Union[str, Any]						=				name.replace('''head'''     ,   '''classifier'''     )
	else:
		__snake_case	:						int						=				'''focalnet.''' + name

	return name






def 		lowercase							(     _snake_case						:      Tuple     ,   _snake_case						:      Dict     ,   _snake_case						:      List[str]=False     )     ->Any:
	"""simple docstring"""





	__snake_case	:						List[Any]						=				{
	    '''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

	__snake_case	:						int						=				model_name_to_url[model_name]
	print('''Checkpoint URL: '''     ,   _snake_case     )
	__snake_case	:						int						=				torch.hub.load_state_dict_from_url(_snake_case     ,   map_location='''cpu'''     )['''model''']

	# rename keys
	for key in state_dict.copy().keys():
		__snake_case	:						str						=				state_dict.pop(_snake_case     )
		__snake_case	:						Tuple						=				val

	__snake_case	:						Any						=				get_focalnet_config(_snake_case     )
	__snake_case	:						List[Any]						=				FocalNetForImageClassification(_snake_case     )
	model.eval()

	# load state dict
	model.load_state_dict(_snake_case     )

	# verify conversion
	__snake_case	:						str						=				'''http://images.cocodataset.org/val2017/000000039769.jpg'''

	__snake_case	:						Any						=				BitImageProcessor(
	    do_resize=_snake_case     ,   size={'''shortest_edge''': 256}     ,   resample=PILImageResampling.BILINEAR     ,   do_center_crop=_snake_case     ,   crop_size=224     ,   do_normalize=_snake_case     ,   image_mean=_snake_case     ,   image_std=_snake_case     ,   )
	__snake_case	:						List[str]						=				Image.open(requests.get(_snake_case     ,   stream=_snake_case     ).raw     )
	__snake_case	:						int						=				processor(images=_snake_case     ,   return_tensors='''pt'''     )

	__snake_case	:						Optional[int]						=				transforms.Compose(
	    [
	        transforms.Resize(256     ),
	        transforms.CenterCrop(224     ),
	        transforms.ToTensor(),
	        transforms.Normalize(mean=[0.485, 0.456, 0.406]     ,   std=[0.229, 0.224, 0.225]     ),
	    ]     )

	__snake_case	:						Optional[Any]						=				image_transforms(_snake_case     ).unsqueeze(0     )

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

	__snake_case	:						Tuple						=				model(**_snake_case     )

	__snake_case	:						str						=				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":
		__snake_case	:						Any						=				torch.tensor([0.2166, -0.4368, 0.2191]     )
	elif model_name == "focalnet-tiny-lrf":
		__snake_case	:						int						=				torch.tensor([1.1669, 0.0125, -0.1695]     )
	elif model_name == "focalnet-small":
		__snake_case	:						Optional[int]						=				torch.tensor([0.4917, -0.0430, 0.1341]     )
	elif model_name == "focalnet-small-lrf":
		__snake_case	:						List[Any]						=				torch.tensor([-0.2588, -0.5342, -0.2331]     )
	elif model_name == "focalnet-base":
		__snake_case	:						Union[str, Any]						=				torch.tensor([-0.1655, -0.4090, -0.1730]     )
	elif model_name == "focalnet-base-lrf":
		__snake_case	:						List[str]						=				torch.tensor([0.5306, -0.0483, -0.3928]     )
	assert torch.allclose(outputs.logits[0, :3]     ,   _snake_case     ,   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(_snake_case     )
		processor.save_pretrained(_snake_case     )

	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__":
			SCREAMING_SNAKE_CASE :    Any									=				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.""",
			)

			SCREAMING_SNAKE_CASE :    str									=				parser.parse_args()
			convert_focalnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)





