

import gc
import random
import unittest

import numpy as np
import torch
from transformers import XLMRobertaTokenizer

from diffusers import (
    AltDiffusionImgaImgPipeline,
    AutoencoderKL,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.image_processor import VaeImageProcessor
from diffusers.pipelines.alt_diffusion.modeling_roberta_series import (
    RobertaSeriesConfig,
    RobertaSeriesModelWithTransformation,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()




class   UpperCamelCase			(  unittest.TestCase ):

    def UpperCamelCase      (      self			:   Optional[int]     ):

     """simple docstring"""






     super().tearDown()
     gc.collect()
     torch.cuda.empty_cache()

    @property
    def UpperCamelCase      (      self			:   Union[str, Any]     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      1
     SCREAMING_SNAKE_CASE		    =      3
     SCREAMING_SNAKE_CASE		    =      (3_2, 3_2)

     SCREAMING_SNAKE_CASE		    =      floats_tensor((batch_size, num_channels) + sizes				,     rng=random.Random(0     )     ).to(snake_case__     )
     return image

    @property
    def UpperCamelCase      (      self			:   List[Any]     ):

     """simple docstring"""






     torch.manual_seed(0     )
     SCREAMING_SNAKE_CASE		    =      UNetaDConditionModel(
         block_out_channels=(3_2, 6_4)				,     layers_per_block=2				,     sample_size=3_2				,     in_channels=4				,     out_channels=4				,     down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')				,     up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D')				,     cross_attention_dim=3_2				,     )
     return model

    @property
    def UpperCamelCase      (      self			:   str     ):

     """simple docstring"""






     torch.manual_seed(0     )
     SCREAMING_SNAKE_CASE		    =      AutoencoderKL(
         block_out_channels=[3_2, 6_4]				,     in_channels=3				,     out_channels=3				,     down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D']				,     up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D']				,     latent_channels=4				,     )
     return model

    @property
    def UpperCamelCase      (      self			:   List[Any]     ):

     """simple docstring"""






     torch.manual_seed(0     )
     SCREAMING_SNAKE_CASE		    =      RobertaSeriesConfig(
         hidden_size=3_2				,     project_dim=3_2				,     intermediate_size=3_7				,     layer_norm_eps=1E-05				,     num_attention_heads=4				,     num_hidden_layers=5				,     pad_token_id=1				,     vocab_size=5_0_0_6				,     )
     return RobertaSeriesModelWithTransformation(snake_case__     )

    @property
    def UpperCamelCase      (      self			:   Dict     ):

     """simple docstring"""






     def extract(*snake_case__			:   List[Any]				,     **snake_case__			:   Union[str, Any]     ):




      class   UpperCamelCase			:

          def __init__(      self			:   str     ):

           """simple docstring"""






           SCREAMING_SNAKE_CASE		    =      torch.ones([0]     )




          def UpperCamelCase      (      self			:   Any				,     snake_case__			:   List[str]     ):

           """simple docstring"""






           self.pixel_values.to(snake_case__     )
           return self


      return Out()

     return extract

    def UpperCamelCase      (      self			:   Tuple     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      'cpu'  # ensure determinism for the device-dependent torch.Generator
     SCREAMING_SNAKE_CASE		    =      self.dummy_cond_unet
     SCREAMING_SNAKE_CASE		    =      PNDMScheduler(skip_prk_steps=snake_case__     )
     SCREAMING_SNAKE_CASE		    =      self.dummy_vae
     SCREAMING_SNAKE_CASE		    =      self.dummy_text_encoder
     SCREAMING_SNAKE_CASE		    =      XLMRobertaTokenizer.from_pretrained('hf-internal-testing/tiny-xlm-roberta'     )
     SCREAMING_SNAKE_CASE		    =      7_7

     SCREAMING_SNAKE_CASE		    =      self.dummy_image.to(snake_case__     )
     SCREAMING_SNAKE_CASE		    =      init_image / 2 + 0.5

     # make sure here that pndm scheduler skips prk
     SCREAMING_SNAKE_CASE		    =      AltDiffusionImgaImgPipeline(
         unet=snake_case__				,     scheduler=snake_case__				,     vae=snake_case__				,     text_encoder=snake_case__				,     tokenizer=snake_case__				,     safety_checker=snake_case__				,     feature_extractor=self.dummy_extractor				,     )
     SCREAMING_SNAKE_CASE		    =      VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor				,     do_normalize=snake_case__     )
     SCREAMING_SNAKE_CASE		    =      alt_pipe.to(snake_case__     )
     alt_pipe.set_progress_bar_config(disable=snake_case__     )

     SCREAMING_SNAKE_CASE		    =      'A painting of a squirrel eating a burger'
     SCREAMING_SNAKE_CASE		    =      torch.Generator(device=snake_case__     ).manual_seed(0     )
     SCREAMING_SNAKE_CASE		    =      alt_pipe(
         [prompt]				,     generator=snake_case__				,     guidance_scale=6.0				,     num_inference_steps=2				,     output_type='np'				,     image=snake_case__				,     )

     SCREAMING_SNAKE_CASE		    =      output.images

     SCREAMING_SNAKE_CASE		    =      torch.Generator(device=snake_case__     ).manual_seed(0     )
     SCREAMING_SNAKE_CASE		    =      alt_pipe(
         [prompt]				,     generator=snake_case__				,     guidance_scale=6.0				,     num_inference_steps=2				,     output_type='np'				,     image=snake_case__				,     return_dict=snake_case__				,     )[0]

     SCREAMING_SNAKE_CASE		    =      image[0, -3:, -3:, -1]
     SCREAMING_SNAKE_CASE		    =      image_from_tuple[0, -3:, -3:, -1]

     assert image.shape == (1, 3_2, 3_2, 3)
     SCREAMING_SNAKE_CASE		    =      np.array([0.4_427, 0.3_731, 0.4_249, 0.4_941, 0.4_546, 0.4_148, 0.4_193, 0.4_666, 0.4_499]     )

     assert np.abs(image_slice.flatten() - expected_slice     ).max() < 5E-3
     assert np.abs(image_from_tuple_slice.flatten() - expected_slice     ).max() < 5E-3

    @unittest.skipIf(torch_device != 'cuda'				,     'This test requires a GPU'     )
    def UpperCamelCase      (      self			:   str     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      self.dummy_cond_unet
     SCREAMING_SNAKE_CASE		    =      PNDMScheduler(skip_prk_steps=snake_case__     )
     SCREAMING_SNAKE_CASE		    =      self.dummy_vae
     SCREAMING_SNAKE_CASE		    =      self.dummy_text_encoder
     SCREAMING_SNAKE_CASE		    =      XLMRobertaTokenizer.from_pretrained('hf-internal-testing/tiny-xlm-roberta'     )
     SCREAMING_SNAKE_CASE		    =      7_7

     SCREAMING_SNAKE_CASE		    =      self.dummy_image.to(snake_case__     )

     # put models in fp16
     SCREAMING_SNAKE_CASE		    =      unet.half()
     SCREAMING_SNAKE_CASE		    =      vae.half()
     SCREAMING_SNAKE_CASE		    =      bert.half()

     # make sure here that pndm scheduler skips prk
     SCREAMING_SNAKE_CASE		    =      AltDiffusionImgaImgPipeline(
         unet=snake_case__				,     scheduler=snake_case__				,     vae=snake_case__				,     text_encoder=snake_case__				,     tokenizer=snake_case__				,     safety_checker=snake_case__				,     feature_extractor=self.dummy_extractor				,     )
     SCREAMING_SNAKE_CASE		    =      VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor				,     do_normalize=snake_case__     )
     SCREAMING_SNAKE_CASE		    =      alt_pipe.to(snake_case__     )
     alt_pipe.set_progress_bar_config(disable=snake_case__     )

     SCREAMING_SNAKE_CASE		    =      'A painting of a squirrel eating a burger'
     SCREAMING_SNAKE_CASE		    =      torch.manual_seed(0     )
     SCREAMING_SNAKE_CASE		    =      alt_pipe(
         [prompt]				,     generator=snake_case__				,     num_inference_steps=2				,     output_type='np'				,     image=snake_case__				,     ).images

     assert image.shape == (1, 3_2, 3_2, 3)




    @unittest.skipIf(torch_device != 'cuda'				,     'This test requires a GPU'     )
    def UpperCamelCase      (      self			:   Tuple     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      load_image(
         'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
         '/img2img/sketch-mountains-input.jpg'     )
     # resize to resolution that is divisible by 8 but not 16 or 32
     SCREAMING_SNAKE_CASE		    =      init_image.resize((7_6_0, 5_0_4)     )

     SCREAMING_SNAKE_CASE		    =      'BAAI/AltDiffusion'
     SCREAMING_SNAKE_CASE		    =      AltDiffusionImgaImgPipeline.from_pretrained(
         snake_case__				,     safety_checker=snake_case__				,     )
     pipe.to(snake_case__     )
     pipe.set_progress_bar_config(disable=snake_case__     )
     pipe.enable_attention_slicing()

     SCREAMING_SNAKE_CASE		    =      'A fantasy landscape, trending on artstation'

     SCREAMING_SNAKE_CASE		    =      torch.manual_seed(0     )
     SCREAMING_SNAKE_CASE		    =      pipe(
         prompt=snake_case__				,     image=snake_case__				,     strength=0.75				,     guidance_scale=7.5				,     generator=snake_case__				,     output_type='np'				,     )
     SCREAMING_SNAKE_CASE		    =      output.images[0]

     SCREAMING_SNAKE_CASE		    =      image[2_5_5:2_5_8, 3_8_3:3_8_6, -1]

     assert image.shape == (5_0_4, 7_6_0, 3)
     SCREAMING_SNAKE_CASE		    =      np.array([0.9_358, 0.9_397, 0.9_599, 0.9_901, 1.0_000, 1.0_000, 0.9_882, 1.0_000, 1.0_000]     )

     assert np.abs(image_slice.flatten() - expected_slice     ).max() < 1E-2




@slow
@require_torch_gpu
class   UpperCamelCase			(  unittest.TestCase ):

    def UpperCamelCase      (      self			:   int     ):

     """simple docstring"""






     super().tearDown()
     gc.collect()
     torch.cuda.empty_cache()




    def UpperCamelCase      (      self			:   List[Any]     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      load_image(
         'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
         '/img2img/sketch-mountains-input.jpg'     )
     SCREAMING_SNAKE_CASE		    =      init_image.resize((7_6_8, 5_1_2)     )
     SCREAMING_SNAKE_CASE		    =      load_numpy(
         'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy'     )

     SCREAMING_SNAKE_CASE		    =      'BAAI/AltDiffusion'
     SCREAMING_SNAKE_CASE		    =      AltDiffusionImgaImgPipeline.from_pretrained(
         snake_case__				,     safety_checker=snake_case__				,     )
     pipe.to(snake_case__     )
     pipe.set_progress_bar_config(disable=snake_case__     )
     pipe.enable_attention_slicing()

     SCREAMING_SNAKE_CASE		    =      'A fantasy landscape, trending on artstation'

     SCREAMING_SNAKE_CASE		    =      torch.manual_seed(0     )
     SCREAMING_SNAKE_CASE		    =      pipe(
         prompt=snake_case__				,     image=snake_case__				,     strength=0.75				,     guidance_scale=7.5				,     generator=snake_case__				,     output_type='np'				,     )
     SCREAMING_SNAKE_CASE		    =      output.images[0]

     assert image.shape == (5_1_2, 7_6_8, 3)
     # img2img is flaky across GPUs even in fp32, so using MAE here
     assert np.abs(expected_image - image     ).max() < 1E-2




import argparse

from transformers import BigBirdConfig, BigBirdForPreTraining, BigBirdForQuestionAnswering, load_tf_weights_in_big_bird
from transformers.utils import logging


logging.set_verbosity_info()


def 							__lowerCAmelCase     (							_UpperCamelCase		:	str		,				_UpperCamelCase		:	Union[str, Any]		,				_UpperCamelCase		:	Tuple		,				_UpperCamelCase		:	Tuple						)		->				Dict:
 '''simple docstring'''


 SCREAMING_SNAKE_CASE		    =      BigBirdConfig.from_json_file(_UpperCamelCase						)
 print(f"""Building PyTorch model from configuration: {config}"""						)

 if is_trivia_qa:
  SCREAMING_SNAKE_CASE		    =      BigBirdForQuestionAnswering(_UpperCamelCase						)
 else:
  SCREAMING_SNAKE_CASE		    =      BigBirdForPreTraining(_UpperCamelCase						)

 # Load weights from tf checkpoint
 load_tf_weights_in_big_bird(_UpperCamelCase		,				_UpperCamelCase		,				is_trivia_qa=_UpperCamelCase						)

 # Save pytorch-model
 print(f"""Save PyTorch model to {pytorch_dump_path}"""						)
 model.save_pretrained(_UpperCamelCase						)


if __name__ == "__main__":
      a_     :    int     		=   argparse.ArgumentParser()
      # Required parameters
      parser.add_argument(
          "--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path."
      )
      parser.add_argument(
          "--big_bird_config_file",
          default=None,
          type=str,
          required=True,
          help=(
              "The config json file corresponding to the pre-trained BERT model. \n"
              "This specifies the model architecture."
          ),
      )
      parser.add_argument(
          "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
      )
      parser.add_argument(
          "--is_trivia_qa", action="store_true", help="Whether to convert a model with a trivia_qa head."
      )
      a_     :    Any     		=   parser.parse_args()
      convert_tf_checkpoint_to_pytorch(
          args.tf_checkpoint_path, args.big_bird_config_file, args.pytorch_dump_path, args.is_trivia_qa
      )

