






from __future__ import annotations

import unittest

from transformers import XGLMConfig, XGLMTokenizer, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
		import tensorflow as tf

		from transformers.models.xglm.modeling_tf_xglm import (
		    TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST,
		    TFXGLMForCausalLM,
		    TFXGLMModel,
		)



@require_tf
class   lowerCamelCase				:







		'''simple docstring'''



		_snake_case   :   List[Any]							=  XGLMConfig
		_snake_case   :   Optional[int]							=  {}
		_snake_case   :   List[Any]							=  '''gelu'''



		def __init__(							self    ,		_UpperCamelCase    ,		_UpperCamelCase=1_4    ,		_UpperCamelCase=7    ,		_UpperCamelCase=True    ,		_UpperCamelCase=True    ,		_UpperCamelCase=True    ,		_UpperCamelCase=9_9    ,		_UpperCamelCase=3_2    ,		_UpperCamelCase=2    ,		_UpperCamelCase=4    ,		_UpperCamelCase=3_7    ,		_UpperCamelCase="gelu"    ,		_UpperCamelCase=0.1    ,		_UpperCamelCase=0.1    ,		_UpperCamelCase=5_1_2    ,		_UpperCamelCase=0.02    ,		)     ->							List[Any]:
							UpperCAmelCase_   :				Union[str, Any]						=						parent
							UpperCAmelCase_   :				List[Any]						=						batch_size
							UpperCAmelCase_   :				Optional[int]						=						seq_length
							UpperCAmelCase_   :				Optional[int]						=						is_training
							UpperCAmelCase_   :				List[Any]						=						use_input_mask
							UpperCAmelCase_   :				List[str]						=						use_labels
							UpperCAmelCase_   :				Any						=						vocab_size
							UpperCAmelCase_   :				Dict						=						d_model
							UpperCAmelCase_   :				Any						=						num_hidden_layers
							UpperCAmelCase_   :				Optional[Any]						=						num_attention_heads
							UpperCAmelCase_   :				Union[str, Any]						=						ffn_dim
							UpperCAmelCase_   :				str						=						activation_function
							UpperCAmelCase_   :				List[Any]						=						activation_dropout
							UpperCAmelCase_   :				Union[str, Any]						=						attention_dropout
							UpperCAmelCase_   :				Union[str, Any]						=						max_position_embeddings
							UpperCAmelCase_   :				Union[str, Any]						=						initializer_range
							UpperCAmelCase_   :				List[str]						=						None
							UpperCAmelCase_   :				Tuple						=						0
							UpperCAmelCase_   :				Dict						=						2
							UpperCAmelCase_   :				Union[str, Any]						=						1



		def  __UpperCAmelCase      (							self       )     ->							Optional[Any]:
							return XGLMConfig.from_pretrained('facebook/xglm-564M'       )



		def  __UpperCAmelCase      (							self       )     ->							Optional[int]:
							UpperCAmelCase_   :				str						=						tf.clip_by_value(
							    ids_tensor([self.batch_size, self.seq_length]    ,		self.vocab_size       )    ,		clip_value_min=0    ,		clip_value_max=3       )

							UpperCAmelCase_   :				Tuple						=						None
							if self.use_input_mask:
												UpperCAmelCase_   :				Union[str, Any]						=						random_attention_mask([self.batch_size, self.seq_length]       )

							UpperCAmelCase_   :				Tuple						=						self.get_config()

							UpperCAmelCase_   :				List[Any]						=						floats_tensor([self.num_hidden_layers, self.num_attention_heads]    ,		2       )

							return (
							    config,
							    input_ids,
							    input_mask,
							    head_mask,
							)



		def  __UpperCAmelCase      (							self       )     ->							Dict:
							return XGLMConfig(
							    vocab_size=self.vocab_size    ,		d_model=self.hidden_size    ,		num_layers=self.num_hidden_layers    ,		attention_heads=self.num_attention_heads    ,		ffn_dim=self.ffn_dim    ,		activation_function=self.activation_function    ,		activation_dropout=self.activation_dropout    ,		attention_dropout=self.attention_dropout    ,		max_position_embeddings=self.max_position_embeddings    ,		initializer_range=self.initializer_range    ,		use_cache=_UpperCamelCase    ,		bos_token_id=self.bos_token_id    ,		eos_token_id=self.eos_token_id    ,		pad_token_id=self.pad_token_id    ,		return_dict=_UpperCamelCase    ,		)



		def  __UpperCAmelCase      (							self       )     ->							Any:
							UpperCAmelCase_   :				Dict						=						self.prepare_config_and_inputs()

							(
							    (
							    UpperCAmelCase_
							)	,  (
							    UpperCAmelCase_
							)	,  (
							    UpperCAmelCase_
							)	,  (
							    UpperCAmelCase_
							)	,  
							)   :				Tuple						=						config_and_inputs

							UpperCAmelCase_   :				Union[str, Any]						=						{
							    'input_ids': input_ids,
							    'head_mask': head_mask,
							}

							return config, inputs_dict





@require_tf
class   lowerCamelCase				(_snake_case			,  _snake_case			,  unittest.TestCase      ):







		'''simple docstring'''



		_snake_case   :   Optional[Any]							=  (TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else ()
		_snake_case   :   Dict							=  (TFXGLMForCausalLM,) if is_tf_available() else ()
		_snake_case   :   Optional[Any]							=  (
		    {'''feature-extraction''': TFXGLMModel, '''text-generation''': TFXGLMForCausalLM} if is_tf_available() else {}
		)
		_snake_case   :   Optional[int]							=  False
		_snake_case   :   List[Any]							=  False
		_snake_case   :   Union[str, Any]							=  False



		def  __UpperCAmelCase      (							self       )     ->							Tuple:
							UpperCAmelCase_   :				Optional[Any]						=						TFXGLMModelTester(self       )
							UpperCAmelCase_   :				List[Any]						=						ConfigTester(self    ,		config_class=_UpperCamelCase    ,		n_embd=3_7       )



		def  __UpperCAmelCase      (							self       )     ->							List[str]:
							self.config_tester.run_common_tests()



		@slow
		def  __UpperCAmelCase      (							self       )     ->							Union[str, Any]:
							for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
												UpperCAmelCase_   :				Any						=						TFXGLMModel.from_pretrained(_UpperCamelCase       )
												self.assertIsNotNone(_UpperCamelCase       )



		@unittest.skip(reason='Currently, model embeddings are going to undergo a major refactor.'       )
		def  __UpperCAmelCase      (							self       )     ->							Optional[Any]:
							super().test_resize_token_embeddings()





@require_tf
class   lowerCamelCase				(unittest.TestCase      ):







		'''simple docstring'''



		@slow
		def  __UpperCAmelCase      (							self    ,		_UpperCamelCase=True       )     ->							int:
							UpperCAmelCase_   :				Tuple						=						TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M'       )
							UpperCAmelCase_   :				Any						=						tf.convert_to_tensor([[2, 2_6_8, 9_8_6_5]]    ,		dtype=tf.intaa       )  # The dog
							# </s> The dog is a very friendly dog. He is very affectionate and loves to play with other
							# fmt: off
							UpperCAmelCase_   :				int						=						[2, 2_6_8, 9_8_6_5, 6_7, 1_1, 1_9_8_8, 5_7_2_5_2, 9_8_6_5, 5, 9_8_4, 6_7, 1_9_8_8, 2_1_3_8_3_8, 1_6_5_8, 5_3, 7_0_4_4_6, 3_3, 6_6_5_7, 2_7_8, 1_5_8_1]
							# fmt: on
							UpperCAmelCase_   :				Union[str, Any]						=						model.generate(_UpperCamelCase    ,		do_sample=_UpperCamelCase    ,		num_beams=1       )
							if verify_outputs:
												self.assertListEqual(output_ids[0].numpy().tolist()    ,		_UpperCamelCase       )



		@slow
		def  __UpperCAmelCase      (							self       )     ->							Optional[Any]:
							UpperCAmelCase_   :				Tuple						=						XGLMTokenizer.from_pretrained('facebook/xglm-564M'       )
							UpperCAmelCase_   :				Tuple						=						TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M'       )

							tf.random.set_seed(0       )
							UpperCAmelCase_   :				str						=						tokenizer('Today is a nice day and'    ,		return_tensors='tf'       )
							UpperCAmelCase_   :				int						=						tokenized.input_ids
							# forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices)
							with tf.device(':/CPU:0'       ):
												UpperCAmelCase_   :				str						=						model.generate(_UpperCamelCase    ,		do_sample=_UpperCamelCase    ,		seed=[7, 0]       )
							UpperCAmelCase_   :				Any						=						tokenizer.decode(output_ids[0]    ,		skip_special_tokens=_UpperCamelCase       )

							UpperCAmelCase_   :				Tuple						=						(
							    'Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due'
							)
							self.assertEqual(_UpperCamelCase    ,		_UpperCamelCase       )



		@slow
		def  __UpperCAmelCase      (							self       )     ->							int:
							UpperCAmelCase_   :				List[str]						=						TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M'       )
							UpperCAmelCase_   :				Tuple						=						XGLMTokenizer.from_pretrained('facebook/xglm-564M'       )

							UpperCAmelCase_   :				Optional[Any]						=						'left'

							# use different length sentences to test batching
							UpperCAmelCase_   :				List[Any]						=						[
							    'This is an extremelly long sentence that only exists to test the ability of the model to cope with '
							    'left-padding, such as in batched generation. The output for the sequence below should be the same '
							    'regardless of whether left padding is applied or not. When',
							    'Hello, my dog is a little',
							]

							UpperCAmelCase_   :				Optional[int]						=						tokenizer(_UpperCamelCase    ,		return_tensors='tf'    ,		padding=_UpperCamelCase       )
							UpperCAmelCase_   :				Optional[int]						=						inputs['input_ids']

							UpperCAmelCase_   :				int						=						model.generate(input_ids=_UpperCamelCase    ,		attention_mask=inputs['attention_mask']    ,		max_new_tokens=1_2       )

							UpperCAmelCase_   :				int						=						tokenizer(sentences[0]    ,		return_tensors='tf'       ).input_ids
							UpperCAmelCase_   :				int						=						model.generate(input_ids=_UpperCamelCase    ,		max_new_tokens=1_2       )

							UpperCAmelCase_   :				Any						=						tokenizer(sentences[1]    ,		return_tensors='tf'       ).input_ids
							UpperCAmelCase_   :				Dict						=						model.generate(input_ids=_UpperCamelCase    ,		max_new_tokens=1_2       )

							UpperCAmelCase_   :				Union[str, Any]						=						tokenizer.batch_decode(_UpperCamelCase    ,		skip_special_tokens=_UpperCamelCase       )
							UpperCAmelCase_   :				str						=						tokenizer.decode(output_non_padded[0]    ,		skip_special_tokens=_UpperCamelCase       )
							UpperCAmelCase_   :				int						=						tokenizer.decode(output_padded[0]    ,		skip_special_tokens=_UpperCamelCase       )

							UpperCAmelCase_   :				str						=						[
							    'This is an extremelly long sentence that only exists to test the ability of the model to cope with '
							    'left-padding, such as in batched generation. The output for the sequence below should be the same '
							    'regardless of whether left padding is applied or not. When left padding is applied, the sequence will be '
							    'a single',
							    'Hello, my dog is a little bit of a shy one, but he is very friendly',
							]
							self.assertListEqual(_UpperCamelCase    ,		_UpperCamelCase       )
							self.assertListEqual(_UpperCamelCase    ,		[non_padded_sentence, padded_sentence]       )














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   lowerCamelCase				(_snake_case			,  _snake_case      ):







		'''simple docstring'''



		@register_to_config
		def __init__(							self    ,		_UpperCamelCase    ,		_UpperCamelCase = None    ,		_UpperCamelCase = None       )     ->							int:
							super().__init__()

							UpperCAmelCase_   :				str						=						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"

												UpperCAmelCase_   :				Optional[Any]						=						torch.zeros(_UpperCamelCase    ,		_UpperCamelCase       )
							else:
												UpperCAmelCase_   :				Any						=						None

							UpperCAmelCase_   :				Any						=						torch.nn.Parameter(_UpperCamelCase       )





class   lowerCamelCase				(_snake_case      ):







		'''simple docstring'''



		_snake_case   :   VQModel
		_snake_case   :   CLIPTextModel
		_snake_case   :   CLIPTokenizer
		_snake_case   :   TransformeraDModel
		_snake_case   :   LearnedClassifierFreeSamplingEmbeddings
		_snake_case   :   VQDiffusionScheduler



		def __init__(							self    ,		_UpperCamelCase    ,		_UpperCamelCase    ,		_UpperCamelCase    ,		_UpperCamelCase    ,		_UpperCamelCase    ,		_UpperCamelCase    ,		)     ->							List[Any]:
							super().__init__()

							self.register_modules(
							    vqvae=_UpperCamelCase    ,		transformer=_UpperCamelCase    ,		text_encoder=_UpperCamelCase    ,		tokenizer=_UpperCamelCase    ,		scheduler=_UpperCamelCase    ,		learned_classifier_free_sampling_embeddings=_UpperCamelCase    ,		)



		def  __UpperCAmelCase      (							self    ,		_UpperCamelCase    ,		_UpperCamelCase    ,		_UpperCamelCase       )     ->							List[str]:
							UpperCAmelCase_   :				Union[str, Any]						=						len(_UpperCamelCase       ) if isinstance(_UpperCamelCase    ,		_UpperCamelCase       ) else 1

							# get prompt text embeddings
							UpperCAmelCase_   :				str						=						self.tokenizer(
							    _UpperCamelCase    ,		padding='max_length'    ,		max_length=self.tokenizer.model_max_length    ,		return_tensors='pt'    ,		)
							UpperCAmelCase_   :				Optional[Any]						=						text_inputs.input_ids

							if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
												UpperCAmelCase_   :				List[Any]						=						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}"       )
												UpperCAmelCase_   :				str						=						text_input_ids[:, : self.tokenizer.model_max_length]
							UpperCAmelCase_   :				str						=						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
							UpperCAmelCase_   :				Dict						=						prompt_embeds / prompt_embeds.norm(dim=-1    ,		keepdim=_UpperCamelCase       )

							# duplicate text embeddings for each generation per prompt
							UpperCAmelCase_   :				Dict						=						prompt_embeds.repeat_interleave(_UpperCamelCase    ,		dim=0       )

							if do_classifier_free_guidance:
												if self.learned_classifier_free_sampling_embeddings.learnable:
																	UpperCAmelCase_   :				List[str]						=						self.learned_classifier_free_sampling_embeddings.embeddings
																	UpperCAmelCase_   :				List[str]						=						negative_prompt_embeds.unsqueeze(0       ).repeat(_UpperCamelCase    ,		1    ,		1       )
												else:
																	UpperCAmelCase_   :				List[Any]						=						[''] * batch_size

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

												# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
												UpperCAmelCase_   :				List[Any]						=						negative_prompt_embeds.shape[1]
												UpperCAmelCase_   :				Dict						=						negative_prompt_embeds.repeat(1    ,		_UpperCamelCase    ,		1       )
												UpperCAmelCase_   :				Any						=						negative_prompt_embeds.view(batch_size * num_images_per_prompt    ,		_UpperCamelCase    ,		-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
												UpperCAmelCase_   :				Union[str, Any]						=						torch.cat([negative_prompt_embeds, prompt_embeds]       )

							return prompt_embeds



		@torch.no_grad()
		def __call__(							self    ,		_UpperCamelCase    ,		_UpperCamelCase = 1_0_0    ,		_UpperCamelCase = 5.0    ,		_UpperCamelCase = 1.0    ,		_UpperCamelCase = 1    ,		_UpperCamelCase = None    ,		_UpperCamelCase = None    ,		_UpperCamelCase = "pil"    ,		_UpperCamelCase = True    ,		_UpperCamelCase = None    ,		_UpperCamelCase = 1    ,		)     ->							Union[ImagePipelineOutput, Tuple]:
							if isinstance(_UpperCamelCase    ,		_UpperCamelCase       ):
												UpperCAmelCase_   :				Any						=						1
							elif isinstance(_UpperCamelCase    ,		_UpperCamelCase       ):
												UpperCAmelCase_   :				Tuple						=						len(_UpperCamelCase       )
							else:
												raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(_UpperCamelCase       )}"       )

							UpperCAmelCase_   :				Union[str, Any]						=						batch_size * num_images_per_prompt

							UpperCAmelCase_   :				Optional[int]						=						guidance_scale > 1.0

							UpperCAmelCase_   :				Any						=						self._encode_prompt(_UpperCamelCase    ,		_UpperCamelCase    ,		_UpperCamelCase       )

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

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

							UpperCAmelCase_   :				Optional[int]						=						(batch_size, self.transformer.num_latent_pixels)
							if latents is None:
												UpperCAmelCase_   :				Tuple						=						self.transformer.num_vector_embeds - 1
												UpperCAmelCase_   :				List[Any]						=						torch.full(_UpperCamelCase    ,		_UpperCamelCase       ).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)."       )
												UpperCAmelCase_   :				Any						=						latents.to(self.device       )

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

							UpperCAmelCase_   :				List[str]						=						self.scheduler.timesteps.to(self.device       )

							UpperCAmelCase_   :				Union[str, Any]						=						latents

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

												# predict the un-noised image
												# model_output == `log_p_x_0`
												UpperCAmelCase_   :				Dict						=						self.transformer(_UpperCamelCase    ,		encoder_hidden_states=_UpperCamelCase    ,		timestep=_UpperCamelCase       ).sample

												if do_classifier_free_guidance:
																	UpperCAmelCase_	,  UpperCAmelCase_   :				Optional[Any]						=						model_output.chunk(2       )
																	UpperCAmelCase_   :				Optional[int]						=						model_output_uncond + guidance_scale * (model_output_text - model_output_uncond)
																	model_output -= torch.logsumexp(_UpperCamelCase    ,		dim=1    ,		keepdim=_UpperCamelCase       )

												UpperCAmelCase_   :				str						=						self.truncate(_UpperCamelCase    ,		_UpperCamelCase       )

												# remove `log(0)`'s (`-inf`s)
												UpperCAmelCase_   :				Optional[int]						=						model_output.clamp(-7_0       )

												# compute the previous noisy sample x_t -> x_t-1
												UpperCAmelCase_   :				Union[str, Any]						=						self.scheduler.step(_UpperCamelCase    ,		timestep=_UpperCamelCase    ,		sample=_UpperCamelCase    ,		generator=_UpperCamelCase       ).prev_sample

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

							UpperCAmelCase_   :				str						=						self.vqvae.config.vq_embed_dim
							UpperCAmelCase_   :				Optional[int]						=						(batch_size, self.transformer.height, self.transformer.width, embedding_channels)
							UpperCAmelCase_   :				int						=						self.vqvae.quantize.get_codebook_entry(_UpperCamelCase    ,		shape=_UpperCamelCase       )
							UpperCAmelCase_   :				Dict						=						self.vqvae.decode(_UpperCamelCase    ,		force_not_quantize=_UpperCamelCase       ).sample

							UpperCAmelCase_   :				List[str]						=						(image / 2 + 0.5).clamp(0    ,		1       )
							UpperCAmelCase_   :				Any						=						image.cpu().permute(0    ,		2    ,		3    ,		1       ).numpy()

							if output_type == "pil":
												UpperCAmelCase_   :				int						=						self.numpy_to_pil(_UpperCamelCase       )

							if not return_dict:
												return (image,)

							return ImagePipelineOutput(images=_UpperCamelCase       )



		def  __UpperCAmelCase      (							self    ,		_UpperCamelCase    ,		_UpperCamelCase       )     ->							torch.FloatTensor:
							UpperCAmelCase_	,  UpperCAmelCase_   :				int						=						torch.sort(_UpperCamelCase    ,		1    ,		descending=_UpperCamelCase       )
							UpperCAmelCase_   :				Dict						=						torch.exp(_UpperCamelCase       )
							UpperCAmelCase_   :				int						=						sorted_p_x_0.cumsum(dim=1       ) < truncation_rate

							# Ensure that at least the largest probability is not zeroed out
							UpperCAmelCase_   :				Tuple						=						torch.full_like(keep_mask[:, 0:1, :]    ,		_UpperCamelCase       )
							UpperCAmelCase_   :				List[str]						=						torch.cat((all_true, keep_mask)    ,		dim=1       )
							UpperCAmelCase_   :				int						=						keep_mask[:, :-1, :]

							UpperCAmelCase_   :				Any						=						keep_mask.gather(1    ,		indices.argsort(1       )       )

							UpperCAmelCase_   :				str						=						log_p_x_0.clone()

							UpperCAmelCase_   :				Any						=						-torch.inf  # -inf = log(0)

							return rv






