'''simple docstring'''





import logging
import sys
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Union

import librosa
import torch
from datasets import DatasetDict, load_dataset
from packaging import version
from torch import nn

from transformers import (
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    WavaVecaConfig,
    WavaVecaFeatureExtractor,
    WavaVecaForPreTraining,
    is_apex_available,
    trainer_utils,
)
from transformers.models.wavaveca.modeling_wavaveca import _compute_mask_indices


if is_apex_available():
			from apex import amp

if version.parse(version.parse(torch.__version__).base_version) >= version.parse("""1.6"""):
			lowerCAmelCase_	:		Optional[int]			=     True
			from torch.cuda.amp import autocast


lowerCAmelCase_	:		List[Any]			=     logging.getLogger(__name__)




@dataclass
class 		SCREAMING_SNAKE_CASE     :







					'''simple docstring'''
					UpperCAmelCase__							=							field(
					    metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''}	)
					UpperCAmelCase__							=							field(
					    default=__UpperCAmelCase   , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''}   , )
					UpperCAmelCase__							=							field(
					    default=__UpperCAmelCase   , metadata={'''help''': '''Whether to freeze the feature extractor layers of the model.'''}	)
					UpperCAmelCase__							=							field(
					    default=__UpperCAmelCase   , metadata={'''help''': '''Whether to log verbose messages or not.'''}   , )
					UpperCAmelCase__							=							field(
					    default=2.0   , metadata={'''help''': '''Maximum temperature for gumbel softmax.'''}	)
					UpperCAmelCase__							=							field(
					    default=0.5   , metadata={'''help''': '''Minimum temperature for gumbel softmax.'''}	)
					UpperCAmelCase__							=							field(
					    default=0.999_995   , metadata={'''help''': '''Decay of gumbel temperature during training.'''}	)





def 						__A							(     UpperCAmelCase     ,UpperCAmelCase					)     ->			Optional[Any]:




						'''simple docstring'''
						logging.basicConfig(
						    format="%(asctime)s - %(levelname)s - %(name)s - %(message)s"     ,datefmt="%m/%d/%Y %H:%M:%S"     ,handlers=[logging.StreamHandler(sys.stdout					)]     ,)
						_UpperCamelCase			:			int   			=						logging.WARNING
						if model_args.verbose_logging:
												_UpperCamelCase			:			Optional[Any]   			=						logging.DEBUG
						elif trainer_utils.is_main_process(training_args.local_rank					):
												_UpperCamelCase			:			Union[str, Any]   			=						logging.INFO
						logger.setLevel(_snake_case					)




@dataclass
class 		SCREAMING_SNAKE_CASE     :







					'''simple docstring'''
					UpperCAmelCase__							=							field(
					    default=__UpperCAmelCase   , metadata={'''help''': '''The name of the dataset to use (via the datasets library).'''}	)
					UpperCAmelCase__							=							field(
					    default=__UpperCAmelCase   , metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''}	)
					UpperCAmelCase__							=							field(
					    default='''train'''   , metadata={
					        '''help''': '''The name of the training data set split to use (via the datasets library). Defaults to \'train\''''
					    }   , )
					UpperCAmelCase__							=							field(
					    default='''validation'''   , metadata={
					        '''help''': (
					            '''The name of the validation data set split to use (via the datasets library). Defaults to \'validation\''''
					        )
					    }   , )
					UpperCAmelCase__							=							field(
					    default='''file'''   , metadata={'''help''': '''Column in the dataset that contains speech file path. Defaults to \'file\''''}   , )
					UpperCAmelCase__							=							field(
					    default=__UpperCAmelCase   , metadata={'''help''': '''Overwrite the cached preprocessed datasets or not.'''}	)
					UpperCAmelCase__							=							field(
					    default=1   , metadata={
					        '''help''': '''The percentage of the train set used as validation set in case there\'s no validation split'''
					    }   , )
					UpperCAmelCase__							=							field(
					    default=__UpperCAmelCase   , metadata={'''help''': '''The number of processes to use for the preprocessing.'''}   , )
					UpperCAmelCase__							=							field(
					    default=20.0   , metadata={'''help''': '''Filter audio files that are longer than `max_duration_in_seconds` seconds'''}	)





@dataclass
class 		SCREAMING_SNAKE_CASE     :







					'''simple docstring'''
					UpperCAmelCase__							=							42
					UpperCAmelCase__							=							42
					UpperCAmelCase__							=							"longest"
					UpperCAmelCase__							=							None
					UpperCAmelCase__							=							None





					def __call__(						self					:						Union[str, Any]       ,		lowercase__					:						int					)							->Dict:


											'''simple docstring'''




											_UpperCamelCase			:			Optional[Any]   			=						self.feature_extractor.pad(
											    UpperCAmelCase_       ,		max_length=self.max_length       ,		padding=self.padding       ,		pad_to_multiple_of=self.pad_to_multiple_of       ,		return_tensors="pt"       ,		)
											_UpperCamelCase			:			Dict   			=						self.model._get_feat_extract_output_lengths(batch["input_values"].shape[-1]					)

											_UpperCamelCase			:			Tuple   			=						batch["input_values"].shape[0]

											# make sure that no loss is computed on padded inputs
											if batch["attention_mask"] is not None:
																	# compute real output lengths according to convolution formula
																	_UpperCamelCase			:			List[Any]   			=						self.model._get_feat_extract_output_lengths(batch["attention_mask"].sum(-1					)					).to(
																	    torch.long					)

																	_UpperCamelCase			:			Optional[Any]   			=						torch.zeros(
																	    (batch_size, mask_indices_seq_length)       ,		dtype=torch.long       ,		device=batch["input_values"].device					)

																	# these two operations makes sure that all values
																	# before the output lengths indices are attended to
																	_UpperCamelCase			:			str   			=						1
																	_UpperCamelCase			:			int   			=						attention_mask.flip([-1]					).cumsum(-1					).flip([-1]					).bool()

											# sample randomly masked indices
											_UpperCamelCase			:			str   			=						_compute_mask_indices(
											    (batch_size, mask_indices_seq_length)       ,		self.model.config.mask_time_prob       ,		self.model.config.mask_time_length       ,		attention_mask=UpperCAmelCase_       ,		min_masks=2       ,		)

											return batch





class 		SCREAMING_SNAKE_CASE     (					__UpperCAmelCase	):







					'''simple docstring'''





					def __init__(						self					:						List[str]       ,		*lowercase__					:						List[Any]       ,		lowercase__					:						List[str]=1       ,		lowercase__					:						Dict=0       ,		lowercase__					:						Tuple=1.0       ,		**lowercase__					:						List[str]					)							->Optional[Any]:


											'''simple docstring'''




											super().__init__(*UpperCAmelCase_       ,		**UpperCAmelCase_					)
											_UpperCamelCase			:			List[Any]   			=						0
											_UpperCamelCase			:			Tuple   			=						max_gumbel_temp
											_UpperCamelCase			:			Optional[int]   			=						min_gumbel_temp
											_UpperCamelCase			:			Union[str, Any]   			=						gumbel_temp_decay







					def  snake_case__				(						self					:						List[str]       ,		lowercase__					:						Any       ,		lowercase__					:						List[Any]					)							->Optional[Any]:


											'''simple docstring'''




											model.train()
											_UpperCamelCase			:			Optional[int]   			=						self._prepare_inputs(UpperCAmelCase_					)

											if self.use_amp:
																	with autocast():
																							_UpperCamelCase			:			List[Any]   			=						self.compute_loss(UpperCAmelCase_       ,		UpperCAmelCase_					)
											else:
																	_UpperCamelCase			:			Union[str, Any]   			=						self.compute_loss(UpperCAmelCase_       ,		UpperCAmelCase_					)

											if self.args.n_gpu > 1 or self.deepspeed:
																	if model.module.config.ctc_loss_reduction == "mean":
																							_UpperCamelCase			:			List[str]   			=						loss.mean()
																	elif model.module.config.ctc_loss_reduction == "sum":
																							_UpperCamelCase			:			Tuple   			=						loss.sum() / (inputs["mask_time_indices"]).sum()
																	else:
																							raise ValueError(f'''{model.config.ctc_loss_reduction} is not valid. Choose one of [\'mean\', \'sum\']'''					)

											if self.args.gradient_accumulation_steps > 1:
																	_UpperCamelCase			:			List[str]   			=						loss / self.args.gradient_accumulation_steps

											if self.use_amp:
																	self.scaler.scale(UpperCAmelCase_					).backward()
											elif self.use_apex:
																	with amp.scale_loss(UpperCAmelCase_       ,		self.optimizer					) as scaled_loss:
																							scaled_loss.backward()
											elif self.deepspeed:
																	self.deepspeed.backward(UpperCAmelCase_					)
											else:
																	loss.backward()

											self.num_update_step += 1
											# make sure gumbel softmax temperature is decayed
											if self.args.n_gpu > 1 or self.deepspeed:
																	model.module.set_gumbel_temperature(
																	    max(self.max_gumbel_temp * self.gumbel_temp_decay**self.num_update_step       ,		self.min_gumbel_temp					)					)
											else:
																	model.set_gumbel_temperature(
																	    max(self.max_gumbel_temp * self.gumbel_temp_decay**self.num_update_step       ,		self.min_gumbel_temp					)					)

											return loss.detach()





def 						__A							(     )     ->			Any:




						'''simple docstring'''
						# See all possible arguments in src/transformers/training_args.py
						# or by passing the --help flag to this script.
						# We now keep distinct sets of args, for a cleaner separation of concerns.

						_UpperCamelCase			:			List[str]   			=						HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)					)

						_UpperCamelCase			,       _UpperCamelCase			,       _UpperCamelCase			:			List[Any]   			=						parser.parse_args_into_dataclasses()
						configure_logger(_snake_case     ,_snake_case					)

						# Downloading and loading a dataset from the hub.
						_UpperCamelCase			:			List[str]   			=						load_dataset(data_args.dataset_name     ,data_args.dataset_config_name     ,cache_dir=model_args.cache_dir					)

						if "validation" not in datasets.keys():
												# make sure only "validation" and "train" keys remain"
												_UpperCamelCase			:			Union[str, Any]   			=						DatasetDict()
												_UpperCamelCase			:			Union[str, Any]   			=						load_dataset(
												    data_args.dataset_name     ,data_args.dataset_config_name     ,split=f'''{data_args.train_split_name}[:{data_args.validation_split_percentage}%]'''     ,cache_dir=model_args.cache_dir     ,)
												_UpperCamelCase			:			List[Any]   			=						load_dataset(
												    data_args.dataset_name     ,data_args.dataset_config_name     ,split=f'''{data_args.train_split_name}[{data_args.validation_split_percentage}%:]'''     ,cache_dir=model_args.cache_dir     ,)
						else:
												# make sure only "validation" and "train" keys remain"
												_UpperCamelCase			:			List[str]   			=						DatasetDict()
												_UpperCamelCase			:			Union[str, Any]   			=						load_dataset(
												    data_args.dataset_name     ,data_args.dataset_config_name     ,split="validation"     ,cache_dir=model_args.cache_dir     ,)
												_UpperCamelCase			:			str   			=						load_dataset(
												    data_args.dataset_name     ,data_args.dataset_config_name     ,split=f'''{data_args.train_split_name}'''     ,cache_dir=model_args.cache_dir     ,)

						# only normalized-inputs-training is supported
						_UpperCamelCase			:			Tuple   			=						WavaVecaFeatureExtractor.from_pretrained(
						    model_args.model_name_or_path     ,cache_dir=model_args.cache_dir     ,do_normalize=_snake_case					)

						def prepare_dataset(UpperCAmelCase					):
												# check that all files have the correct sampling rate
												_UpperCamelCase			,       _UpperCamelCase			:			List[str]   			=						librosa.load(batch[data_args.speech_file_column]     ,sr=feature_extractor.sampling_rate					)
												return batch

						# load audio files into numpy arrays
						_UpperCamelCase			:			Dict   			=						datasets.map(
						    _snake_case     ,num_proc=data_args.preprocessing_num_workers     ,remove_columns=datasets["train"].column_names					)

						# filter audio files that are too long
						_UpperCamelCase			:			Tuple   			=						vectorized_datasets.filter(
						    lambda UpperCAmelCase					: len(data["speech"]					) < int(data_args.max_duration_in_seconds * feature_extractor.sampling_rate					)					)

						def normalize(UpperCAmelCase					):
												return feature_extractor(batch["speech"]     ,sampling_rate=feature_extractor.sampling_rate					)

						# normalize and transform to `BatchFeatures`
						_UpperCamelCase			:			Union[str, Any]   			=						vectorized_datasets.map(
						    _snake_case     ,batched=_snake_case     ,num_proc=data_args.preprocessing_num_workers     ,load_from_cache_file=not data_args.overwrite_cache     ,remove_columns=vectorized_datasets["train"].column_names     ,)

						# pretraining is only supported for "newer" stable layer norm architecture
						# apply_spec_augment has to be True, mask_feature_prob has to be 0.0
						_UpperCamelCase			:			Optional[Any]   			=						WavaVecaConfig.from_pretrained(
						    model_args.model_name_or_path     ,cache_dir=model_args.cache_dir     ,gradient_checkpointing=training_args.gradient_checkpointing     ,)

						if not config.do_stable_layer_norm or config.feat_extract_norm != "layer":
												raise ValueError(
												    "PreTraining is only supported for ``config.do_stable_layer_norm=True`` and"
												    " ``config.feat_extract_norm=\'layer\'"					)

						_UpperCamelCase			:			Union[str, Any]   			=						WavaVecaForPreTraining(_snake_case					)

						_UpperCamelCase			:			List[str]   			=						DataCollatorForWavaVecaPretraining(model=_snake_case     ,feature_extractor=_snake_case					)

						_UpperCamelCase			:			int   			=						WavaVecaPreTrainer(
						    model=_snake_case     ,data_collator=_snake_case     ,args=_snake_case     ,train_dataset=vectorized_datasets["train"]     ,eval_dataset=vectorized_datasets["validation"]     ,tokenizer=_snake_case     ,max_gumbel_temp=model_args.max_gumbel_temperature     ,min_gumbel_temp=model_args.min_gumbel_temperature     ,gumbel_temp_decay=model_args.gumbel_temperature_decay     ,)
						trainer.train()


if __name__ == "__main__":
			main()



'''simple docstring'''





from dataclasses import dataclass
from typing import Optional

import numpy as np
import torch
import torch.nn as nn

from ..utils import BaseOutput, is_torch_version, randn_tensor
from .attention_processor import SpatialNorm
from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block




@dataclass
class 		SCREAMING_SNAKE_CASE     (					SCREAMING_SNAKE_CASE	):







				'''simple docstring'''
				UpperCAmelCase__							=							42





class 		SCREAMING_SNAKE_CASE     (					nn.Module	):







				'''simple docstring'''





				def __init__(						self					:						Optional[Any]       ,		lowercase__					:						List[str]=3       ,		lowercase__					:						Tuple=3       ,		lowercase__					:						List[str]=("DownEncoderBlock2D",)       ,		lowercase__					:						Optional[int]=(64,)       ,		lowercase__					:						List[Any]=2       ,		lowercase__					:						int=32       ,		lowercase__					:						Optional[int]="silu"       ,		lowercase__					:						List[Any]=True       ,		)							->Optional[Any]:


										'''simple docstring'''




										super().__init__()
										_UpperCamelCase			:			Union[str, Any]   			=						layers_per_block

										_UpperCamelCase			:			Union[str, Any]   			=						torch.nn.Convad(
										    lowercase__       ,		block_out_channels[0]       ,		kernel_size=3       ,		stride=1       ,		padding=1       ,		)

										_UpperCamelCase			:			int   			=						None
										_UpperCamelCase			:			Optional[Any]   			=						nn.ModuleList([]					)

										# down
										_UpperCamelCase			:			Optional[int]   			=						block_out_channels[0]
										for i, down_block_type in enumerate(lowercase__					):
																_UpperCamelCase			:			int   			=						output_channel
																_UpperCamelCase			:			int   			=						block_out_channels[i]
																_UpperCamelCase			:			Tuple   			=						i == len(lowercase__					) - 1

																_UpperCamelCase			:			List[Any]   			=						get_down_block(
																    lowercase__       ,		num_layers=self.layers_per_block       ,		in_channels=lowercase__       ,		out_channels=lowercase__       ,		add_downsample=not is_final_block       ,		resnet_eps=1e-6       ,		downsample_padding=0       ,		resnet_act_fn=lowercase__       ,		resnet_groups=lowercase__       ,		attention_head_dim=lowercase__       ,		temb_channels=lowercase__       ,		)
																self.down_blocks.append(lowercase__					)

										# mid
										_UpperCamelCase			:			Dict   			=						UNetMidBlockaD(
										    in_channels=block_out_channels[-1]       ,		resnet_eps=1e-6       ,		resnet_act_fn=lowercase__       ,		output_scale_factor=1       ,		resnet_time_scale_shift="default"       ,		attention_head_dim=block_out_channels[-1]       ,		resnet_groups=lowercase__       ,		temb_channels=lowercase__       ,		)

										# out
										_UpperCamelCase			:			List[str]   			=						nn.GroupNorm(num_channels=block_out_channels[-1]       ,		num_groups=lowercase__       ,		eps=1e-6					)
										_UpperCamelCase			:			Union[str, Any]   			=						nn.SiLU()

										_UpperCamelCase			:			Tuple   			=						2 * out_channels if double_z else out_channels
										_UpperCamelCase			:			List[Any]   			=						nn.Convad(block_out_channels[-1]       ,		lowercase__       ,		3       ,		padding=1					)

										_UpperCamelCase			:			Tuple   			=						False







				def  snake_case__				(						self					:						str       ,		lowercase__					:						Any					)							->Any:


										'''simple docstring'''




										_UpperCamelCase			:			Dict   			=						x
										_UpperCamelCase			:			str   			=						self.conv_in(lowercase__					)

										if self.training and self.gradient_checkpointing:

																def create_custom_forward(lowercase__					:						Any					):
																						def custom_forward(*lowercase__					:						List[Any]					):
																												return module(*lowercase__					)

																						return custom_forward

																# down
																if is_torch_version(">="       ,		"1.11.0"					):
																						for down_block in self.down_blocks:
																												_UpperCamelCase			:			Optional[Any]   			=						torch.utils.checkpoint.checkpoint(
																												    create_custom_forward(lowercase__					)       ,		lowercase__       ,		use_reentrant=lowercase__					)
																						# middle
																						_UpperCamelCase			:			List[Any]   			=						torch.utils.checkpoint.checkpoint(
																						    create_custom_forward(self.mid_block					)       ,		lowercase__       ,		use_reentrant=lowercase__					)
																else:
																						for down_block in self.down_blocks:
																												_UpperCamelCase			:			List[str]   			=						torch.utils.checkpoint.checkpoint(create_custom_forward(lowercase__					)       ,		lowercase__					)
																						# middle
																						_UpperCamelCase			:			Union[str, Any]   			=						torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block					)       ,		lowercase__					)

										else:
																# down
																for down_block in self.down_blocks:
																						_UpperCamelCase			:			Tuple   			=						down_block(lowercase__					)

																# middle
																_UpperCamelCase			:			Optional[int]   			=						self.mid_block(lowercase__					)

										# post-process
										_UpperCamelCase			:			List[Any]   			=						self.conv_norm_out(lowercase__					)
										_UpperCamelCase			:			Tuple   			=						self.conv_act(lowercase__					)
										_UpperCamelCase			:			int   			=						self.conv_out(lowercase__					)

										return sample





class 		SCREAMING_SNAKE_CASE     (					nn.Module	):







				'''simple docstring'''





				def __init__(						self					:						Dict       ,		lowercase__					:						str=3       ,		lowercase__					:						List[Any]=3       ,		lowercase__					:						Optional[int]=("UpDecoderBlock2D",)       ,		lowercase__					:						Any=(64,)       ,		lowercase__					:						str=2       ,		lowercase__					:						List[Any]=32       ,		lowercase__					:						Optional[int]="silu"       ,		lowercase__					:						List[str]="group"       ,		)							->Any:


										'''simple docstring'''




										super().__init__()
										_UpperCamelCase			:			List[Any]   			=						layers_per_block

										_UpperCamelCase			:			Any   			=						nn.Convad(
										    lowercase__       ,		block_out_channels[-1]       ,		kernel_size=3       ,		stride=1       ,		padding=1       ,		)

										_UpperCamelCase			:			List[str]   			=						None
										_UpperCamelCase			:			Dict   			=						nn.ModuleList([]					)

										_UpperCamelCase			:			Optional[int]   			=						in_channels if norm_type == "spatial" else None

										# mid
										_UpperCamelCase			:			int   			=						UNetMidBlockaD(
										    in_channels=block_out_channels[-1]       ,		resnet_eps=1e-6       ,		resnet_act_fn=lowercase__       ,		output_scale_factor=1       ,		resnet_time_scale_shift="default" if norm_type == "group" else norm_type       ,		attention_head_dim=block_out_channels[-1]       ,		resnet_groups=lowercase__       ,		temb_channels=lowercase__       ,		)

										# up
										_UpperCamelCase			:			Dict   			=						list(reversed(lowercase__					)					)
										_UpperCamelCase			:			Tuple   			=						reversed_block_out_channels[0]
										for i, up_block_type in enumerate(lowercase__					):
																_UpperCamelCase			:			Union[str, Any]   			=						output_channel
																_UpperCamelCase			:			Dict   			=						reversed_block_out_channels[i]

																_UpperCamelCase			:			List[str]   			=						i == len(lowercase__					) - 1

																_UpperCamelCase			:			Tuple   			=						get_up_block(
																    lowercase__       ,		num_layers=self.layers_per_block + 1       ,		in_channels=lowercase__       ,		out_channels=lowercase__       ,		prev_output_channel=lowercase__       ,		add_upsample=not is_final_block       ,		resnet_eps=1e-6       ,		resnet_act_fn=lowercase__       ,		resnet_groups=lowercase__       ,		attention_head_dim=lowercase__       ,		temb_channels=lowercase__       ,		resnet_time_scale_shift=lowercase__       ,		)
																self.up_blocks.append(lowercase__					)
																_UpperCamelCase			:			Any   			=						output_channel

										# out
										if norm_type == "spatial":
																_UpperCamelCase			:			Any   			=						SpatialNorm(block_out_channels[0]       ,		lowercase__					)
										else:
																_UpperCamelCase			:			int   			=						nn.GroupNorm(num_channels=block_out_channels[0]       ,		num_groups=lowercase__       ,		eps=1e-6					)
										_UpperCamelCase			:			Tuple   			=						nn.SiLU()
										_UpperCamelCase			:			Tuple   			=						nn.Convad(block_out_channels[0]       ,		lowercase__       ,		3       ,		padding=1					)

										_UpperCamelCase			:			Optional[Any]   			=						False







				def  snake_case__				(						self					:						Tuple       ,		lowercase__					:						Union[str, Any]       ,		lowercase__					:						Optional[Any]=None					)							->Union[str, Any]:


										'''simple docstring'''




										_UpperCamelCase			:			str   			=						z
										_UpperCamelCase			:			str   			=						self.conv_in(lowercase__					)

										_UpperCamelCase			:			Any   			=						next(iter(self.up_blocks.parameters()					)					).dtype
										if self.training and self.gradient_checkpointing:

																def create_custom_forward(lowercase__					:						Optional[int]					):
																						def custom_forward(*lowercase__					:						List[str]					):
																												return module(*lowercase__					)

																						return custom_forward

																if is_torch_version(">="       ,		"1.11.0"					):
																						# middle
																						_UpperCamelCase			:			Dict   			=						torch.utils.checkpoint.checkpoint(
																						    create_custom_forward(self.mid_block					)       ,		lowercase__       ,		lowercase__       ,		use_reentrant=lowercase__					)
																						_UpperCamelCase			:			Union[str, Any]   			=						sample.to(lowercase__					)

																						# up
																						for up_block in self.up_blocks:
																												_UpperCamelCase			:			Dict   			=						torch.utils.checkpoint.checkpoint(
																												    create_custom_forward(lowercase__					)       ,		lowercase__       ,		lowercase__       ,		use_reentrant=lowercase__					)
																else:
																						# middle
																						_UpperCamelCase			:			Any   			=						torch.utils.checkpoint.checkpoint(
																						    create_custom_forward(self.mid_block					)       ,		lowercase__       ,		lowercase__					)
																						_UpperCamelCase			:			int   			=						sample.to(lowercase__					)

																						# up
																						for up_block in self.up_blocks:
																												_UpperCamelCase			:			Dict   			=						torch.utils.checkpoint.checkpoint(create_custom_forward(lowercase__					)       ,		lowercase__       ,		lowercase__					)
										else:
																# middle
																_UpperCamelCase			:			str   			=						self.mid_block(lowercase__       ,		lowercase__					)
																_UpperCamelCase			:			int   			=						sample.to(lowercase__					)

																# up
																for up_block in self.up_blocks:
																						_UpperCamelCase			:			str   			=						up_block(lowercase__       ,		lowercase__					)

        # post-process
										if latent_embeds is None:
																_UpperCamelCase			:			Union[str, Any]   			=						self.conv_norm_out(lowercase__					)
										else:
																_UpperCamelCase			:			Any   			=						self.conv_norm_out(lowercase__       ,		lowercase__					)
										_UpperCamelCase			:			List[str]   			=						self.conv_act(lowercase__					)
										_UpperCamelCase			:			Dict   			=						self.conv_out(lowercase__					)

										return sample





class 		SCREAMING_SNAKE_CASE     (					nn.Module	):







				'''simple docstring'''





				def __init__(						self					:						Optional[int]       ,		lowercase__					:						str       ,		lowercase__					:						Tuple       ,		lowercase__					:						Optional[Any]       ,		lowercase__					:						Tuple=None       ,		lowercase__					:						Dict="random"       ,		lowercase__					:						List[Any]=False       ,		lowercase__					:						List[Any]=True					)							->Optional[int]:


										'''simple docstring'''




										super().__init__()
										_UpperCamelCase			:			List[Any]   			=						n_e
										_UpperCamelCase			:			List[str]   			=						vq_embed_dim
										_UpperCamelCase			:			List[str]   			=						beta
										_UpperCamelCase			:			Any   			=						legacy

										_UpperCamelCase			:			Optional[int]   			=						nn.Embedding(self.n_e       ,		self.vq_embed_dim					)
										self.embedding.weight.data.uniform_(-1.0 / self.n_e       ,		1.0 / self.n_e					)

										_UpperCamelCase			:			str   			=						remap
										if self.remap is not None:
																self.register_buffer("used"       ,		torch.tensor(np.load(self.remap					)					)					)
																_UpperCamelCase			:			List[Any]   			=						self.used.shape[0]
																_UpperCamelCase			:			Optional[int]   			=						unknown_index  # "random" or "extra" or integer
																if self.unknown_index == "extra":
																						_UpperCamelCase			:			Any   			=						self.re_embed
																						_UpperCamelCase			:			Any   			=						self.re_embed + 1
																print(
																    f'''Remapping {self.n_e} indices to {self.re_embed} indices. '''
																    f'''Using {self.unknown_index} for unknown indices.'''					)
										else:
																_UpperCamelCase			:			Optional[Any]   			=						n_e

										_UpperCamelCase			:			Optional[Any]   			=						sane_index_shape





				def  snake_case__				(						self					:						str       ,		lowercase__					:						Dict					)							->Optional[int]:


										'''simple docstring'''




										_UpperCamelCase			:			str   			=						inds.shape
										assert len(lowercase__					) > 1
										_UpperCamelCase			:			List[Any]   			=						inds.reshape(ishape[0]       ,		-1					)
										_UpperCamelCase			:			Tuple   			=						self.used.to(lowercase__					)
										_UpperCamelCase			:			List[str]   			=						(inds[:, :, None] == used[None, None, ...]).long()
										_UpperCamelCase			:			Optional[Any]   			=						match.argmax(-1					)
										_UpperCamelCase			:			int   			=						match.sum(2					) < 1
										if self.unknown_index == "random":
																_UpperCamelCase			:			int   			=						torch.randint(0       ,		self.re_embed       ,		size=new[unknown].shape					).to(device=new.device					)
										else:
																_UpperCamelCase			:			Optional[int]   			=						self.unknown_index
										return new.reshape(lowercase__					)





				def  snake_case__				(						self					:						Any       ,		lowercase__					:						Optional[Any]					)							->int:


										'''simple docstring'''




										_UpperCamelCase			:			Tuple   			=						inds.shape
										assert len(lowercase__					) > 1
										_UpperCamelCase			:			Dict   			=						inds.reshape(ishape[0]       ,		-1					)
										_UpperCamelCase			:			Optional[Any]   			=						self.used.to(lowercase__					)
										if self.re_embed > self.used.shape[0]:  # extra token
																_UpperCamelCase			:			int   			=						0  # simply set to zero
										_UpperCamelCase			:			Tuple   			=						torch.gather(used[None, :][inds.shape[0] * [0], :]       ,		1       ,		lowercase__					)
										return back.reshape(lowercase__					)





				def  snake_case__				(						self					:						List[Any]       ,		lowercase__					:						Union[str, Any]					)							->Any:


										'''simple docstring'''




										_UpperCamelCase			:			Any   			=						z.permute(0       ,		2       ,		3       ,		1					).contiguous()
										_UpperCamelCase			:			Optional[Any]   			=						z.view(-1       ,		self.vq_embed_dim					)

										# distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z
										_UpperCamelCase			:			Optional[Any]   			=						torch.argmin(torch.cdist(lowercase__       ,		self.embedding.weight					)       ,		dim=1					)

										_UpperCamelCase			:			List[str]   			=						self.embedding(lowercase__					).view(z.shape					)
										_UpperCamelCase			:			Optional[int]   			=						None
										_UpperCamelCase			:			Tuple   			=						None

										# compute loss for embedding
										if not self.legacy:
																_UpperCamelCase			:			Any   			=						self.beta * torch.mean((z_q.detach() - z) ** 2					) + torch.mean((z_q - z.detach()) ** 2					)
										else:
																_UpperCamelCase			:			str   			=						torch.mean((z_q.detach() - z) ** 2					) + self.beta * torch.mean((z_q - z.detach()) ** 2					)

										# preserve gradients
										_UpperCamelCase			:			List[Any]   			=						z + (z_q - z).detach()

										# reshape back to match original input shape
										_UpperCamelCase			:			List[Any]   			=						z_q.permute(0       ,		3       ,		1       ,		2					).contiguous()

										if self.remap is not None:
																_UpperCamelCase			:			str   			=						min_encoding_indices.reshape(z.shape[0]       ,		-1					)  # add batch axis
																_UpperCamelCase			:			int   			=						self.remap_to_used(lowercase__					)
																_UpperCamelCase			:			List[str]   			=						min_encoding_indices.reshape(-1       ,		1					)  # flatten

										if self.sane_index_shape:
																_UpperCamelCase			:			Tuple   			=						min_encoding_indices.reshape(z_q.shape[0]       ,		z_q.shape[2]       ,		z_q.shape[3]					)

										return z_q, loss, (perplexity, min_encodings, min_encoding_indices)







				def  snake_case__				(						self					:						Optional[Any]       ,		lowercase__					:						List[str]       ,		lowercase__					:						List[str]					)							->Dict:


										'''simple docstring'''




										if self.remap is not None:
																_UpperCamelCase			:			Tuple   			=						indices.reshape(shape[0]       ,		-1					)  # add batch axis
																_UpperCamelCase			:			str   			=						self.unmap_to_all(lowercase__					)
																_UpperCamelCase			:			str   			=						indices.reshape(-1					)  # flatten again

										# get quantized latent vectors
										_UpperCamelCase			:			Dict   			=						self.embedding(lowercase__					)

										if shape is not None:
																_UpperCamelCase			:			List[Any]   			=						z_q.view(lowercase__					)
																# reshape back to match original input shape
																_UpperCamelCase			:			Optional[int]   			=						z_q.permute(0       ,		3       ,		1       ,		2					).contiguous()

										return z_q





class 		SCREAMING_SNAKE_CASE     (					SCREAMING_SNAKE_CASE	):







				'''simple docstring'''





				def __init__(						self					:						Dict       ,		lowercase__					:						str       ,		lowercase__					:						List[Any]=False					)							->Any:


										'''simple docstring'''




										_UpperCamelCase			:			Tuple   			=						parameters
										_UpperCamelCase			,       _UpperCamelCase			:			Tuple   			=						torch.chunk(lowercase__       ,		2       ,		dim=1					)
										_UpperCamelCase			:			str   			=						torch.clamp(self.logvar       ,		-3_0.0       ,		2_0.0					)
										_UpperCamelCase			:			str   			=						deterministic
										_UpperCamelCase			:			Optional[Any]   			=						torch.exp(0.5 * self.logvar					)
										_UpperCamelCase			:			Optional[Any]   			=						torch.exp(self.logvar					)
										if self.deterministic:
																_UpperCamelCase			:			Optional[Any]   			=						torch.zeros_like(
																    self.mean       ,		device=self.parameters.device       ,		dtype=self.parameters.dtype					)





				def  snake_case__				(						self					:						Any       ,		lowercase__					:						Optional[torch.Generator] = None					)							->torch.FloatTensor:


										'''simple docstring'''




										_UpperCamelCase			:			Union[str, Any]   			=						randn_tensor(
										    self.mean.shape       ,		generator=lowercase__       ,		device=self.parameters.device       ,		dtype=self.parameters.dtype					)
										_UpperCamelCase			:			Optional[int]   			=						self.mean + self.std * sample
										return x





				def  snake_case__				(						self					:						str       ,		lowercase__					:						Optional[int]=None					)							->List[str]:


										'''simple docstring'''




										if self.deterministic:
																return torch.Tensor([0.0]					)
										else:
																if other is None:
																						return 0.5 * torch.sum(torch.pow(self.mean       ,		2					) + self.var - 1.0 - self.logvar       ,		dim=[1, 2, 3]					)
																else:
																						return 0.5 * torch.sum(
																						    torch.pow(self.mean - other.mean       ,		2					) / other.var
																						    + self.var / other.var
																						    - 1.0
																						    - self.logvar
																						    + other.logvar       ,		dim=[1, 2, 3]       ,		)





				def  snake_case__				(						self					:						List[Any]       ,		lowercase__					:						str       ,		lowercase__					:						List[Any]=[1, 2, 3]					)							->Dict:


										'''simple docstring'''




										if self.deterministic:
																return torch.Tensor([0.0]					)
										_UpperCamelCase			:			Optional[Any]   			=						np.log(2.0 * np.pi					)
										return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean       ,		2					) / self.var       ,		dim=lowercase__					)







				def  snake_case__				(						self					:						List[Any]					)							->str:


										'''simple docstring'''




										return self.mean


