



"""simple docstring"""


import torch

from diffusers import HeunDiscreteScheduler
from diffusers.utils import torch_device

from .test_schedulers import SchedulerCommonTest







class  A_     (	SCREAMING_SNAKE_CASE_							):



						"""simple docstring"""
						__UpperCamelCase													=				(HeunDiscreteScheduler,)
						__UpperCamelCase													=				10






						def       UpperCAmelCase__	(   self					:int  ,    **lowercase_					:str   )							->     Any:
												UpperCAmelCase			 =					{
												    'num_train_timesteps': 11_00,
												    'beta_start': 0.0001,
												    'beta_end': 0.02,
												    'beta_schedule': 'linear',
												}

												config.update(**lowercase_   )
												return config






						def       UpperCAmelCase__	(   self					:List[str]   )							->     int:
												for timesteps in [10, 50, 1_00, 10_00]:
																		self.check_over_configs(num_train_timesteps=lowercase_   )






						def       UpperCAmelCase__	(   self					:Any   )							->     Tuple:
												for beta_start, beta_end in zip([0.0_0001, 0.0001, 0.001]  ,    [0.0002, 0.002, 0.02]   ):
																		self.check_over_configs(beta_start=lowercase_  ,    beta_end=lowercase_   )






						def       UpperCAmelCase__	(   self					:List[Any]   )							->     List[str]:
												for schedule in ["linear", "scaled_linear", "exp"]:
																		self.check_over_configs(beta_schedule=lowercase_   )






						def       UpperCAmelCase__	(   self					:Tuple   )							->     str:
												for clip_sample_range in [1.0, 2.0, 3.0]:
																		self.check_over_configs(clip_sample_range=lowercase_  ,    clip_sample=lowercase_   )






						def       UpperCAmelCase__	(   self					:Tuple   )							->     Optional[Any]:
												for prediction_type in ["epsilon", "v_prediction", "sample"]:
																		self.check_over_configs(prediction_type=lowercase_   )






						def       UpperCAmelCase__	(   self					:int   )							->     Optional[Any]:
												UpperCAmelCase			 =					self.scheduler_classes[0]
												UpperCAmelCase			 =					self.get_scheduler_config()
												UpperCAmelCase			 =					scheduler_class(**lowercase_   )

												scheduler.set_timesteps(self.num_inference_steps   )

												UpperCAmelCase			 =					self.dummy_model()
												UpperCAmelCase			 =					self.dummy_sample_deter * scheduler.init_noise_sigma
												UpperCAmelCase			 =					sample.to(lowercase_   )

												for i, t in enumerate(scheduler.timesteps   ):
																		UpperCAmelCase			 =					scheduler.scale_model_input(lowercase_  ,    lowercase_   )

																		UpperCAmelCase			 =					model(lowercase_  ,    lowercase_   )

																		UpperCAmelCase			 =					scheduler.step(lowercase_  ,    lowercase_  ,    lowercase_   )
																		UpperCAmelCase			 =					output.prev_sample

												UpperCAmelCase			 =					torch.sum(torch.abs(lowercase_   )   )
												UpperCAmelCase			 =					torch.mean(torch.abs(lowercase_   )   )

												if torch_device in ["cpu", "mps"]:
																		assert abs(result_sum.item() - 0.1233   ) < 1E-2
																		assert abs(result_mean.item() - 0.0002   ) < 1E-3
												else:
																		# CUDA
																		assert abs(result_sum.item() - 0.1233   ) < 1E-2
																		assert abs(result_mean.item() - 0.0002   ) < 1E-3






						def       UpperCAmelCase__	(   self					:Tuple   )							->     int:
												UpperCAmelCase			 =					self.scheduler_classes[0]
												UpperCAmelCase			 =					self.get_scheduler_config(prediction_type='v_prediction'   )
												UpperCAmelCase			 =					scheduler_class(**lowercase_   )

												scheduler.set_timesteps(self.num_inference_steps   )

												UpperCAmelCase			 =					self.dummy_model()
												UpperCAmelCase			 =					self.dummy_sample_deter * scheduler.init_noise_sigma
												UpperCAmelCase			 =					sample.to(lowercase_   )

												for i, t in enumerate(scheduler.timesteps   ):
																		UpperCAmelCase			 =					scheduler.scale_model_input(lowercase_  ,    lowercase_   )

																		UpperCAmelCase			 =					model(lowercase_  ,    lowercase_   )

																		UpperCAmelCase			 =					scheduler.step(lowercase_  ,    lowercase_  ,    lowercase_   )
																		UpperCAmelCase			 =					output.prev_sample

												UpperCAmelCase			 =					torch.sum(torch.abs(lowercase_   )   )
												UpperCAmelCase			 =					torch.mean(torch.abs(lowercase_   )   )

												if torch_device in ["cpu", "mps"]:
																		assert abs(result_sum.item() - 4.6_934E-07   ) < 1E-2
																		assert abs(result_mean.item() - 6.1_112E-10   ) < 1E-3
												else:
																		# CUDA
																		assert abs(result_sum.item() - 4.693_428_650_170_972E-07   ) < 1E-2
																		assert abs(result_mean.item() - 0.0002   ) < 1E-3






						def       UpperCAmelCase__	(   self					:str   )							->     int:
												UpperCAmelCase			 =					self.scheduler_classes[0]
												UpperCAmelCase			 =					self.get_scheduler_config()
												UpperCAmelCase			 =					scheduler_class(**lowercase_   )

												scheduler.set_timesteps(self.num_inference_steps  ,    device=lowercase_   )

												UpperCAmelCase			 =					self.dummy_model()
												UpperCAmelCase			 =					self.dummy_sample_deter.to(lowercase_   ) * scheduler.init_noise_sigma

												for t in scheduler.timesteps:
																		UpperCAmelCase			 =					scheduler.scale_model_input(lowercase_  ,    lowercase_   )

																		UpperCAmelCase			 =					model(lowercase_  ,    lowercase_   )

																		UpperCAmelCase			 =					scheduler.step(lowercase_  ,    lowercase_  ,    lowercase_   )
																		UpperCAmelCase			 =					output.prev_sample

												UpperCAmelCase			 =					torch.sum(torch.abs(lowercase_   )   )
												UpperCAmelCase			 =					torch.mean(torch.abs(lowercase_   )   )

												if str(lowercase_   ).startswith('cpu'   ):
																		# The following sum varies between 148 and 156 on mps. Why?
																		assert abs(result_sum.item() - 0.1233   ) < 1E-2
																		assert abs(result_mean.item() - 0.0002   ) < 1E-3
												elif str(lowercase_   ).startswith('mps'   ):
																		# Larger tolerance on mps
																		assert abs(result_mean.item() - 0.0002   ) < 1E-2
												else:
																		# CUDA
																		assert abs(result_sum.item() - 0.1233   ) < 1E-2
																		assert abs(result_mean.item() - 0.0002   ) < 1E-3






						def       UpperCAmelCase__	(   self					:List[Any]   )							->     Optional[Any]:
												UpperCAmelCase			 =					self.scheduler_classes[0]
												UpperCAmelCase			 =					self.get_scheduler_config()
												UpperCAmelCase			 =					scheduler_class(**lowercase_  ,    use_karras_sigmas=lowercase_   )

												scheduler.set_timesteps(self.num_inference_steps  ,    device=lowercase_   )

												UpperCAmelCase			 =					self.dummy_model()
												UpperCAmelCase			 =					self.dummy_sample_deter.to(lowercase_   ) * scheduler.init_noise_sigma
												UpperCAmelCase			 =					sample.to(lowercase_   )

												for t in scheduler.timesteps:
																		UpperCAmelCase			 =					scheduler.scale_model_input(lowercase_  ,    lowercase_   )

																		UpperCAmelCase			 =					model(lowercase_  ,    lowercase_   )

																		UpperCAmelCase			 =					scheduler.step(lowercase_  ,    lowercase_  ,    lowercase_   )
																		UpperCAmelCase			 =					output.prev_sample

												UpperCAmelCase			 =					torch.sum(torch.abs(lowercase_   )   )
												UpperCAmelCase			 =					torch.mean(torch.abs(lowercase_   )   )

												assert abs(result_sum.item() - 0.0_0015   ) < 1E-2
												assert abs(result_mean.item() - 1.9_869_554_535_034_695E-07   ) < 1E-2










"""simple docstring"""


from typing import List, Optional, Tuple

from tokenizers import pre_tokenizers

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_clip import CLIPTokenizer


snake_case_								=			logging.get_logger(__name__)

snake_case_								=			{"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""}

snake_case_								=			{
    """vocab_file""": {
        """openai/clip-vit-base-patch32""": """https://huggingface.co/openai/clip-vit-base-patch32/resolve/main/vocab.json""",
    },
    """merges_file""": {
        """openai/clip-vit-base-patch32""": """https://huggingface.co/openai/clip-vit-base-patch32/resolve/main/merges.txt""",
    },
    """tokenizer_file""": {
        """openai/clip-vit-base-patch32""": (
            """https://huggingface.co/openai/clip-vit-base-patch32/resolve/main/tokenizer.json"""
        ),
    },
}

snake_case_								=			{
    """openai/clip-vit-base-patch32""": 77,
}







class  A_     (	SCREAMING_SNAKE_CASE_							):



						"""simple docstring"""
						__UpperCamelCase													=				VOCAB_FILES_NAMES
						__UpperCamelCase													=				PRETRAINED_VOCAB_FILES_MAP
						__UpperCamelCase													=				PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
						__UpperCamelCase													=				["""input_ids""", """attention_mask"""]
						__UpperCamelCase													=				CLIPTokenizer






						def __init__(   self					:int  ,    lowercase_					:Optional[int]=None  ,    lowercase_					:int=None  ,    lowercase_					:Optional[Any]=None  ,    lowercase_					:Dict="<|endoftext|>"  ,    lowercase_					:List[Any]="<|startoftext|>"  ,    lowercase_					:Any="<|endoftext|>"  ,    lowercase_					:List[str]="<|endoftext|>"  ,    **lowercase_					:Tuple  ,    )							->     List[Any]:
												super().__init__(
												    lowercase_  ,    lowercase_  ,    tokenizer_file=lowercase_  ,    unk_token=lowercase_  ,    bos_token=lowercase_  ,    eos_token=lowercase_  ,    pad_token=lowercase_  ,    **lowercase_  ,    )

												if not isinstance(self.backend_tokenizer.pre_tokenizer  ,    pre_tokenizers.Sequence   ):
																		raise ValueError(
																		    'The `backend_tokenizer` provided does not match the expected format. The CLIP tokenizer has been'
																		    ' heavily modified from transformers version 4.17.0. You need to convert the tokenizer you are using'
																		    ' to be compatible with this version.The easiest way to do so is'
																		    ' `CLIPTokenizerFast.from_pretrained("path_to_local_folder_or_hub_repo, from_slow=True)`. If you want'
																		    ' to use your existing tokenizer, you will have to revert to a version prior to 4.17.0 of'
																		    ' transformers.'   )

												self._wrap_decode_method_backend_tokenizer()






						def       UpperCAmelCase__	(   self					:Dict   )							->     List[Any]:
												UpperCAmelCase			 =					self.backend_tokenizer.decode

												def new_decode_method(*lowercase_					:List[Any]  ,    **lowercase_					:Optional[Any]   ):
																		UpperCAmelCase			 =					orig_decode_method(*lowercase_  ,    **lowercase_   )
																		UpperCAmelCase			 =					text.replace(self.backend_tokenizer.model.end_of_word_suffix  ,    ' '   ).strip()
																		return text

												UpperCAmelCase			 =					new_decode_method






						def       UpperCAmelCase__	(   self					:Optional[int]  ,    lowercase_					:List[int]  ,    lowercase_					:Optional[List[int]] = None   )							->     List[int]:
												UpperCAmelCase			 =					[self.bos_token_id]
												UpperCAmelCase			 =					[self.eos_token_id]

												if token_ids_a is None:
																		return bos_token + token_ids_a + eos_token
												return bos_token + token_ids_a + eos_token + eos_token + token_ids_a + eos_token






						def       UpperCAmelCase__	(   self					:Dict  ,    lowercase_					:List[int]  ,    lowercase_					:Optional[List[int]] = None   )							->     List[int]:
												UpperCAmelCase			 =					[self.bos_token_id]
												UpperCAmelCase			 =					[self.eos_token_id]

												if token_ids_a is None:
																		return len(bos_token + token_ids_a + eos_token   ) * [0]
												return len(bos_token + token_ids_a + eos_token + eos_token + token_ids_a + eos_token   ) * [0]






						def       UpperCAmelCase__	(   self					:Optional[Any]  ,    lowercase_					:str  ,    lowercase_					:Optional[str] = None   )							->     Tuple[str]:
												UpperCAmelCase			 =					self._tokenizer.model.save(lowercase_  ,    name=lowercase_   )
												return tuple(lowercase_   )





