




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

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

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

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

  lowercase    :Tuple      	=						json.load(open(hf_hub_download(lowerCamelCase,			lowerCamelCase,			repo_type="dataset"   ),			"r"   )   )
  lowercase    :Union[str, Any]      	=						{int(lowerCamelCase   ): v for k, v in idalabel.items()}
  lowercase    :Optional[int]      	=						{v: k for k, v in idalabel.items()}

  lowercase    :str      	=						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       UpperCAmelCase__  (     lowerCamelCase   ):
  if "patch_embed.proj" in name:
    lowercase    :Optional[int]      	=						name.replace("patch_embed.proj",			"embeddings.patch_embeddings.projection"   )
  if "patch_embed.norm" in name:
    lowercase    :List[Any]      	=						name.replace("patch_embed.norm",			"embeddings.norm"   )
  if "layers" in name:
    lowercase    :Tuple      	=						"encoder." + name
  if "encoder.layers" in name:
    lowercase    :Union[str, Any]      	=						name.replace("encoder.layers",			"encoder.stages"   )
  if "downsample.proj" in name:
    lowercase    :List[str]      	=						name.replace("downsample.proj",			"downsample.projection"   )
  if "blocks" in name:
    lowercase    :int      	=						name.replace("blocks",			"layers"   )
  if "modulation.f.weight" in name or "modulation.f.bias" in name:
    lowercase    :Tuple      	=						name.replace("modulation.f",			"modulation.projection_in"   )
  if "modulation.h.weight" in name or "modulation.h.bias" in name:
    lowercase    :Tuple      	=						name.replace("modulation.h",			"modulation.projection_context"   )
  if "modulation.proj.weight" in name or "modulation.proj.bias" in name:
    lowercase    :List[str]      	=						name.replace("modulation.proj",			"modulation.projection_out"   )

  if name == "norm.weight":
    lowercase    :Any      	=						"layernorm.weight"
  if name == "norm.bias":
    lowercase    :Tuple      	=						"layernorm.bias"

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

  return name



def       UpperCAmelCase__  (     lowerCamelCase,			lowerCamelCase,			lowerCamelCase=False   ):
  # fmt: off
  lowercase    :Optional[int]      	=						{
      "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

  lowercase    :Union[str, Any]      	=						model_name_to_url[model_name]
  print("Checkpoint URL: ",			lowerCamelCase   )
  lowercase    :Optional[int]      	=						torch.hub.load_state_dict_from_url(lowerCamelCase,			map_location="cpu"   )["model"]

  # rename keys
  for key in state_dict.copy().keys():
    lowercase    :Optional[int]      	=						state_dict.pop(lowerCamelCase   )
    lowercase    :Union[str, Any]      	=						val

  lowercase    :str      	=						get_focalnet_config(lowerCamelCase   )
  lowercase    :List[Any]      	=						FocalNetForImageClassification(lowerCamelCase   )
  model.eval()

  # load state dict
  model.load_state_dict(lowerCamelCase   )

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

  lowercase    :Dict      	=						BitImageProcessor(
      do_resize=lowerCamelCase,			size={"shortest_edge": 256},			resample=PILImageResampling.BILINEAR,			do_center_crop=lowerCamelCase,			crop_size=224,			do_normalize=lowerCamelCase,			image_mean=lowerCamelCase,			image_std=lowerCamelCase,			)
  lowercase    :Optional[Any]      	=						Image.open(requests.get(lowerCamelCase,			stream=lowerCamelCase   ).raw   )
  lowercase    :Tuple      	=						processor(images=lowerCamelCase,			return_tensors="pt"   )

  lowercase    :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]   ),
      ]   )

  lowercase    :Dict      	=						image_transforms(lowerCamelCase   ).unsqueeze(0   )

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

  lowercase    :Dict      	=						model(**lowerCamelCase   )

  lowercase    :Optional[int]      	=						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":
    lowercase    :Optional[int]      	=						torch.tensor([0.2_166, -0.4_368, 0.2_191]   )
  elif model_name == "focalnet-tiny-lrf":
    lowercase    :Optional[Any]      	=						torch.tensor([1.1_669, 0.0_125, -0.1_695]   )
  elif model_name == "focalnet-small":
    lowercase    :List[str]      	=						torch.tensor([0.4_917, -0.0_430, 0.1_341]   )
  elif model_name == "focalnet-small-lrf":
    lowercase    :int      	=						torch.tensor([-0.2_588, -0.5_342, -0.2_331]   )
  elif model_name == "focalnet-base":
    lowercase    :int      	=						torch.tensor([-0.1_655, -0.4_090, -0.1_730]   )
  elif model_name == "focalnet-base-lrf":
    lowercase    :List[Any]      	=						torch.tensor([0.5_306, -0.0_483, -0.3_928]   )
  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__":
     _UpperCAmelCase	:						str			=     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.",
     )

     _UpperCAmelCase	:						List[Any]			=     parser.parse_args()
     convert_focalnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)









def       UpperCAmelCase__  (     lowerCamelCase,			lowerCamelCase = False   ):
  if n == 2:
    return True
  if not n % 2 or n < 2:
    return False
  if n > 5 and n % 10 not in (1, 3, 7, 9):  # can quickly check last digit
    return False
  if n > 3317044064679887385961981 and not allow_probable:
    raise ValueError(
        "Warning: upper bound of deterministic test is exceeded. "
        "Pass allow_probable=True to allow probabilistic test. "
        "A return value of True indicates a probable prime."   )
  # array bounds provided by analysis
  lowercase    :Optional[Any]      	=						[
      2047,
      1373653,
      25326001,
      3215031751,
      2152302898747,
      3474749660383,
      341550071728321,
      1,
      3825123056546413051,
      1,
      1,
      318665857834031151167461,
      3317044064679887385961981,
  ]

  lowercase    :List[Any]      	=						[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41]
  for idx, _p in enumerate(lowerCamelCase,			1   ):
    if n < _p:
      # then we have our last prime to check
      lowercase    :Tuple      	=						primes[:idx]
      break
  lowercase	,    lowercase    :str      	=						n - 1, 0
  # break up n -1 into a power of 2 (s) and
  # remaining odd component
  # essentially, solve for d * 2 ** s == n - 1
  while d % 2 == 0:
    d //= 2
    s += 1
  for prime in plist:
    lowercase    :Tuple      	=						False
    for r in range(lowerCamelCase   ):
      lowercase    :Any      	=						pow(lowerCamelCase,			d * 2**r,			lowerCamelCase   )
      # see article for analysis explanation for m
      if (r == 0 and m == 1) or ((m + 1) % n == 0):
        lowercase    :Any      	=						True
        # this loop will not determine compositeness
        break
    if pr:
      continue
    # if pr is False, then the above loop never evaluated to true,
    # and the n MUST be composite
    return False
  return True



def       UpperCAmelCase__  (     ):
  assert not miller_rabin(561   )
  assert miller_rabin(563   )
  # 2047

  assert not miller_rabin(838201   )
  assert miller_rabin(838207   )
  # 1_373_653

  assert not miller_rabin(17316001   )
  assert miller_rabin(17316017   )
  # 25_326_001

  assert not miller_rabin(3078386641   )
  assert miller_rabin(3078386653   )
  # 3_215_031_751

  assert not miller_rabin(1713045574801   )
  assert miller_rabin(1713045574819   )
  # 2_152_302_898_747

  assert not miller_rabin(2779799728307   )
  assert miller_rabin(2779799728327   )
  # 3_474_749_660_383

  assert not miller_rabin(113850023909441   )
  assert miller_rabin(113850023909527   )
  # 341_550_071_728_321

  assert not miller_rabin(1275041018848804351   )
  assert miller_rabin(1275041018848804391   )
  # 3_825_123_056_546_413_051

  assert not miller_rabin(79666464458507787791867   )
  assert miller_rabin(79666464458507787791951   )
  # 318_665_857_834_031_151_167_461

  assert not miller_rabin(552840677446647897660333   )
  assert miller_rabin(552840677446647897660359   )
  # 3_317_044_064_679_887_385_961_981
  # upper limit for probabilistic test


if __name__ == "__main__":
     test_miller_rabin()



