





import os

import jsonlines
import numpy as np
from tqdm import tqdm


_UpperCamelCase				=       2048
_UpperCamelCase				=       4096
_UpperCamelCase				=       42
_UpperCamelCase				=       os.environ.pop('''PROCESS_TRAIN''', '''false''')
_UpperCamelCase				=       {'''null''': 0, '''short''': 1, '''long''': 2, '''yes''': 3, '''no''': 4}







def 					lowerCAmelCase__(		lowercase				:			List[Any] )       ->			Optional[Any]:







  def choose_first(lowercase				:			Any      ,   lowercase				:			Tuple=False ):
    assert isinstance(lowercase      ,   lowercase )
    if len(lowercase ) == 1:
      __snake_case      : str						=				answer[0]
      return {k: [answer[k]] for k in answer} if is_long_answer else answer
    for a in answer:
      if is_long_answer:
        __snake_case      : List[Any]						=				{k: [a[k]] for k in a}
      if len(a["start_token"] ) > 0:
        break
    return a

  __snake_case      : Union[str, Any]						=				{'''id''': example['''id''']}
  __snake_case      : Optional[Any]						=				example['''annotations''']
  __snake_case      : Tuple						=				annotation['''yes_no_answer''']
  if 0 in yes_no_answer or 1 in yes_no_answer:
    __snake_case      : List[Any]						=				['''yes'''] if 1 in yes_no_answer else ['''no''']
    __snake_case      : Tuple						=				[]
    __snake_case      : List[Any]						=				[]
    __snake_case      : Tuple						=				['''<cls>''']
  else:
    __snake_case      : Optional[Any]						=				['''short''']
    __snake_case      : Union[str, Any]						=				choose_first(annotation["short_answers"] )
    if len(out["start_token"] ) == 0:
      # answer will be long if short is not available
      __snake_case      : int						=				['''long''']
      __snake_case      : List[Any]						=				choose_first(annotation["long_answer"]      ,   is_long_answer=lowercase )
      __snake_case      : str						=				[]
    answer.update(lowercase )

  # disregard some samples
  if len(answer["start_token"] ) > 1 or answer["start_token"] == answer["end_token"]:
    __snake_case      : Any						=				True
  else:
    __snake_case      : str						=				False

  __snake_case      : Tuple						=				['''start_token''', '''end_token''', '''start_byte''', '''end_byte''', '''text''']
  if not all(isinstance(answer[k]      ,   lowercase ) for k in cols ):
    raise ValueError("Issue in ID"      ,   example["id"] )

  return answer







def 					lowerCAmelCase__(		lowercase				:			str      ,   lowercase				:			List[str]=False )       ->			str:
  __snake_case      : Tuple						=				_get_single_answer(lowercase )
  # bytes are of no use
  del answer["start_byte"]
  del answer["end_byte"]

  # handle yes_no answers explicitly
  if answer["category"][0] in ["yes", "no"]:  # category is list with one element
    __snake_case      : str						=				example['''document''']['''tokens''']
    __snake_case      : Any						=				[]
    for i in range(len(doc["token"] ) ):
      if not doc["is_html"][i]:
        context.append(doc["token"][i] )
    return {
        "context": " ".join(lowercase ),
        "answer": {
            "start_token": -100,  # ignore index in cross-entropy
            "end_token": -100,  # ignore index in cross-entropy
            "category": answer["category"],
            "span": answer["category"],  # extra
        },
    }

  # later, help in removing all no answers
  if answer["start_token"] == [-1]:
    return {
        "context": "None",
        "answer": {
            "start_token": -1,
            "end_token": -1,
            "category": "null",
            "span": "None",  # extra
        },
    }

  # handling normal samples

  __snake_case      : Optional[int]						=				['''start_token''', '''end_token''']
  answer.update({k: answer[k][0] if len(answer[k] ) > 0 else answer[k] for k in cols} )  # e.g. [10] == 10

  __snake_case      : Optional[Any]						=				example['''document''']['''tokens''']
  __snake_case      : List[Any]						=				answer['''start_token''']
  __snake_case      : Dict						=				answer['''end_token''']

  __snake_case      : Tuple						=				[]
  for i in range(len(doc["token"] ) ):
    if not doc["is_html"][i]:
      context.append(doc["token"][i] )
    else:
      if answer["start_token"] > i:
        start_token -= 1
      if answer["end_token"] > i:
        end_token -= 1
  __snake_case      : Optional[int]						=				''' '''.join(context[start_token:end_token] )

  # checking above code
  if assertion:
    __snake_case      : str						=				doc['''is_html'''][answer['''start_token'''] : answer['''end_token''']]
    __snake_case      : Union[str, Any]						=				doc['''token'''][answer['''start_token'''] : answer['''end_token''']]
    __snake_case      : Dict						=				''' '''.join([old[i] for i in range(len(lowercase ) ) if not is_html[i]] )
    if new != old:
      print("ID:"      ,   example["id"] )
      print("New:"      ,   lowercase      ,   end="\n" )
      print("Old:"      ,   lowercase      ,   end="\n\n" )

  return {
      "context": " ".join(lowercase ),
      "answer": {
          "start_token": start_token,
          "end_token": end_token - 1,  # this makes it inclusive
          "category": answer["category"],  # either long or short
          "span": new,  # extra
      },
  }







def 					lowerCAmelCase__(		lowercase				:			Optional[int]      ,   lowercase				:			Union[str, Any]      ,   lowercase				:			int=2048      ,   lowercase				:			int=4096      ,   lowercase				:			Tuple=True )       ->			Dict:
  __snake_case      : Optional[Any]						=				get_context_and_ans(lowercase      ,   assertion=lowercase )
  __snake_case      : List[str]						=				out['''answer''']

  # later, removing these samples
  if answer["start_token"] == -1:
    return {
        "example_id": example["id"],
        "input_ids": [[-1]],
        "labels": {
            "start_token": [-1],
            "end_token": [-1],
            "category": ["null"],
        },
    }

  __snake_case      : Optional[int]						=				tokenizer(example["question"]["text"]      ,   out["context"] ).input_ids
  __snake_case      : Optional[int]						=				input_ids.index(tokenizer.sep_token_id ) + 1

  # return yes/no
  if answer["category"][0] in ["yes", "no"]:  # category is list with one element
    __snake_case      : int						=				[]
    __snake_case      : Any						=				[]
    __snake_case      : Tuple						=				input_ids[:q_len]
    __snake_case      : Any						=				range(lowercase      ,   len(lowercase )      ,   max_length - doc_stride )
    for i in doc_start_indices:
      __snake_case      : Tuple						=				i + max_length - q_len
      __snake_case      : Any						=				input_ids[i:end_index]
      inputs.append(q_indices + slice )
      category.append(answer["category"][0] )
      if slice[-1] == tokenizer.sep_token_id:
        break

    return {
        "example_id": example["id"],
        "input_ids": inputs,
        "labels": {
            "start_token": [-100] * len(lowercase ),
            "end_token": [-100] * len(lowercase ),
            "category": category,
        },
    }

  __snake_case      : Tuple						=				out['''context'''].split()
  __snake_case      : Optional[Any]						=				splitted_context[answer['''end_token''']]
  __snake_case      : List[str]						=				len(
      tokenizer(
          " ".join(splitted_context[: answer["start_token"]] )      ,   add_special_tokens=lowercase      ,   ).input_ids )
  __snake_case      : Dict						=				len(
      tokenizer(" ".join(splitted_context[: answer["end_token"]] )      ,   add_special_tokens=lowercase ).input_ids )

  answer["start_token"] += q_len
  answer["end_token"] += q_len

  # fixing end token
  __snake_case      : Any						=				len(tokenizer(lowercase      ,   add_special_tokens=lowercase ).input_ids )
  if num_sub_tokens > 1:
    answer["end_token"] += num_sub_tokens - 1

  __snake_case      : Optional[Any]						=				input_ids[answer['''start_token'''] : answer['''end_token'''] + 1]  # right & left are inclusive
  __snake_case      : List[Any]						=				answer['''start_token''']
  __snake_case      : Optional[Any]						=				answer['''end_token''']

  if assertion:
    __snake_case      : Optional[int]						=				tokenizer.decode(lowercase )
    if answer["span"] != new:
      print("ISSUE IN TOKENIZATION" )
      print("OLD:"      ,   answer["span"] )
      print("NEW:"      ,   lowercase      ,   end="\n\n" )

  if len(lowercase ) <= max_length:
    return {
        "example_id": example["id"],
        "input_ids": [input_ids],
        "labels": {
            "start_token": [answer["start_token"]],
            "end_token": [answer["end_token"]],
            "category": answer["category"],
        },
    }

  __snake_case      : List[str]						=				input_ids[:q_len]
  __snake_case      : Optional[Any]						=				range(lowercase      ,   len(lowercase )      ,   max_length - doc_stride )

  __snake_case      : str						=				[]
  __snake_case      : List[str]						=				[]
  __snake_case      : str						=				[]
  __snake_case      : List[Any]						=				[]  # null, yes, no, long, short
  for i in doc_start_indices:
    __snake_case      : str						=				i + max_length - q_len
    __snake_case      : str						=				input_ids[i:end_index]
    inputs.append(q_indices + slice )
    assert len(inputs[-1] ) <= max_length, "Issue in truncating length"

    if start_token >= i and end_token <= end_index - 1:
      __snake_case      : Tuple						=				start_token - i + q_len
      __snake_case      : List[str]						=				end_token - i + q_len
      answers_category.append(answer["category"][0] )  # ["short"] -> "short"
    else:
      __snake_case      : Any						=				-100
      __snake_case      : Union[str, Any]						=				-100
      answers_category.append("null" )
    __snake_case      : str						=				inputs[-1][start_token : end_token + 1]

    answers_start_token.append(lowercase )
    answers_end_token.append(lowercase )
    if assertion:
      if new != old and new != [tokenizer.cls_token_id]:
        print("ISSUE in strided for ID:"      ,   example["id"] )
        print("New:"      ,   tokenizer.decode(lowercase ) )
        print("Old:"      ,   tokenizer.decode(lowercase )      ,   end="\n\n" )
    if slice[-1] == tokenizer.sep_token_id:
      break

  return {
      "example_id": example["id"],
      "input_ids": inputs,
      "labels": {
          "start_token": answers_start_token,
          "end_token": answers_end_token,
          "category": answers_category,
      },
  }







def 					lowerCAmelCase__(		lowercase				:			Dict      ,   lowercase				:			Dict      ,   lowercase				:			int=2048      ,   lowercase				:			Dict=4096      ,   lowercase				:			Any=False )       ->			Optional[Any]:
  __snake_case      : Any						=				get_strided_contexts_and_ans(
      lowercase      ,   lowercase      ,   doc_stride=lowercase      ,   max_length=lowercase      ,   assertion=lowercase      ,   )

  return example







def 					lowerCAmelCase__(		lowercase				:			Any      ,   lowercase				:			List[Any] )       ->			Tuple:







  with jsonlines.open(lowercase      ,   "a" ) as writer:
    for example in tqdm(lowercase      ,   total=len(lowercase )      ,   desc="Saving samples ... " ):
      __snake_case      : Union[str, Any]						=				example['''labels''']
      for ids, start, end, cat in zip(
          example["input_ids"]      ,   labels["start_token"]      ,   labels["end_token"]      ,   labels["category"]      ,   ):
        if start == -1 and end == -1:
          continue  # leave waste samples with no answer
        if cat == "null" and np.random.rand() < 0.6:
          continue  # removing 50 % samples
        writer.write(
            {
                "input_ids": ids,
                "start_token": start,
                "end_token": end,
                "category": CATEGORY_MAPPING[cat],
            } )


if __name__ == "__main__":
     from datasets import load_dataset

     from transformers import BigBirdTokenizer

     _UpperCamelCase				=       load_dataset('''natural_questions''')
     _UpperCamelCase				=       BigBirdTokenizer.from_pretrained('''google/bigbird-roberta-base''')

     _UpperCamelCase				=       data['''train''' if PROCESS_TRAIN == '''true''' else '''validation''']

     _UpperCamelCase				=       {
         '''tokenizer''': tokenizer,
         '''doc_stride''': DOC_STRIDE,
         '''max_length''': MAX_LENGTH,
         '''assertion''': False,
     }
     _UpperCamelCase				=       data.map(prepare_inputs, fn_kwargs=fn_kwargs)
     _UpperCamelCase				=       data.remove_columns(['''annotations''', '''document''', '''id''', '''question'''])
     print(data)

     np.random.seed(SEED)
     _UpperCamelCase				=       '''nq-training.jsonl''' if PROCESS_TRAIN == '''true''' else '''nq-validation.jsonl'''
     save_to_disk(data, file_name=cache_file_name)


import gc
import random
import unittest

import numpy as np
import torch
from transformers import (
    CLIPImageProcessor,
    CLIPTextConfig,
    CLIPTextModel,
    CLIPTokenizer,
    CLIPVisionConfig,
    CLIPVisionModelWithProjection,
)

from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableUnCLIPImgaImgPipeline, UNetaDConditionModel
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    floats_tensor,
    load_image,
    load_numpy,
    require_torch_gpu,
    skip_mps,
    slow,
    torch_device,
)

from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import (
    PipelineKarrasSchedulerTesterMixin,
    PipelineLatentTesterMixin,
    PipelineTesterMixin,
    assert_mean_pixel_difference,
)


enable_full_determinism()


class 	lowerCamelCase_     (   UpperCAmelCase_						,	UpperCAmelCase_						,	UpperCAmelCase_						,	unittest.TestCase ):






    '''simple docstring'''






    a__	:						int						=      StableUnCLIPImgaImgPipeline
    a__	:						Optional[int]						=      TEXT_GUIDED_IMAGE_VARIATION_PARAMS
    a__	:						Union[str, Any]						=      TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
    a__	:						Optional[Any]						=      frozenset(
        [] )  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
    a__	:						int						=      frozenset([] )







    def 			UpperCamelCase__   (	self)       ->	Tuple:
        __UpperCamelCase     :Tuple			  =		32
        __UpperCamelCase     :Optional[int]			  =		embedder_hidden_size

        # image encoding components

        __UpperCamelCase     :Union[str, Any]			  =		CLIPImageProcessor(crop_size=32 , size=32)

        torch.manual_seed(0)
        __UpperCamelCase     :Union[str, Any]			  =		CLIPVisionModelWithProjection(
            CLIPVisionConfig(
                hidden_size=__lowercase , projection_dim=__lowercase , num_hidden_layers=5 , num_attention_heads=4 , image_size=32 , intermediate_size=37 , patch_size=1 , ))

        # regular denoising components

        torch.manual_seed(0)
        __UpperCamelCase     :str			  =		StableUnCLIPImageNormalizer(embedding_dim=__lowercase)
        __UpperCamelCase     :Optional[int]			  =		DDPMScheduler(beta_schedule='''squaredcos_cap_v2''')

        torch.manual_seed(0)
        __UpperCamelCase     :Union[str, Any]			  =		CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''')

        torch.manual_seed(0)
        __UpperCamelCase     :Dict			  =		CLIPTextModel(
            CLIPTextConfig(
                bos_token_id=0 , eos_token_id=2 , hidden_size=__lowercase , projection_dim=32 , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ))

        torch.manual_seed(0)
        __UpperCamelCase     :List[Any]			  =		UNetaDConditionModel(
            sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('''CrossAttnDownBlock2D''', '''DownBlock2D''') , up_block_types=('''UpBlock2D''', '''CrossAttnUpBlock2D''') , block_out_channels=(32, 64) , attention_head_dim=(2, 4) , class_embed_type='''projection''' , projection_class_embeddings_input_dim=embedder_projection_dim * 2 , cross_attention_dim=__lowercase , layers_per_block=1 , upcast_attention=__lowercase , use_linear_projection=__lowercase , )

        torch.manual_seed(0)
        __UpperCamelCase     :Tuple			  =		DDIMScheduler(
            beta_schedule='''scaled_linear''' , beta_start=0.0_00_85 , beta_end=0.0_12 , prediction_type='''v_prediction''' , set_alpha_to_one=__lowercase , steps_offset=1 , )

        torch.manual_seed(0)
        __UpperCamelCase     :List[str]			  =		AutoencoderKL()

        __UpperCamelCase     :Tuple			  =		{
            # image encoding components
            '''feature_extractor''': feature_extractor,
            '''image_encoder''': image_encoder.eval(),
            # image noising components
            '''image_normalizer''': image_normalizer.eval(),
            '''image_noising_scheduler''': image_noising_scheduler,
            # regular denoising components
            '''tokenizer''': tokenizer,
            '''text_encoder''': text_encoder.eval(),
            '''unet''': unet.eval(),
            '''scheduler''': scheduler,
            '''vae''': vae.eval(),
        }

        return components







    def 			UpperCamelCase__   (	self , __lowercase , __lowercase=0 , __lowercase=True)       ->	str:
        if str(__lowercase).startswith('''mps'''):
            __UpperCamelCase     :Union[str, Any]			  =		torch.manual_seed(__lowercase)
        else:
            __UpperCamelCase     :int			  =		torch.Generator(device=__lowercase).manual_seed(__lowercase)

        __UpperCamelCase     :int			  =		floats_tensor((1, 3, 32, 32) , rng=random.Random(__lowercase)).to(__lowercase)

        if pil_image:
            __UpperCamelCase     :List[Any]			  =		input_image * 0.5 + 0.5
            __UpperCamelCase     :Optional[Any]			  =		input_image.clamp(0 , 1)
            __UpperCamelCase     :int			  =		input_image.cpu().permute(0 , 2 , 3 , 1).float().numpy()
            __UpperCamelCase     :Optional[Any]			  =		DiffusionPipeline.numpy_to_pil(__lowercase)[0]

        return {
            "prompt": "An anime racoon running a marathon",
            "image": input_image,
            "generator": generator,
            "num_inference_steps": 2,
            "output_type": "np",
        }







    @skip_mps
    def 			UpperCamelCase__   (	self)       ->	Union[str, Any]:
        __UpperCamelCase     :Dict			  =		'''cpu'''  # ensure determinism for the device-dependent torch.Generator
        __UpperCamelCase     :Tuple			  =		self.get_dummy_components()
        __UpperCamelCase     :Any			  =		StableUnCLIPImgaImgPipeline(**__lowercase)
        __UpperCamelCase     :Optional[Any]			  =		sd_pipe.to(__lowercase)
        sd_pipe.set_progress_bar_config(disable=__lowercase)

        __UpperCamelCase     :List[Any]			  =		self.get_dummy_inputs(__lowercase)
        inputs.update({'''image_embeds''': None})
        __UpperCamelCase     :Any			  =		sd_pipe(**__lowercase).images
        __UpperCamelCase     :List[str]			  =		image[0, -3:, -3:, -1]

        assert image.shape == (1, 32, 32, 3)
        __UpperCamelCase     :List[Any]			  =		np.array([0.38_72, 0.72_24, 0.56_01, 0.47_41, 0.68_72, 0.58_14, 0.46_36, 0.38_67, 0.50_78])

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







    def 			UpperCamelCase__   (	self)       ->	str:
        __UpperCamelCase     :Optional[Any]			  =		torch_device in ['''cpu''', '''mps''']

        self._test_attention_slicing_forward_pass(test_max_difference=__lowercase)







    def 			UpperCamelCase__   (	self)       ->	List[Any]:
        __UpperCamelCase     :Optional[Any]			  =		torch_device in ['''cpu''', '''mps''']

        self._test_inference_batch_single_identical(test_max_difference=__lowercase)







    @unittest.skipIf(
        torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , )
    def 			UpperCamelCase__   (	self)       ->	Union[str, Any]:
        self._test_xformers_attention_forwardGenerator_pass(test_max_difference=__lowercase)


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






    '''simple docstring'''






    def 			UpperCamelCase__   (	self)       ->	Union[str, Any]:
        # clean up the VRAM after each test
        super().tearDown()
        gc.collect()
        torch.cuda.empty_cache()







    def 			UpperCamelCase__   (	self)       ->	Union[str, Any]:
        __UpperCamelCase     :int			  =		load_image(
            '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png''')

        __UpperCamelCase     :Any			  =		load_numpy(
            '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_img2img_anime_turtle_fp16.npy''')

        __UpperCamelCase     :List[Any]			  =		StableUnCLIPImgaImgPipeline.from_pretrained(
            '''fusing/stable-unclip-2-1-l-img2img''' , torch_dtype=torch.floataa)
        pipe.to(__lowercase)
        pipe.set_progress_bar_config(disable=__lowercase)
        # stable unclip will oom when integration tests are run on a V100,
        # so turn on memory savings
        pipe.enable_attention_slicing()
        pipe.enable_sequential_cpu_offload()

        __UpperCamelCase     :int			  =		torch.Generator(device='''cpu''').manual_seed(0)
        __UpperCamelCase     :Dict			  =		pipe(__lowercase , '''anime turle''' , generator=__lowercase , output_type='''np''')

        __UpperCamelCase     :Dict			  =		output.images[0]

        assert image.shape == (768, 768, 3)

        assert_mean_pixel_difference(__lowercase , __lowercase)







    def 			UpperCamelCase__   (	self)       ->	List[str]:
        __UpperCamelCase     :Optional[Any]			  =		load_image(
            '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png''')

        __UpperCamelCase     :Any			  =		load_numpy(
            '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_h_img2img_anime_turtle_fp16.npy''')

        __UpperCamelCase     :Any			  =		StableUnCLIPImgaImgPipeline.from_pretrained(
            '''fusing/stable-unclip-2-1-h-img2img''' , torch_dtype=torch.floataa)
        pipe.to(__lowercase)
        pipe.set_progress_bar_config(disable=__lowercase)
        # stable unclip will oom when integration tests are run on a V100,
        # so turn on memory savings
        pipe.enable_attention_slicing()
        pipe.enable_sequential_cpu_offload()

        __UpperCamelCase     :int			  =		torch.Generator(device='''cpu''').manual_seed(0)
        __UpperCamelCase     :Optional[int]			  =		pipe(__lowercase , '''anime turle''' , generator=__lowercase , output_type='''np''')

        __UpperCamelCase     :List[Any]			  =		output.images[0]

        assert image.shape == (768, 768, 3)

        assert_mean_pixel_difference(__lowercase , __lowercase)







    def 			UpperCamelCase__   (	self)       ->	List[str]:
        __UpperCamelCase     :Dict			  =		load_image(
            '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png''')

        torch.cuda.empty_cache()
        torch.cuda.reset_max_memory_allocated()
        torch.cuda.reset_peak_memory_stats()

        __UpperCamelCase     :List[Any]			  =		StableUnCLIPImgaImgPipeline.from_pretrained(
            '''fusing/stable-unclip-2-1-h-img2img''' , torch_dtype=torch.floataa)
        __UpperCamelCase     :Union[str, Any]			  =		pipe.to(__lowercase)
        pipe.set_progress_bar_config(disable=__lowercase)
        pipe.enable_attention_slicing()
        pipe.enable_sequential_cpu_offload()

        __UpperCamelCase     :Optional[Any]			  =		pipe(
            __lowercase , '''anime turtle''' , num_inference_steps=2 , output_type='''np''' , )

        __UpperCamelCase     :int			  =		torch.cuda.max_memory_allocated()
        # make sure that less than 7 GB is allocated
        assert mem_bytes < 7 * 10**9





