


'''simple docstring'''





import json
import os
import re
import shutil
import tempfile
import unittest
from typing import Tuple

from transformers import AddedToken, BatchEncoding, PerceiverTokenizer
from transformers.utils import cached_property, is_tf_available, is_torch_available

from ...test_tokenization_common import TokenizerTesterMixin


if is_torch_available():
					UpperCAmelCase__  			=				'''pt'''
elif is_tf_available():
					UpperCAmelCase__  			=				'''tf'''
else:
					UpperCAmelCase__  			=				'''jax'''
class 						a__					(					a_      ,  unittest.TestCase   ):





			'''simple docstring'''

			A						:				int					      =			PerceiverTokenizer
			A						:				Optional[Any]					      =			False
			def 					lowerCAmelCase     (  self							:			List[Any]	)      ->		int:
						super().setUp()
						__A=	PerceiverTokenizer()
						tokenizer.save_pretrained(self.tmpdirname	)
			@cached_property
			def 					lowerCAmelCase     (  self							:			Optional[int]	)      ->		Any:
						return PerceiverTokenizer.from_pretrained('deepmind/language-perceiver'	)
			def 					lowerCAmelCase     (  self							:			Any			,    **lowerCAmelCase_							:			str	)      ->		PerceiverTokenizer:
						return self.tokenizer_class.from_pretrained(self.tmpdirname			,    **lowerCAmelCase_	)
			def 					lowerCAmelCase     (  self							:			Dict			,    lowerCAmelCase_							:			Dict			,    lowerCAmelCase_							:			Union[str, Any]=False			,    lowerCAmelCase_							:			Union[str, Any]=20			,    lowerCAmelCase_							:			List[str]=5	)      ->		Tuple[str, list]:
						# XXX The default common tokenizer tests assume that every ID is decodable on its own.
						# This assumption is invalid for Perceiver because single bytes might not be
						# valid utf-8 (byte 128 for instance).
						# Here we're overriding the smallest possible method to provide
						# a clean sequence without making the same assumption.

						__A=	[]
						for i in range(len(lowerCAmelCase_	)	):
									try:
												__A=	tokenizer.decode([i]			,    clean_up_tokenization_spaces=lowerCAmelCase_	)
									except UnicodeDecodeError:
												pass
									toks.append((i, tok)	)

						__A=	list(filter(lambda lowerCAmelCase_	: re.match(r'^[ a-zA-Z]+$'			,    t[1]	)			,    lowerCAmelCase_	)	)
						__A=	list(filter(lambda lowerCAmelCase_	: [t[0]] == tokenizer.encode(t[1]			,    add_special_tokens=lowerCAmelCase_	)			,    lowerCAmelCase_	)	)
						if max_length is not None and len(lowerCAmelCase_	) > max_length:
									__A=	toks[:max_length]
						if min_length is not None and len(lowerCAmelCase_	) < min_length and len(lowerCAmelCase_	) > 0:
									while len(lowerCAmelCase_	) < min_length:
												__A=	toks + toks
        # toks_str = [t[1] for t in toks]
						__A=	[t[0] for t in toks]

						# Ensure consistency
						__A=	tokenizer.decode(lowerCAmelCase_			,    clean_up_tokenization_spaces=lowerCAmelCase_	)
						if " " not in output_txt and len(lowerCAmelCase_	) > 1:
									__A=	(
									    tokenizer.decode([toks_ids[0]]			,    clean_up_tokenization_spaces=lowerCAmelCase_	)
									    + ' '
									    + tokenizer.decode(toks_ids[1:]			,    clean_up_tokenization_spaces=lowerCAmelCase_	)
									)
						if with_prefix_space:
									__A=	' ' + output_txt
						__A=	tokenizer.encode(lowerCAmelCase_			,    add_special_tokens=lowerCAmelCase_	)
						return output_txt, output_ids
			def 					lowerCAmelCase     (  self							:			Optional[Any]	)      ->		str:
						__A=	self.perceiver_tokenizer
						__A=	'Unicode €.'
						__A=	tokenizer(lowerCAmelCase_	)
						__A=	[4, 91, 116, 111, 105, 117, 106, 107, 38, 232, 136, 178, 52, 5]
						self.assertEqual(encoded['input_ids']			,    lowerCAmelCase_	)

						# decoding
						__A=	tokenizer.decode(lowerCAmelCase_	)
						self.assertEqual(lowerCAmelCase_			,    '[CLS]Unicode €.[SEP]'	)

						__A=	tokenizer('e è é ê ë'	)
						__A=	[4, 107, 38, 201, 174, 38, 201, 175, 38, 201, 176, 38, 201, 177, 5]
						self.assertEqual(encoded['input_ids']			,    lowerCAmelCase_	)
						# decoding
						__A=	tokenizer.decode(lowerCAmelCase_	)
						self.assertEqual(lowerCAmelCase_			,    '[CLS]e è é ê ë[SEP]'	)

						# encode/decode, but with `encode` instead of `__call__`
						self.assertEqual(tokenizer.decode(tokenizer.encode('e è é ê ë'	)	)			,    '[CLS]e è é ê ë[SEP]'	)
			def 					lowerCAmelCase     (  self							:			List[str]	)      ->		Tuple:
						__A=	self.perceiver_tokenizer
						__A=	['A long paragraph for summarization.', 'Another paragraph for summarization.']
						# fmt: off
						__A=	[4, 71, 38, 114, 117, 116, 109, 38, 118, 103, 120, 103, 109, 120, 103, 118, 110, 38, 108, 117, 120, 38, 121, 123, 115, 115, 103, 120, 111, 128, 103, 122, 111, 117, 116, 52, 5, 0]
						# fmt: on
						__A=	tokenizer(lowerCAmelCase_			,    padding=lowerCAmelCase_			,    return_tensors=lowerCAmelCase_	)
						self.assertIsInstance(lowerCAmelCase_			,    lowerCAmelCase_	)

						if FRAMEWORK != "jax":
									__A=	list(batch.input_ids.numpy()[0]	)
						else:
									__A=	list(batch.input_ids.tolist()[0]	)

						self.assertListEqual(lowerCAmelCase_			,    lowerCAmelCase_	)

						self.assertEqual((2, 38)			,    batch.input_ids.shape	)
						self.assertEqual((2, 38)			,    batch.attention_mask.shape	)
			def 					lowerCAmelCase     (  self							:			List[Any]	)      ->		Optional[Any]:
						__A=	self.perceiver_tokenizer
						__A=	['A long paragraph for summarization.', 'Another paragraph for summarization.']
						__A=	tokenizer(lowerCAmelCase_			,    padding=lowerCAmelCase_			,    return_tensors=lowerCAmelCase_	)
						# check if input_ids are returned and no decoder_input_ids
						self.assertIn('input_ids'			,    lowerCAmelCase_	)
						self.assertIn('attention_mask'			,    lowerCAmelCase_	)
						self.assertNotIn('decoder_input_ids'			,    lowerCAmelCase_	)
						self.assertNotIn('decoder_attention_mask'			,    lowerCAmelCase_	)
			def 					lowerCAmelCase     (  self							:			Optional[int]	)      ->		Dict:
						__A=	self.perceiver_tokenizer
						__A=	[
						    'Summary of the text.',
						    'Another summary.',
						]
						__A=	tokenizer(
						    text_target=lowerCAmelCase_			,    max_length=32			,    padding='max_length'			,    truncation=lowerCAmelCase_			,    return_tensors=lowerCAmelCase_	)
						self.assertEqual(32			,    targets['input_ids'].shape[1]	)
			def 					lowerCAmelCase     (  self							:			Any	)      ->		Tuple:
						# safety check on max_len default value so we are sure the test works
						__A=	self.get_tokenizers()
						for tokenizer in tokenizers:
									with self.subTest(F"""{tokenizer.__class__.__name__}"""	):
												self.assertNotEqual(tokenizer.model_max_length			,    42	)

        # Now let's start the test
						__A=	self.get_tokenizers()
						for tokenizer in tokenizers:
									with self.subTest(F"""{tokenizer.__class__.__name__}"""	):
												# Isolate this from the other tests because we save additional tokens/etc
												__A=	tempfile.mkdtemp()

												__A=	' He is very happy, UNwant\u00E9d,running'
												__A=	tokenizer.encode(lowerCAmelCase_			,    add_special_tokens=lowerCAmelCase_	)
												tokenizer.save_pretrained(lowerCAmelCase_	)

												__A=	tokenizer.__class__.from_pretrained(lowerCAmelCase_	)
												__A=	after_tokenizer.encode(lowerCAmelCase_			,    add_special_tokens=lowerCAmelCase_	)
												self.assertListEqual(lowerCAmelCase_			,    lowerCAmelCase_	)

												shutil.rmtree(lowerCAmelCase_	)

						__A=	self.get_tokenizers(model_max_length=42	)
						for tokenizer in tokenizers:
									with self.subTest(F"""{tokenizer.__class__.__name__}"""	):
												# Isolate this from the other tests because we save additional tokens/etc
												__A=	tempfile.mkdtemp()

												__A=	' He is very happy, UNwant\u00E9d,running'
												tokenizer.add_tokens(['bim', 'bambam']	)
												__A=	tokenizer.additional_special_tokens
												additional_special_tokens.append('new_additional_special_token'	)
												tokenizer.add_special_tokens({'additional_special_tokens': additional_special_tokens}	)
												__A=	tokenizer.encode(lowerCAmelCase_			,    add_special_tokens=lowerCAmelCase_	)
												tokenizer.save_pretrained(lowerCAmelCase_	)

												__A=	tokenizer.__class__.from_pretrained(lowerCAmelCase_	)
												__A=	after_tokenizer.encode(lowerCAmelCase_			,    add_special_tokens=lowerCAmelCase_	)
												self.assertListEqual(lowerCAmelCase_			,    lowerCAmelCase_	)
												self.assertIn('new_additional_special_token'			,    after_tokenizer.additional_special_tokens	)
												self.assertEqual(after_tokenizer.model_max_length			,    42	)

												__A=	tokenizer.__class__.from_pretrained(lowerCAmelCase_			,    model_max_length=43	)
												self.assertEqual(tokenizer.model_max_length			,    43	)

												shutil.rmtree(lowerCAmelCase_	)
			def 					lowerCAmelCase     (  self							:			Optional[Any]	)      ->		int:
						__A=	[]
						if self.test_slow_tokenizer:
									tokenizer_list.append((self.tokenizer_class, self.get_tokenizer())	)

						if self.test_rust_tokenizer:
									tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer())	)

						for tokenizer_class, tokenizer_utils in tokenizer_list:
									with tempfile.TemporaryDirectory() as tmp_dir:
												tokenizer_utils.save_pretrained(lowerCAmelCase_	)

												with open(os.path.join(lowerCAmelCase_			,    'special_tokens_map.json'	)			,    encoding='utf-8'	) as json_file:
															__A=	json.load(lowerCAmelCase_	)

												with open(os.path.join(lowerCAmelCase_			,    'tokenizer_config.json'	)			,    encoding='utf-8'	) as json_file:
															__A=	json.load(lowerCAmelCase_	)

												__A=	[F"""<extra_id_{i}>""" for i in range(125	)]

												__A=	added_tokens_extra_ids + [
												    'an_additional_special_token'
												]
												__A=	added_tokens_extra_ids + [
												    'an_additional_special_token'
												]

												with open(os.path.join(lowerCAmelCase_			,    'special_tokens_map.json'	)			,    'w'			,    encoding='utf-8'	) as outfile:
															json.dump(lowerCAmelCase_			,    lowerCAmelCase_	)
												with open(os.path.join(lowerCAmelCase_			,    'tokenizer_config.json'	)			,    'w'			,    encoding='utf-8'	) as outfile:
															json.dump(lowerCAmelCase_			,    lowerCAmelCase_	)

												# the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes
												# into account the new value of additional_special_tokens given in the "tokenizer_config.json" and
												# "special_tokens_map.json" files
												__A=	tokenizer_class.from_pretrained(
												    lowerCAmelCase_			,    )
												self.assertIn(
												    'an_additional_special_token'			,    tokenizer_without_change_in_init.additional_special_tokens	)
												self.assertEqual(
												    ['an_additional_special_token']			,    tokenizer_without_change_in_init.convert_ids_to_tokens(
												        tokenizer_without_change_in_init.convert_tokens_to_ids(['an_additional_special_token']	)	)			,    )

												# Now we test that we can change the value of additional_special_tokens in the from_pretrained
												__A=	added_tokens_extra_ids + [AddedToken('a_new_additional_special_token'			,    lstrip=lowerCAmelCase_	)]
												__A=	tokenizer_class.from_pretrained(
												    lowerCAmelCase_			,    additional_special_tokens=lowerCAmelCase_			,    )

												self.assertIn('a_new_additional_special_token'			,    tokenizer.additional_special_tokens	)
												self.assertEqual(
												    ['a_new_additional_special_token']			,    tokenizer.convert_ids_to_tokens(
												        tokenizer.convert_tokens_to_ids(['a_new_additional_special_token']	)	)			,    )
			def 					lowerCAmelCase     (  self							:			Optional[Any]	)      ->		int:
						__A=	self.perceiver_tokenizer
						self.assertEqual(tokenizer.decode([178]	)			,    '�'	)
			def 					lowerCAmelCase     (  self							:			Optional[Any]	)      ->		str:
						pass
			def 					lowerCAmelCase     (  self							:			Tuple	)      ->		Optional[int]:
						pass
			def 					lowerCAmelCase     (  self							:			Union[str, Any]	)      ->		Any:
						pass
			def 					lowerCAmelCase     (  self							:			List[Any]	)      ->		Optional[int]:
						pass

			def 					lowerCAmelCase     (  self							:			Optional[int]	)      ->		Union[str, Any]:
						# The default common tokenizer tests uses invalid tokens for Perceiver that can only accept one-character
						# strings and special added tokens as tokens
						__A=	self.get_tokenizers(fast=lowerCAmelCase_			,    do_lower_case=lowerCAmelCase_	)
						for tokenizer in tokenizers:
									with self.subTest(F"""{tokenizer.__class__.__name__}"""	):
												__A=	['[CLS]', 't', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 's', 't', '[SEP]']
												__A=	tokenizer.convert_tokens_to_string(lowerCAmelCase_	)

												self.assertIsInstance(lowerCAmelCase_			,    lowerCAmelCase_	)







'''simple docstring'''





from typing import Callable, List, Optional, Tuple, Union

import torch
from transformers import CLIPTextModel, CLIPTokenizer

from ...configuration_utils import ConfigMixin, register_to_config
from ...models import ModelMixin, TransformeraDModel, VQModel
from ...schedulers import VQDiffusionScheduler
from ...utils import logging
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput


UpperCAmelCase__  			=				logging.get_logger(__name__)  # pylint: disable=invalid-name
class 						a__					(					a_      ,  a_   ):





			'''simple docstring'''

			@register_to_config
			def __init__(  self							:			Any			,    lowerCAmelCase_							:			bool			,    lowerCAmelCase_							:			Optional[int] = None			,    lowerCAmelCase_							:			Optional[int] = None	)      ->		str:
						super().__init__()

						__A=	learnable

						if self.learnable:
									assert hidden_size is not None, "learnable=True requires `hidden_size` to be set"
									assert length is not None, "learnable=True requires `length` to be set"

									__A=	torch.zeros(lowerCAmelCase_			,    lowerCAmelCase_	)
						else:
									__A=	None

						__A=	torch.nn.Parameter(lowerCAmelCase_	)


class 						a__					(					a_   ):





			'''simple docstring'''

			A						:				VQModel
			A						:				CLIPTextModel
			A						:				CLIPTokenizer
			A						:				TransformeraDModel
			A						:				LearnedClassifierFreeSamplingEmbeddings
			A						:				VQDiffusionScheduler
			def __init__(  self							:			Optional[int]			,    lowerCAmelCase_							:			VQModel			,    lowerCAmelCase_							:			CLIPTextModel			,    lowerCAmelCase_							:			CLIPTokenizer			,    lowerCAmelCase_							:			TransformeraDModel			,    lowerCAmelCase_							:			VQDiffusionScheduler			,    lowerCAmelCase_							:			LearnedClassifierFreeSamplingEmbeddings			,    )      ->		Tuple:
						super().__init__()

						self.register_modules(
						    vqvae=lowerCAmelCase_			,    transformer=lowerCAmelCase_			,    text_encoder=lowerCAmelCase_			,    tokenizer=lowerCAmelCase_			,    scheduler=lowerCAmelCase_			,    learned_classifier_free_sampling_embeddings=lowerCAmelCase_			,    )
			def 					lowerCAmelCase     (  self							:			int			,    lowerCAmelCase_							:			List[str]			,    lowerCAmelCase_							:			Optional[Any]			,    lowerCAmelCase_							:			List[str]	)      ->		Union[str, Any]:
						__A=	len(lowerCAmelCase_	) if isinstance(lowerCAmelCase_			,    lowerCAmelCase_	) else 1

						# get prompt text embeddings
						__A=	self.tokenizer(
						    lowerCAmelCase_			,    padding='max_length'			,    max_length=self.tokenizer.model_max_length			,    return_tensors='pt'			,    )
						__A=	text_inputs.input_ids

						if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
									__A=	self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :]	)
									logger.warning(
									    'The following part of your input was truncated because CLIP can only handle sequences up to'
									    F""" {self.tokenizer.model_max_length} tokens: {removed_text}"""	)
									__A=	text_input_ids[:, : self.tokenizer.model_max_length]
						__A=	self.text_encoder(text_input_ids.to(self.device	)	)[0]

						# NOTE: This additional step of normalizing the text embeddings is from VQ-Diffusion.
						# While CLIP does normalize the pooled output of the text transformer when combining
						# the image and text embeddings, CLIP does not directly normalize the last hidden state.
						#
						# CLIP normalizing the pooled output.
						# https://github.com/huggingface/transformers/blob/d92e22d1f28324f513f3080e5c47c071a3916721/src/transformers/models/clip/modeling_clip.py#L1052-L1053
						__A=	prompt_embeds / prompt_embeds.norm(dim=-1			,    keepdim=lowerCAmelCase_	)

						# duplicate text embeddings for each generation per prompt
						__A=	prompt_embeds.repeat_interleave(lowerCAmelCase_			,    dim=0	)

						if do_classifier_free_guidance:
									if self.learned_classifier_free_sampling_embeddings.learnable:
												__A=	self.learned_classifier_free_sampling_embeddings.embeddings
												__A=	negative_prompt_embeds.unsqueeze(0	).repeat(lowerCAmelCase_			,    1			,    1	)
									else:
												__A=	[''] * batch_size

												__A=	text_input_ids.shape[-1]
												__A=	self.tokenizer(
												    lowerCAmelCase_			,    padding='max_length'			,    max_length=lowerCAmelCase_			,    truncation=lowerCAmelCase_			,    return_tensors='pt'			,    )
												__A=	self.text_encoder(uncond_input.input_ids.to(self.device	)	)[0]
												# See comment for normalizing text embeddings
												__A=	negative_prompt_embeds / negative_prompt_embeds.norm(dim=-1			,    keepdim=lowerCAmelCase_	)

									# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
									__A=	negative_prompt_embeds.shape[1]
									__A=	negative_prompt_embeds.repeat(1			,    lowerCAmelCase_			,    1	)
									__A=	negative_prompt_embeds.view(batch_size * num_images_per_prompt			,    lowerCAmelCase_			,    -1	)

									# For classifier free guidance, we need to do two forward passes.
									# Here we concatenate the unconditional and text embeddings into a single batch
									# to avoid doing two forward passes
									__A=	torch.cat([negative_prompt_embeds, prompt_embeds]	)

						return prompt_embeds
			@torch.no_grad()
			def __call__(  self							:			int			,    lowerCAmelCase_							:			Union[str, List[str]]			,    lowerCAmelCase_							:			int = 100			,    lowerCAmelCase_							:			float = 5.0			,    lowerCAmelCase_							:			float = 1.0			,    lowerCAmelCase_							:			int = 1			,    lowerCAmelCase_							:			Optional[Union[torch.Generator, List[torch.Generator]]] = None			,    lowerCAmelCase_							:			Optional[torch.FloatTensor] = None			,    lowerCAmelCase_							:			Optional[str] = "pil"			,    lowerCAmelCase_							:			bool = True			,    lowerCAmelCase_							:			Optional[Callable[[int, int, torch.FloatTensor], None]] = None			,    lowerCAmelCase_							:			int = 1			,    )      ->		Union[ImagePipelineOutput, Tuple]:
						if isinstance(lowerCAmelCase_			,    lowerCAmelCase_	):
									__A=	1
						elif isinstance(lowerCAmelCase_			,    lowerCAmelCase_	):
									__A=	len(lowerCAmelCase_	)
						else:
									raise ValueError(F"""`prompt` has to be of type `str` or `list` but is {type(lowerCAmelCase_	)}"""	)

						__A=	batch_size * num_images_per_prompt

						__A=	guidance_scale > 1.0

						__A=	self._encode_prompt(lowerCAmelCase_			,    lowerCAmelCase_			,    lowerCAmelCase_	)

						if (callback_steps is None) or (
						    callback_steps is not None and (not isinstance(lowerCAmelCase_			,    lowerCAmelCase_	) or callback_steps <= 0)
						):
									raise ValueError(
									    F"""`callback_steps` has to be a positive integer but is {callback_steps} of type"""
									    F""" {type(lowerCAmelCase_	)}."""	)

						# get the initial completely masked latents unless the user supplied it

						__A=	(batch_size, self.transformer.num_latent_pixels)
						if latents is None:
									__A=	self.transformer.num_vector_embeds - 1
									__A=	torch.full(lowerCAmelCase_			,    lowerCAmelCase_	).to(self.device	)
						else:
									if latents.shape != latents_shape:
												raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {latents_shape}"""	)
									if (latents < 0).any() or (latents >= self.transformer.num_vector_embeds).any():
												raise ValueError(
												    'Unexpected latents value(s). All latents be valid embedding indices i.e. in the range 0,'
												    F""" {self.transformer.num_vector_embeds - 1} (inclusive)."""	)
									__A=	latents.to(self.device	)

						# set timesteps
						self.scheduler.set_timesteps(lowerCAmelCase_			,    device=self.device	)

						__A=	self.scheduler.timesteps.to(self.device	)

						__A=	latents

						for i, t in enumerate(self.progress_bar(lowerCAmelCase_	)	):
									# expand the sample if we are doing classifier free guidance
									__A=	torch.cat([sample] * 2	) if do_classifier_free_guidance else sample

									# predict the un-noised image
									# model_output == `log_p_x_0`
									__A=	self.transformer(lowerCAmelCase_			,    encoder_hidden_states=lowerCAmelCase_			,    timestep=lowerCAmelCase_	).sample

									if do_classifier_free_guidance:
												__A,	__A=	model_output.chunk(2	)
												__A=	model_output_uncond + guidance_scale * (model_output_text - model_output_uncond)
												model_output -= torch.logsumexp(lowerCAmelCase_			,    dim=1			,    keepdim=lowerCAmelCase_	)

									__A=	self.truncate(lowerCAmelCase_			,    lowerCAmelCase_	)

									# remove `log(0)`'s (`-inf`s)
									__A=	model_output.clamp(-70	)

									# compute the previous noisy sample x_t -> x_t-1
									__A=	self.scheduler.step(lowerCAmelCase_			,    timestep=lowerCAmelCase_			,    sample=lowerCAmelCase_			,    generator=lowerCAmelCase_	).prev_sample

									# call the callback, if provided
									if callback is not None and i % callback_steps == 0:
												callback(lowerCAmelCase_			,    lowerCAmelCase_			,    lowerCAmelCase_	)

						__A=	self.vqvae.config.vq_embed_dim
						__A=	(batch_size, self.transformer.height, self.transformer.width, embedding_channels)
						__A=	self.vqvae.quantize.get_codebook_entry(lowerCAmelCase_			,    shape=lowerCAmelCase_	)
						__A=	self.vqvae.decode(lowerCAmelCase_			,    force_not_quantize=lowerCAmelCase_	).sample

						__A=	(image / 2 + 0.5).clamp(0			,    1	)
						__A=	image.cpu().permute(0			,    2			,    3			,    1	).numpy()

						if output_type == "pil":
									__A=	self.numpy_to_pil(lowerCAmelCase_	)

						if not return_dict:
									return (image,)

						return ImagePipelineOutput(images=lowerCAmelCase_	)

			def 					lowerCAmelCase     (  self							:			Any			,    lowerCAmelCase_							:			torch.FloatTensor			,    lowerCAmelCase_							:			float	)      ->		torch.FloatTensor:
						__A,	__A=	torch.sort(lowerCAmelCase_			,    1			,    descending=lowerCAmelCase_	)
						__A=	torch.exp(lowerCAmelCase_	)
						__A=	sorted_p_x_0.cumsum(dim=1	) < truncation_rate

						# Ensure that at least the largest probability is not zeroed out
						__A=	torch.full_like(keep_mask[:, 0:1, :]			,    lowerCAmelCase_	)
						__A=	torch.cat((all_true, keep_mask)			,    dim=1	)
						__A=	keep_mask[:, :-1, :]

						__A=	keep_mask.gather(1			,    indices.argsort(1	)	)

						__A=	log_p_x_0.clone()

						__A=	-torch.inf  # -inf = log(0)

						return rv



