


'''simple docstring'''





import inspect
import unittest

from transformers import DPTConfig
from transformers.file_utils import is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
					import torch
					from torch import nn

					from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel
					from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
					from PIL import Image

					from transformers import DPTImageProcessor
class 						a__					:





			'''simple docstring'''

			def __init__(  self							:			int			,    lowerCAmelCase_							:			Any			,    lowerCAmelCase_							:			List[str]=2			,    lowerCAmelCase_							:			List[Any]=32			,    lowerCAmelCase_							:			int=16			,    lowerCAmelCase_							:			List[Any]=3			,    lowerCAmelCase_							:			str=True			,    lowerCAmelCase_							:			List[str]=True			,    lowerCAmelCase_							:			Any=32			,    lowerCAmelCase_							:			Optional[int]=4			,    lowerCAmelCase_							:			Any=[0, 1, 2, 3]			,    lowerCAmelCase_							:			str=4			,    lowerCAmelCase_							:			Optional[Any]=37			,    lowerCAmelCase_							:			Tuple="gelu"			,    lowerCAmelCase_							:			Union[str, Any]=0.1			,    lowerCAmelCase_							:			Union[str, Any]=0.1			,    lowerCAmelCase_							:			List[Any]=0.02			,    lowerCAmelCase_							:			Optional[Any]=3			,    lowerCAmelCase_							:			Union[str, Any]=[1, 384, 24, 24]			,    lowerCAmelCase_							:			Union[str, Any]=True			,    lowerCAmelCase_							:			Optional[int]=None			,    )      ->		str:
						__A=	parent
						__A=	batch_size
						__A=	image_size
						__A=	patch_size
						__A=	num_channels
						__A=	is_training
						__A=	use_labels
						__A=	hidden_size
						__A=	num_hidden_layers
						__A=	backbone_out_indices
						__A=	num_attention_heads
						__A=	intermediate_size
						__A=	hidden_act
						__A=	hidden_dropout_prob
						__A=	attention_probs_dropout_prob
						__A=	initializer_range
						__A=	num_labels
						__A=	backbone_featmap_shape
						__A=	scope
						__A=	is_hybrid
						# sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token)
						__A=	(image_size // patch_size) ** 2
						__A=	num_patches + 1
			def 					lowerCAmelCase     (  self							:			Optional[int]	)      ->		Tuple:
						__A=	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

						__A=	None
						if self.use_labels:
									__A=	ids_tensor([self.batch_size, self.image_size, self.image_size]			,    self.num_labels	)

						__A=	self.get_config()

						return config, pixel_values, labels
			def 					lowerCAmelCase     (  self							:			Tuple	)      ->		List[Any]:
						__A=	{
						    'global_padding': 'same',
						    'layer_type': 'bottleneck',
						    'depths': [3, 4, 9],
						    'out_features': ['stage1', 'stage2', 'stage3'],
						    'embedding_dynamic_padding': True,
						    'hidden_sizes': [96, 192, 384, 768],
						    'num_groups': 2,
						}

						return DPTConfig(
						    image_size=self.image_size			,    patch_size=self.patch_size			,    num_channels=self.num_channels			,    hidden_size=self.hidden_size			,    num_hidden_layers=self.num_hidden_layers			,    backbone_out_indices=self.backbone_out_indices			,    num_attention_heads=self.num_attention_heads			,    intermediate_size=self.intermediate_size			,    hidden_act=self.hidden_act			,    hidden_dropout_prob=self.hidden_dropout_prob			,    attention_probs_dropout_prob=self.attention_probs_dropout_prob			,    is_decoder=lowerCAmelCase_			,    initializer_range=self.initializer_range			,    is_hybrid=self.is_hybrid			,    backbone_config=lowerCAmelCase_			,    backbone_featmap_shape=self.backbone_featmap_shape			,    )
			def 					lowerCAmelCase     (  self							:			Optional[int]			,    lowerCAmelCase_							:			Tuple			,    lowerCAmelCase_							:			Tuple			,    lowerCAmelCase_							:			Tuple	)      ->		Union[str, Any]:
						__A=	DPTModel(config=lowerCAmelCase_	)
						model.to(lowerCAmelCase_	)
						model.eval()
						__A=	model(lowerCAmelCase_	)
						self.parent.assertEqual(result.last_hidden_state.shape			,    (self.batch_size, self.seq_length, self.hidden_size)	)
			def 					lowerCAmelCase     (  self							:			List[str]			,    lowerCAmelCase_							:			int			,    lowerCAmelCase_							:			Any			,    lowerCAmelCase_							:			Union[str, Any]	)      ->		Optional[int]:
						__A=	self.num_labels
						__A=	DPTForDepthEstimation(lowerCAmelCase_	)
						model.to(lowerCAmelCase_	)
						model.eval()
						__A=	model(lowerCAmelCase_	)
						self.parent.assertEqual(result.predicted_depth.shape			,    (self.batch_size, self.image_size, self.image_size)	)
			def 					lowerCAmelCase     (  self							:			Union[str, Any]			,    lowerCAmelCase_							:			Optional[int]			,    lowerCAmelCase_							:			List[Any]			,    lowerCAmelCase_							:			Optional[int]	)      ->		Tuple:
						__A=	self.num_labels
						__A=	DPTForSemanticSegmentation(lowerCAmelCase_	)
						model.to(lowerCAmelCase_	)
						model.eval()
						__A=	model(lowerCAmelCase_			,    labels=lowerCAmelCase_	)
						self.parent.assertEqual(
						    result.logits.shape			,    (self.batch_size, self.num_labels, self.image_size, self.image_size)	)

			def 					lowerCAmelCase     (  self							:			Dict	)      ->		Any:
						__A=	self.prepare_config_and_inputs()
						__A,	__A,	__A=	config_and_inputs
						__A=	{'pixel_values': pixel_values}
						return config, inputs_dict


@require_torch
class 						a__					(					a_      ,  a_      ,  unittest.TestCase   ):





			'''simple docstring'''

			A						:				Optional[Any]					      =			(DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else ()
			A						:				Optional[Any]					      =			(
			    {
			        '''depth-estimation''': DPTForDepthEstimation,
			        '''feature-extraction''': DPTModel,
			        '''image-segmentation''': DPTForSemanticSegmentation,
			    }
			    if is_torch_available()
			    else {}
			)

			A						:				int					      =			False
			A						:				Dict					      =			False
			A						:				Optional[int]					      =			False
			def 					lowerCAmelCase     (  self							:			Optional[int]	)      ->		Optional[Any]:
						__A=	DPTModelTester(self	)
						__A=	ConfigTester(self			,    config_class=lowerCAmelCase_			,    has_text_modality=lowerCAmelCase_			,    hidden_size=37	)
			def 					lowerCAmelCase     (  self							:			str	)      ->		str:
						self.config_tester.run_common_tests()
			@unittest.skip(reason='DPT does not use inputs_embeds'	)
			def 					lowerCAmelCase     (  self							:			Optional[Any]	)      ->		List[Any]:
						pass
			def 					lowerCAmelCase     (  self							:			str	)      ->		Optional[Any]:
						__A,	__A=	self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
									__A=	model_class(lowerCAmelCase_	)
									self.assertIsInstance(model.get_input_embeddings()			,    (nn.Module)	)
									__A=	model.get_output_embeddings()
									self.assertTrue(x is None or isinstance(lowerCAmelCase_			,    nn.Linear	)	)
			def 					lowerCAmelCase     (  self							:			Dict	)      ->		List[Any]:
						__A,	__A=	self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
									__A=	model_class(lowerCAmelCase_	)
									__A=	inspect.signature(model.forward	)
									# signature.parameters is an OrderedDict => so arg_names order is deterministic
									__A=	[*signature.parameters.keys()]

									__A=	['pixel_values']
									self.assertListEqual(arg_names[:1]			,    lowerCAmelCase_	)
			def 					lowerCAmelCase     (  self							:			Optional[Any]	)      ->		Tuple:
						__A=	self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*lowerCAmelCase_	)
			def 					lowerCAmelCase     (  self							:			List[str]	)      ->		List[Any]:
						__A=	self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_depth_estimation(*lowerCAmelCase_	)
			def 					lowerCAmelCase     (  self							:			int	)      ->		Dict:
						__A=	self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_semantic_segmentation(*lowerCAmelCase_	)
			def 					lowerCAmelCase     (  self							:			str	)      ->		Union[str, Any]:
						for model_class in self.all_model_classes:
									if model_class.__name__ == "DPTForDepthEstimation":
												continue

									__A,	__A=	self.model_tester.prepare_config_and_inputs_for_common()
									__A=	True

									if model_class in get_values(lowerCAmelCase_	):
												continue

									__A=	model_class(lowerCAmelCase_	)
									model.to(lowerCAmelCase_	)
									model.train()
									__A=	self._prepare_for_class(lowerCAmelCase_			,    lowerCAmelCase_			,    return_labels=lowerCAmelCase_	)
									__A=	model(**lowerCAmelCase_	).loss
									loss.backward()
			def 					lowerCAmelCase     (  self							:			List[Any]	)      ->		Dict:
						for model_class in self.all_model_classes:
									if model_class.__name__ == "DPTForDepthEstimation":
												continue

									__A,	__A=	self.model_tester.prepare_config_and_inputs_for_common()
									__A=	False
									__A=	True

									if model_class in get_values(lowerCAmelCase_	) or not model_class.supports_gradient_checkpointing:
												continue
									__A=	model_class(lowerCAmelCase_	)
									model.to(lowerCAmelCase_	)
									model.gradient_checkpointing_enable()
									model.train()
									__A=	self._prepare_for_class(lowerCAmelCase_			,    lowerCAmelCase_			,    return_labels=lowerCAmelCase_	)
									__A=	model(**lowerCAmelCase_	).loss
									loss.backward()
			def 					lowerCAmelCase     (  self							:			Optional[Any]	)      ->		int:
						__A,	__A=	self.model_tester.prepare_config_and_inputs_for_common()

						__A=	_config_zero_init(lowerCAmelCase_	)
						for model_class in self.all_model_classes:
									__A=	model_class(config=lowerCAmelCase_	)
									# Skip the check for the backbone
									__A=	[]
									for name, module in model.named_modules():
												if module.__class__.__name__ == "DPTViTHybridEmbeddings":
															__A=	[F"""{name}.{key}""" for key in module.state_dict().keys()]
															break

									for name, param in model.named_parameters():
												if param.requires_grad:
															if name in backbone_params:
																		continue
															self.assertIn(
															    ((param.data.mean() * 1E9).round() / 1E9).item()			,    [0.0, 1.0]			,    msg=F"""Parameter {name} of model {model_class} seems not properly initialized"""			,    )
			@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'	)
			def 					lowerCAmelCase     (  self							:			str	)      ->		Optional[int]:
						pass
			@slow
			def 					lowerCAmelCase     (  self							:			Optional[Any]	)      ->		Any:
						for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]:
									__A=	DPTModel.from_pretrained(lowerCAmelCase_	)
									self.assertIsNotNone(lowerCAmelCase_	)

			def 					lowerCAmelCase     (  self							:			List[Any]	)      ->		Dict:
						# We do this test only for DPTForDepthEstimation since it is the only model that uses readout_type
						__A,	__A=	self.model_tester.prepare_config_and_inputs_for_common()
						__A=	'add'
						with self.assertRaises(lowerCAmelCase_	):
									__A=	DPTForDepthEstimation(lowerCAmelCase_	)






def 						UpperCAmelCase__(				):






			"""simple docstring"""




			__A=	Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
			return image






@require_torch
@require_vision
@slow
class 						a__					(					unittest.TestCase   ):





			'''simple docstring'''

			def 					lowerCAmelCase     (  self							:			Any	)      ->		Optional[int]:
						__A=	DPTImageProcessor.from_pretrained('Intel/dpt-hybrid-midas'	)
						__A=	DPTForDepthEstimation.from_pretrained('Intel/dpt-hybrid-midas'	).to(lowerCAmelCase_	)

						__A=	prepare_img()
						__A=	image_processor(images=lowerCAmelCase_			,    return_tensors='pt'	).to(lowerCAmelCase_	)

						# forward pass
						with torch.no_grad():
									__A=	model(**lowerCAmelCase_	)
									__A=	outputs.predicted_depth

						# verify the predicted depth
						__A=	torch.Size((1, 384, 384)	)
						self.assertEqual(predicted_depth.shape			,    lowerCAmelCase_	)

						__A=	torch.tensor(
						    [[[5.64_37, 5.61_46, 5.65_11], [5.43_71, 5.56_49, 5.59_58], [5.52_15, 5.51_84, 5.52_93]]]	).to(lowerCAmelCase_	)

						self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 100			,    lowerCAmelCase_			,    atol=1E-4	)	)







'''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



