





'''simple docstring'''




import argparse

import torch
from datasets import load_dataset
from donut import DonutModel

from transformers import (
    DonutImageProcessor,
    DonutProcessor,
    DonutSwinConfig,
    DonutSwinModel,
    MBartConfig,
    MBartForCausalLM,
    VisionEncoderDecoderModel,
    XLMRobertaTokenizerFast,
)





def 	__lowerCamelCase			(      __lowerCAmelCase       :							Union[str, Any]		)		->  int:
   snake_case 						=   model.config

   snake_case 						=   DonutSwinConfig(
       image_size=original_config.input_size      ,    patch_size=4      ,    depths=original_config.encoder_layer      ,    num_heads=[4, 8, 16, 32]      ,    window_size=original_config.window_size      ,    embed_dim=1_28      ,    )
   snake_case 						=   MBartConfig(
       is_decoder=__lowerCAmelCase      ,    is_encoder_decoder=__lowerCAmelCase      ,    add_cross_attention=__lowerCAmelCase      ,    decoder_layers=original_config.decoder_layer      ,    max_position_embeddings=original_config.max_position_embeddings      ,    vocab_size=len(
           model.decoder.tokenizer		)      ,    scale_embedding=__lowerCAmelCase      ,    add_final_layer_norm=__lowerCAmelCase      ,    )

   return encoder_config, decoder_config





def 	__lowerCamelCase			(      __lowerCAmelCase       :							Any		)		->  List[Any]:
   if "encoder.model" in name:
      snake_case 						=   name.replace("""encoder.model"""      ,    """encoder"""		)
   if "decoder.model" in name:
      snake_case 						=   name.replace("""decoder.model"""      ,    """decoder"""		)
   if "patch_embed.proj" in name:
      snake_case 						=   name.replace("""patch_embed.proj"""      ,    """embeddings.patch_embeddings.projection"""		)
   if "patch_embed.norm" in name:
      snake_case 						=   name.replace("""patch_embed.norm"""      ,    """embeddings.norm"""		)
   if name.startswith("""encoder"""		):
      if "layers" in name:
         snake_case 						=   """encoder.""" + name
      if "attn.proj" in name:
         snake_case 						=   name.replace("""attn.proj"""      ,    """attention.output.dense"""		)
      if "attn" in name and "mask" not in name:
         snake_case 						=   name.replace("""attn"""      ,    """attention.self"""		)
      if "norm1" in name:
         snake_case 						=   name.replace("""norm1"""      ,    """layernorm_before"""		)
      if "norm2" in name:
         snake_case 						=   name.replace("""norm2"""      ,    """layernorm_after"""		)
      if "mlp.fc1" in name:
         snake_case 						=   name.replace("""mlp.fc1"""      ,    """intermediate.dense"""		)
      if "mlp.fc2" in name:
         snake_case 						=   name.replace("""mlp.fc2"""      ,    """output.dense"""		)

      if name == "encoder.norm.weight":
         snake_case 						=   """encoder.layernorm.weight"""
      if name == "encoder.norm.bias":
         snake_case 						=   """encoder.layernorm.bias"""

   return name





def 	__lowerCamelCase			(      __lowerCAmelCase       :							Optional[int]      ,    __lowerCAmelCase       :							Optional[Any]		)		->  List[Any]:
   for key in orig_state_dict.copy().keys():
      snake_case 						=   orig_state_dict.pop(__lowerCAmelCase		)

      if "qkv" in key:
         snake_case 						=   key.split("""."""		)
         snake_case 						=   int(key_split[3]		)
         snake_case 						=   int(key_split[5]		)
         snake_case 						=   model.encoder.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size

         if "weight" in key:
            snake_case 						=   val[:dim, :]
            snake_case 						=   val[dim : dim * 2, :]
            snake_case 						=   val[-dim:, :]
         else:
            snake_case 						=   val[:dim]
            snake_case 						=   val[dim : dim * 2]
            snake_case 						=   val[-dim:]
      elif "attn_mask" in key or key in ["encoder.model.norm.weight", "encoder.model.norm.bias"]:
         # HuggingFace implementation doesn't use attn_mask buffer
         # and model doesn't use final LayerNorms for the encoder
         pass
      else:
         snake_case 						=   val

   return orig_state_dict





def 	__lowerCamelCase			(      __lowerCAmelCase       :							List[str]      ,    __lowerCAmelCase       :							Tuple=None      ,    __lowerCAmelCase       :							Union[str, Any]=False		)		->  Tuple:
   # load original model
   snake_case 						=   DonutModel.from_pretrained(__lowerCAmelCase		).eval()

   # load HuggingFace model
   snake_case						,    snake_case 						=   get_configs(__lowerCAmelCase		)
   snake_case 						=   DonutSwinModel(__lowerCAmelCase		)
   snake_case 						=   MBartForCausalLM(__lowerCAmelCase		)
   snake_case 						=   VisionEncoderDecoderModel(encoder=__lowerCAmelCase      ,    decoder=__lowerCAmelCase		)
   model.eval()

   snake_case 						=   original_model.state_dict()
   snake_case 						=   convert_state_dict(__lowerCAmelCase      ,    __lowerCAmelCase		)
   model.load_state_dict(__lowerCAmelCase		)

   # verify results on scanned document
   snake_case 						=   load_dataset("""hf-internal-testing/example-documents"""		)
   snake_case 						=   dataset["""test"""][0]["""image"""].convert("""RGB"""		)

   snake_case 						=   XLMRobertaTokenizerFast.from_pretrained(__lowerCAmelCase      ,    from_slow=__lowerCAmelCase		)
   snake_case 						=   DonutImageProcessor(
       do_align_long_axis=original_model.config.align_long_axis      ,    size=original_model.config.input_size[::-1]		)
   snake_case 						=   DonutProcessor(__lowerCAmelCase      ,    __lowerCAmelCase		)
   snake_case 						=   processor(__lowerCAmelCase      ,    return_tensors="""pt"""		).pixel_values

   if model_name == "naver-clova-ix/donut-base-finetuned-docvqa":
      snake_case 						=   """<s_docvqa><s_question>{user_input}</s_question><s_answer>"""
      snake_case 						=   """When is the coffee break?"""
      snake_case 						=   task_prompt.replace("""{user_input}"""      ,    __lowerCAmelCase		)
   elif model_name == "naver-clova-ix/donut-base-finetuned-rvlcdip":
      snake_case 						=   """<s_rvlcdip>"""
   elif model_name in [
       "naver-clova-ix/donut-base-finetuned-cord-v1",
       "naver-clova-ix/donut-base-finetuned-cord-v1-2560",
   ]:
      snake_case 						=   """<s_cord>"""
   elif model_name == "naver-clova-ix/donut-base-finetuned-cord-v2":
      snake_case 						=   """s_cord-v2>"""
   elif model_name == "naver-clova-ix/donut-base-finetuned-zhtrainticket":
      snake_case 						=   """<s_zhtrainticket>"""
   elif model_name in ["naver-clova-ix/donut-proto", "naver-clova-ix/donut-base"]:
      # use a random prompt
      snake_case 						=   """hello world"""
   else:
      raise ValueError("""Model name not supported"""		)
   snake_case 						=   original_model.decoder.tokenizer(__lowerCAmelCase      ,    add_special_tokens=__lowerCAmelCase      ,    return_tensors="""pt"""		)[
       """input_ids"""
   ]

   snake_case 						=   original_model.encoder.model.patch_embed(__lowerCAmelCase		)
   snake_case						,    snake_case 						=   model.encoder.embeddings(__lowerCAmelCase		)
   assert torch.allclose(__lowerCAmelCase      ,    __lowerCAmelCase      ,    atol=1e-3		)

   # verify encoder hidden states
   snake_case 						=   original_model.encoder(__lowerCAmelCase		)
   snake_case 						=   model.encoder(__lowerCAmelCase		).last_hidden_state
   assert torch.allclose(__lowerCAmelCase      ,    __lowerCAmelCase      ,    atol=1e-2		)

   # verify decoder hidden states
   snake_case 						=   original_model(__lowerCAmelCase      ,    __lowerCAmelCase      ,    __lowerCAmelCase		).logits
   snake_case 						=   model(__lowerCAmelCase      ,    decoder_input_ids=__lowerCAmelCase		).logits
   assert torch.allclose(__lowerCAmelCase      ,    __lowerCAmelCase      ,    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(__lowerCAmelCase		)
      processor.save_pretrained(__lowerCAmelCase		)

   if push_to_hub:
      model.push_to_hub("""nielsr/""" + model_name.split("""/"""		)[-1]      ,    commit_message="""Update model"""		)
      processor.push_to_hub("""nielsr/""" + model_name.split("""/"""		)[-1]      ,    commit_message="""Update model"""		)


if __name__ == "__main__":
 _SCREAMING_SNAKE_CASE							     =			argparse.ArgumentParser()
 # Required parameters
 parser.add_argument(
     "--model_name",
     default="naver-clova-ix/donut-base-finetuned-docvqa",
     required=False,
     type=str,
     help="Name of the original model you'd like to convert.",
 )
 parser.add_argument(
     "--pytorch_dump_folder_path",
     default=None,
     required=False,
     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 and processor to the 🤗 hub.",
 )

 _SCREAMING_SNAKE_CASE							     =			parser.parse_args()
 convert_donut_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)








'''simple docstring'''




from . import (
    albert,
    align,
    altclip,
    audio_spectrogram_transformer,
    auto,
    autoformer,
    bark,
    bart,
    barthez,
    bartpho,
    beit,
    bert,
    bert_generation,
    bert_japanese,
    bertweet,
    big_bird,
    bigbird_pegasus,
    biogpt,
    bit,
    blenderbot,
    blenderbot_small,
    blip,
    blip_a,
    bloom,
    bridgetower,
    byta,
    camembert,
    canine,
    chinese_clip,
    clap,
    clip,
    clipseg,
    codegen,
    conditional_detr,
    convbert,
    convnext,
    convnextva,
    cpm,
    cpmant,
    ctrl,
    cvt,
    dataavec,
    deberta,
    deberta_va,
    decision_transformer,
    deformable_detr,
    deit,
    deprecated,
    deta,
    detr,
    dialogpt,
    dinat,
    distilbert,
    dit,
    donut,
    dpr,
    dpt,
    efficientformer,
    efficientnet,
    electra,
    encodec,
    encoder_decoder,
    ernie,
    ernie_m,
    esm,
    falcon,
    flaubert,
    flava,
    fnet,
    focalnet,
    fsmt,
    funnel,
    git,
    glpn,
    gpta,
    gpt_bigcode,
    gpt_neo,
    gpt_neox,
    gpt_neox_japanese,
    gpt_swa,
    gptj,
    gptsan_japanese,
    graphormer,
    groupvit,
    herbert,
    hubert,
    ibert,
    imagegpt,
    informer,
    instructblip,
    jukebox,
    layoutlm,
    layoutlmva,
    layoutlmva,
    layoutxlm,
    led,
    levit,
    lilt,
    llama,
    longformer,
    longta,
    luke,
    lxmert,
    mam_aaa,
    marian,
    markuplm,
    maskaformer,
    maskformer,
    mbart,
    mbartaa,
    mega,
    megatron_bert,
    megatron_gpta,
    mgp_str,
    mluke,
    mobilebert,
    mobilenet_va,
    mobilenet_va,
    mobilevit,
    mobilevitva,
    mpnet,
    mra,
    mta,
    musicgen,
    mvp,
    nat,
    nezha,
    nllb,
    nllb_moe,
    nystromformer,
    oneformer,
    open_llama,
    openai,
    opt,
    owlvit,
    pegasus,
    pegasus_x,
    perceiver,
    phobert,
    pixastruct,
    plbart,
    poolformer,
    prophetnet,
    qdqbert,
    rag,
    realm,
    reformer,
    regnet,
    rembert,
    resnet,
    roberta,
    roberta_prelayernorm,
    roc_bert,
    roformer,
    rwkv,
    sam,
    segformer,
    sew,
    sew_d,
    speech_encoder_decoder,
    speech_to_text,
    speech_to_text_a,
    speechta,
    splinter,
    squeezebert,
    swiftformer,
    swin,
    swinasr,
    swinva,
    switch_transformers,
    ta,
    table_transformer,
    tapas,
    time_series_transformer,
    timesformer,
    timm_backbone,
    transfo_xl,
    trocr,
    tvlt,
    umta,
    unispeech,
    unispeech_sat,
    upernet,
    videomae,
    vilt,
    vision_encoder_decoder,
    vision_text_dual_encoder,
    visual_bert,
    vit,
    vit_hybrid,
    vit_mae,
    vit_msn,
    vivit,
    wavaveca,
    wavaveca_conformer,
    wavaveca_phoneme,
    wavaveca_with_lm,
    wavlm,
    whisper,
    x_clip,
    xglm,
    xlm,
    xlm_prophetnet,
    xlm_roberta,
    xlm_roberta_xl,
    xlnet,
    xmod,
    yolos,
    yoso,
)

