

'''simple docstring'''






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

import datasets
import numpy as np
import torch
import torchaudio
from packaging import version
from torch import nn

import transformers
from transformers import (
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaForCTC,
    WavaVecaProcessor,
    is_apex_available,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint, is_main_process


if is_apex_available():
 from apex import amp


if version.parse(version.parse(torch.__version__).base_version) >= version.parse('''1.6'''):
 lowerCAmelCase__											=	True
 from torch.cuda.amp import autocast

lowerCAmelCase__											=	logging.getLogger(__name__)


def 		_A     (    A__=None     ,				A__=None      ):






 """simple docstring"""



 return field(default_factory=lambda: default     ,				metadata=A__      )






@dataclass
class 			lowercase_	:




  """simple docstring"""




  SCREAMING_SNAKE_CASE    :  str							=			field(
      metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'}      )
  SCREAMING_SNAKE_CASE    :  Optional[str]							=			field(
      default=lowerCamelCase__				,       metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'}				,       )
  SCREAMING_SNAKE_CASE    :  Optional[bool]							=			field(
      default=lowerCamelCase__				,       metadata={'help': 'Whether to freeze the feature extractor layers of the model.'}      )
  SCREAMING_SNAKE_CASE    :  Optional[float]							=			field(
      default=0.1				,       metadata={'help': 'The dropout ratio for the attention probabilities.'}      )
  SCREAMING_SNAKE_CASE    :  Optional[float]							=			field(
      default=0.1				,       metadata={'help': 'The dropout ratio for activations inside the fully connected layer.'}      )
  SCREAMING_SNAKE_CASE    :  Optional[float]							=			field(
      default=0.1				,       metadata={
          'help': 'The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.'
      }				,       )
  SCREAMING_SNAKE_CASE    :  Optional[float]							=			field(
      default=0.1				,       metadata={'help': 'The dropout probabilitiy for all 1D convolutional layers in feature extractor.'}				,       )
  SCREAMING_SNAKE_CASE    :  Optional[float]							=			field(
      default=0.05				,       metadata={
          'help': (
              'Propability of each feature vector along the time axis to be chosen as the start of the vector'
              'span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature'
              'vectors will be masked along the time axis. This is only relevant if ``apply_spec_augment is True``.'
          )
      }				,       )
  SCREAMING_SNAKE_CASE    :  Optional[float]							=			field(default=0.0				,       metadata={'help': 'The LayerDrop probability.'}      )






@dataclass
class 			lowercase_	:




  """simple docstring"""




  SCREAMING_SNAKE_CASE    :  Optional[str]							=			field(
      default=lowerCamelCase__				,       metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'}      )
  SCREAMING_SNAKE_CASE    :  Optional[str]							=			field(
      default='train+validation'				,       metadata={
          'help': 'The name of the training data set split to use (via the datasets library). Defaults to \'train\''
      }				,       )
  SCREAMING_SNAKE_CASE    :  bool							=			field(
      default=lowerCamelCase__				,       metadata={'help': 'Overwrite the cached preprocessed datasets or not.'}      )
  SCREAMING_SNAKE_CASE    :  Optional[int]							=			field(
      default=lowerCamelCase__				,       metadata={'help': 'The number of processes to use for the preprocessing.'}				,       )
  SCREAMING_SNAKE_CASE    :  Optional[int]							=			field(
      default=lowerCamelCase__				,       metadata={
          'help': (
              'For debugging purposes or quicker training, truncate the number of training examples to this '
              'value if set.'
          )
      }				,       )
  SCREAMING_SNAKE_CASE    :  Optional[int]							=			field(
      default=lowerCamelCase__				,       metadata={
          'help': (
              'For debugging purposes or quicker training, truncate the number of validation examples to this '
              'value if set.'
          )
      }				,       )
  SCREAMING_SNAKE_CASE    :  List[str]							=			list_field(
      default=[',', '?', '.', '!', '-', ';', ':', '""', '%', '\'', '"', '�']				,       metadata={'help': 'A list of characters to remove from the transcripts.'}				,       )






@dataclass
class 			lowercase_	:




  """simple docstring"""




  SCREAMING_SNAKE_CASE    :  WavaVecaProcessor
  SCREAMING_SNAKE_CASE    :  Union[bool, str]							=			True
  SCREAMING_SNAKE_CASE    :  Optional[int]							=			None
  SCREAMING_SNAKE_CASE    :  Optional[int]							=			None
  SCREAMING_SNAKE_CASE    :  Optional[int]							=			None
  SCREAMING_SNAKE_CASE    :  Optional[int]							=			None






  def __call__(      self   :     Union[str, Any]					,lowercase__   :     List[Dict[str, Union[List[int], torch.Tensor]]]			):
   # split inputs and labels since they have to be of different lenghts and need
   # different padding methods
   __lowercase							  = [{'''input_values''': feature['''input_values''']} for feature in features]
   __lowercase							  = [{'''input_ids''': feature['''labels''']} for feature in features]

   __lowercase							  = self.processor.pad(
       lowercase__					,padding=self.padding					,max_length=self.max_length					,pad_to_multiple_of=self.pad_to_multiple_of					,return_tensors='''pt'''					,)
   __lowercase							  = self.processor.pad(
       labels=lowercase__					,padding=self.padding					,max_length=self.max_length_labels					,pad_to_multiple_of=self.pad_to_multiple_of_labels					,return_tensors='''pt'''					,)

   # replace padding with -100 to ignore loss correctly
   __lowercase							  = labels_batch['''input_ids'''].masked_fill(labels_batch.attention_mask.ne(1			)					,-1_0_0			)

   __lowercase							  = labels

   return batch






class 			lowercase_	(lowerCamelCase__      ):




  """simple docstring"""




  def 					SCREAMING_SNAKE_CASE      (      self   :     Union[str, Any]					,lowercase__   :     nn.Module					,lowercase__   :     Dict[str, Union[torch.Tensor, Any]]			):
   model.train()
   __lowercase							  = self._prepare_inputs(lowercase__			)

   if self.use_amp:
    with autocast():
     __lowercase							  = self.compute_loss(lowercase__					,lowercase__			)
   else:
    __lowercase							  = self.compute_loss(lowercase__					,lowercase__			)

   if self.args.n_gpu > 1:
    if model.module.config.ctc_loss_reduction == "mean":
     __lowercase							  = loss.mean()
    elif model.module.config.ctc_loss_reduction == "sum":
     __lowercase							  = loss.sum() / (inputs['''labels'''] >= 0).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:
    __lowercase							  = loss / self.args.gradient_accumulation_steps

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

   return loss.detach()


def 		_A     (    ):






 """simple docstring"""



 __lowercase							  = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)      )
 if len(sys.argv      ) == 2 and sys.argv[1].endswith('''.json'''      ):
  # If we pass only one argument to the script and it's the path to a json file,
  # let's parse it to get our arguments.
  __lowercase  ,	__lowercase  ,	__lowercase							  = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]      )      )
 else:
  __lowercase  ,	__lowercase  ,	__lowercase							  = parser.parse_args_into_dataclasses()

 # Detecting last checkpoint.
 __lowercase							  = None
 if os.path.isdir(training_args.output_dir      ) and training_args.do_train and not training_args.overwrite_output_dir:
  __lowercase							  = get_last_checkpoint(training_args.output_dir      )
  if last_checkpoint is None and len(os.listdir(training_args.output_dir      )      ) > 0:
   raise ValueError(
       F"Output directory ({training_args.output_dir}) already exists and is not empty. "
       '''Use --overwrite_output_dir to overcome.'''      )
  elif last_checkpoint is not None:
   logger.info(
       F"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
       '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.'''      )

    # Setup logging
 logging.basicConfig(
     format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s'''     ,				datefmt='''%m/%d/%Y %H:%M:%S'''     ,				handlers=[logging.StreamHandler(sys.stdout      )]     ,				)
 logger.setLevel(logging.INFO if is_main_process(training_args.local_rank      ) else logging.WARN      )

 # Log on each process the small summary:
 logger.warning(
     F"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
     + F"distributed training: {bool(training_args.local_rank != -1      )}, 16-bits training: {training_args.fpaa}"      )
 # Set the verbosity to info of the Transformers logger (on main process only):
 if is_main_process(training_args.local_rank      ):
  transformers.utils.logging.set_verbosity_info()
 logger.info('''Training/evaluation parameters %s'''     ,				A__      )

 # Set seed before initializing model.
 set_seed(training_args.seed      )

 # Get the datasets:
 __lowercase							  = datasets.load_dataset(
     '''common_voice'''     ,				data_args.dataset_config_name     ,				split=data_args.train_split_name      )
 __lowercase							  = datasets.load_dataset('''common_voice'''     ,				data_args.dataset_config_name     ,				split='''test'''      )

 # Create and save tokenizer
 __lowercase							  = F"[{''.join(data_args.chars_to_ignore      )}]"

 def remove_special_characters(A__      ):
  __lowercase							  = re.sub(A__     ,				''''''     ,				batch['''sentence''']      ).lower() + ''' '''
  return batch

 __lowercase							  = train_dataset.map(A__     ,				remove_columns=['''sentence''']      )
 __lowercase							  = eval_dataset.map(A__     ,				remove_columns=['''sentence''']      )

 def extract_all_chars(A__      ):
  __lowercase							  = ''' '''.join(batch['''text''']      )
  __lowercase							  = list(set(A__      )      )
  return {"vocab": [vocab], "all_text": [all_text]}

 __lowercase							  = train_dataset.map(
     A__     ,				batched=A__     ,				batch_size=-1     ,				keep_in_memory=A__     ,				remove_columns=train_dataset.column_names     ,				)
 __lowercase							  = train_dataset.map(
     A__     ,				batched=A__     ,				batch_size=-1     ,				keep_in_memory=A__     ,				remove_columns=eval_dataset.column_names     ,				)

 __lowercase							  = list(set(vocab_train['''vocab'''][0]      ) | set(vocab_test['''vocab'''][0]      )      )
 __lowercase							  = {v: k for k, v in enumerate(A__      )}
 __lowercase							  = vocab_dict[''' ''']
 del vocab_dict[" "]
 __lowercase							  = len(A__      )
 __lowercase							  = len(A__      )

 with open('''vocab.json'''     ,				'''w'''      ) as vocab_file:
  json.dump(A__     ,				A__      )

 # Load pretrained model and tokenizer
 #
 # Distributed training:
 # The .from_pretrained methods guarantee that only one local process can concurrently
 # download model & vocab.
 __lowercase							  = WavaVecaCTCTokenizer(
     '''vocab.json'''     ,				unk_token='''[UNK]'''     ,				pad_token='''[PAD]'''     ,				word_delimiter_token='''|'''     ,				)
 __lowercase							  = WavaVecaFeatureExtractor(
     feature_size=1     ,				sampling_rate=16000     ,				padding_value=0.0     ,				do_normalize=A__     ,				return_attention_mask=A__      )
 __lowercase							  = WavaVecaProcessor(feature_extractor=A__     ,				tokenizer=A__      )
 __lowercase							  = WavaVecaForCTC.from_pretrained(
     model_args.model_name_or_path     ,				cache_dir=model_args.cache_dir     ,				activation_dropout=model_args.activation_dropout     ,				attention_dropout=model_args.attention_dropout     ,				hidden_dropout=model_args.hidden_dropout     ,				feat_proj_dropout=model_args.feat_proj_dropout     ,				mask_time_prob=model_args.mask_time_prob     ,				gradient_checkpointing=training_args.gradient_checkpointing     ,				layerdrop=model_args.layerdrop     ,				ctc_loss_reduction='''mean'''     ,				pad_token_id=processor.tokenizer.pad_token_id     ,				vocab_size=len(processor.tokenizer      )     ,				)

 if data_args.max_train_samples is not None:
  __lowercase							  = min(len(A__      )     ,				data_args.max_train_samples      )
  __lowercase							  = train_dataset.select(range(A__      )      )

 if data_args.max_val_samples is not None:
  __lowercase							  = eval_dataset.select(range(data_args.max_val_samples      )      )

 __lowercase							  = torchaudio.transforms.Resample(48000     ,				16000      )

 # Preprocessing the datasets.
 # We need to read the aduio files as arrays and tokenize the targets.
 def speech_file_to_array_fn(A__      ):
  __lowercase  ,	__lowercase							  = torchaudio.load(batch['''path''']      )
  __lowercase							  = resampler(A__      ).squeeze().numpy()
  __lowercase							  = 16000
  __lowercase							  = batch['''text''']
  return batch

 __lowercase							  = train_dataset.map(
     A__     ,				remove_columns=train_dataset.column_names     ,				num_proc=data_args.preprocessing_num_workers     ,				)
 __lowercase							  = eval_dataset.map(
     A__     ,				remove_columns=eval_dataset.column_names     ,				num_proc=data_args.preprocessing_num_workers     ,				)

 def prepare_dataset(A__      ):
  # check that all files have the correct sampling rate
  assert (
      len(set(batch['''sampling_rate''']      )      ) == 1
  ), F"Make sure all inputs have the same sampling rate of {processor.feature_extractor.sampling_rate}."

  __lowercase							  = processor(
      audio=batch['''speech''']     ,				text=batch['''target_text''']     ,				sampling_rate=batch['''sampling_rate'''][0]      )
  batch.update(A__      )
  return batch

 __lowercase							  = train_dataset.map(
     A__     ,				remove_columns=train_dataset.column_names     ,				batch_size=training_args.per_device_train_batch_size     ,				batched=A__     ,				num_proc=data_args.preprocessing_num_workers     ,				)
 __lowercase							  = eval_dataset.map(
     A__     ,				remove_columns=eval_dataset.column_names     ,				batch_size=training_args.per_device_train_batch_size     ,				batched=A__     ,				num_proc=data_args.preprocessing_num_workers     ,				)

 # Metric
 __lowercase							  = datasets.load_metric('''wer'''      )

 def compute_metrics(A__      ):
  __lowercase							  = pred.predictions
  __lowercase							  = np.argmax(A__     ,				axis=-1      )

  __lowercase							  = processor.tokenizer.pad_token_id

  __lowercase							  = processor.batch_decode(A__      )
  # we do not want to group tokens when computing the metrics
  __lowercase							  = processor.batch_decode(pred.label_ids     ,				group_tokens=A__      )

  __lowercase							  = wer_metric.compute(predictions=A__     ,				references=A__      )

  return {"wer": wer}

 if model_args.freeze_feature_extractor:
  model.freeze_feature_extractor()

 # Data collator
 __lowercase							  = DataCollatorCTCWithPadding(processor=A__     ,				padding=A__      )

 # Initialize our Trainer
 __lowercase							  = CTCTrainer(
     model=A__     ,				data_collator=A__     ,				args=A__     ,				compute_metrics=A__     ,				train_dataset=train_dataset if training_args.do_train else None     ,				eval_dataset=eval_dataset if training_args.do_eval else None     ,				tokenizer=processor.feature_extractor     ,				)

 # Training
 if training_args.do_train:
  if last_checkpoint is not None:
   __lowercase							  = last_checkpoint
  elif os.path.isdir(model_args.model_name_or_path      ):
   __lowercase							  = model_args.model_name_or_path
  else:
   __lowercase							  = None

  # Save the feature_extractor and the tokenizer
  if is_main_process(training_args.local_rank      ):
   processor.save_pretrained(training_args.output_dir      )

  __lowercase							  = trainer.train(resume_from_checkpoint=A__      )
  trainer.save_model()

  __lowercase							  = train_result.metrics
  __lowercase							  = (
      data_args.max_train_samples if data_args.max_train_samples is not None else len(A__      )
  )
  __lowercase							  = min(A__     ,				len(A__      )      )

  trainer.log_metrics('''train'''     ,				A__      )
  trainer.save_metrics('''train'''     ,				A__      )
  trainer.save_state()

 # Evaluation
 __lowercase							  = {}
 if training_args.do_eval:
  logger.info('''*** Evaluate ***'''      )
  __lowercase							  = trainer.evaluate()
  __lowercase							  = data_args.max_val_samples if data_args.max_val_samples is not None else len(A__      )
  __lowercase							  = min(A__     ,				len(A__      )      )

  trainer.log_metrics('''eval'''     ,				A__      )
  trainer.save_metrics('''eval'''     ,				A__      )

 return results


if __name__ == "__main__":
 main()




'''simple docstring'''






import torch
from torch import nn






class 			lowercase_	(nn.Module      ):




  """simple docstring"""




  def __init__(      self   :     Optional[int]					,lowercase__   :     List[str]					,lowercase__   :     Any					,lowercase__   :     Union[str, Any]					,lowercase__   :     Optional[int]					,lowercase__   :     Optional[int]=1					,lowercase__   :     Optional[Any]=False			):
   super().__init__()

   __lowercase							  = n_token
   __lowercase							  = d_embed
   __lowercase							  = d_proj

   __lowercase							  = cutoffs + [n_token]
   __lowercase							  = [0] + self.cutoffs
   __lowercase							  = div_val

   __lowercase							  = self.cutoffs[0]
   __lowercase							  = len(self.cutoffs			) - 1
   __lowercase							  = self.shortlist_size + self.n_clusters

   if self.n_clusters > 0:
    __lowercase							  = nn.Parameter(torch.zeros(self.n_clusters					,self.d_embed			)			)
    __lowercase							  = nn.Parameter(torch.zeros(self.n_clusters			)			)

   __lowercase							  = nn.ModuleList()
   __lowercase							  = nn.ParameterList()

   if div_val == 1:
    for i in range(len(self.cutoffs			)			):
     if d_proj != d_embed:
      self.out_projs.append(nn.Parameter(torch.FloatTensor(lowercase__					,lowercase__			)			)			)
     else:
      self.out_projs.append(lowercase__			)

    self.out_layers.append(nn.Linear(lowercase__					,lowercase__			)			)
   else:
    for i in range(len(self.cutoffs			)			):
     __lowercase  ,	__lowercase							  = self.cutoff_ends[i], self.cutoff_ends[i + 1]
     __lowercase							  = d_embed // (div_val**i)

     self.out_projs.append(nn.Parameter(torch.FloatTensor(lowercase__					,lowercase__			)			)			)

     self.out_layers.append(nn.Linear(lowercase__					,r_idx - l_idx			)			)

   __lowercase							  = keep_order






  def 					SCREAMING_SNAKE_CASE      (      self   :     Optional[int]					,lowercase__   :     List[Any]					,lowercase__   :     Dict					,lowercase__   :     List[Any]					,lowercase__   :     Any			):
   if proj is None:
    __lowercase							  = nn.functional.linear(lowercase__					,lowercase__					,bias=lowercase__			)
   else:
    # if CUDA_MAJOR <= 9 and CUDA_MINOR <= 1:
    __lowercase							  = nn.functional.linear(lowercase__					,proj.t().contiguous()			)
    __lowercase							  = nn.functional.linear(lowercase__					,lowercase__					,bias=lowercase__			)
    # else:
    #     logit = torch.einsum('bd,de,ev->bv', (hidden, proj, weight.t()))
    #     if bias is not None:
    #         logit = logit + bias

   return logit






  def 					SCREAMING_SNAKE_CASE      (      self   :     Union[str, Any]					,lowercase__   :     Optional[Any]					,lowercase__   :     Any=None					,lowercase__   :     List[str]=False			):

   if labels is not None:
    # Shift so that tokens < n predict n
    __lowercase							  = hidden[..., :-1, :].contiguous()
    __lowercase							  = labels[..., 1:].contiguous()
    __lowercase							  = hidden.view(-1					,hidden.size(-1			)			)
    __lowercase							  = labels.view(-1			)
    if hidden.size(0			) != labels.size(0			):
     raise RuntimeError('''Input and labels should have the same size in the batch dimension.'''			)
   else:
    __lowercase							  = hidden.view(-1					,hidden.size(-1			)			)

   if self.n_clusters == 0:
    __lowercase							  = self._compute_logit(lowercase__					,self.out_layers[0].weight					,self.out_layers[0].bias					,self.out_projs[0]			)
    if labels is not None:
     __lowercase							  = labels != -1_0_0
     __lowercase							  = torch.zeros_like(lowercase__					,dtype=hidden.dtype					,device=hidden.device			)
     __lowercase							  = (
         -nn.functional.log_softmax(lowercase__					,dim=-1			)[mask].gather(1					,labels[mask].unsqueeze(1			)			).squeeze(1			)
     )
    else:
     __lowercase							  = nn.functional.log_softmax(lowercase__					,dim=-1			)
   else:
    # construct weights and biases
    __lowercase  ,	__lowercase							  = [], []
    for i in range(len(self.cutoffs			)			):
     if self.div_val == 1:
      __lowercase  ,	__lowercase							  = self.cutoff_ends[i], self.cutoff_ends[i + 1]
      __lowercase							  = self.out_layers[0].weight[l_idx:r_idx]
      __lowercase							  = self.out_layers[0].bias[l_idx:r_idx]
     else:
      __lowercase							  = self.out_layers[i].weight
      __lowercase							  = self.out_layers[i].bias

     if i == 0:
      __lowercase							  = torch.cat([weight_i, self.cluster_weight]					,dim=0			)
      __lowercase							  = torch.cat([bias_i, self.cluster_bias]					,dim=0			)

     weights.append(lowercase__			)
     biases.append(lowercase__			)

    __lowercase  ,	__lowercase  ,	__lowercase							  = weights[0], biases[0], self.out_projs[0]

    __lowercase							  = self._compute_logit(lowercase__					,lowercase__					,lowercase__					,lowercase__			)
    __lowercase							  = nn.functional.log_softmax(lowercase__					,dim=1			)

    if labels is None:
     __lowercase							  = hidden.new_empty((head_logit.size(0			), self.n_token)			)
    else:
     __lowercase							  = torch.zeros_like(lowercase__					,dtype=hidden.dtype					,device=hidden.device			)

    __lowercase							  = 0
    __lowercase							  = [0] + self.cutoffs
    for i in range(len(lowercase__			) - 1			):
     __lowercase  ,	__lowercase							  = cutoff_values[i], cutoff_values[i + 1]

     if labels is not None:
      __lowercase							  = (labels >= l_idx) & (labels < r_idx)
      __lowercase							  = mask_i.nonzero().squeeze()

      if indices_i.numel() == 0:
       continue

      __lowercase							  = labels.index_select(0					,lowercase__			) - l_idx
      __lowercase							  = head_logprob.index_select(0					,lowercase__			)
      __lowercase							  = hidden.index_select(0					,lowercase__			)
     else:
      __lowercase							  = hidden

     if i == 0:
      if labels is not None:
       __lowercase							  = head_logprob_i.gather(1					,target_i[:, None]			).squeeze(1			)
      else:
       __lowercase							  = head_logprob[:, : self.cutoffs[0]]
     else:
      __lowercase  ,	__lowercase  ,	__lowercase							  = weights[i], biases[i], self.out_projs[i]

      __lowercase							  = self._compute_logit(lowercase__					,lowercase__					,lowercase__					,lowercase__			)
      __lowercase							  = nn.functional.log_softmax(lowercase__					,dim=1			)
      __lowercase							  = self.cutoffs[0] + i - 1  # No probability for the head cluster
      if labels is not None:
       __lowercase							  = head_logprob_i[:, cluster_prob_idx] + tail_logprob_i.gather(
           1					,target_i[:, None]			).squeeze(1			)
      else:
       __lowercase							  = head_logprob[:, cluster_prob_idx, None] + tail_logprob_i
       __lowercase							  = logprob_i

     if labels is not None:
      if (hasattr(self					,'''keep_order'''			) and self.keep_order) or keep_order:
       out.index_copy_(0					,lowercase__					,-logprob_i			)
      else:
       out[offset : offset + logprob_i.size(0			)].copy_(-logprob_i			)
      offset += logprob_i.size(0			)

   return out






  def 					SCREAMING_SNAKE_CASE      (      self   :     Any					,lowercase__   :     Union[str, Any]			):
   if self.n_clusters == 0:
    __lowercase							  = self._compute_logit(lowercase__					,self.out_layers[0].weight					,self.out_layers[0].bias					,self.out_projs[0]			)
    return nn.functional.log_softmax(lowercase__					,dim=-1			)
   else:
    # construct weights and biases
    __lowercase  ,	__lowercase							  = [], []
    for i in range(len(self.cutoffs			)			):
     if self.div_val == 1:
      __lowercase  ,	__lowercase							  = self.cutoff_ends[i], self.cutoff_ends[i + 1]
      __lowercase							  = self.out_layers[0].weight[l_idx:r_idx]
      __lowercase							  = self.out_layers[0].bias[l_idx:r_idx]
     else:
      __lowercase							  = self.out_layers[i].weight
      __lowercase							  = self.out_layers[i].bias

     if i == 0:
      __lowercase							  = torch.cat([weight_i, self.cluster_weight]					,dim=0			)
      __lowercase							  = torch.cat([bias_i, self.cluster_bias]					,dim=0			)

     weights.append(lowercase__			)
     biases.append(lowercase__			)

    __lowercase  ,	__lowercase  ,	__lowercase							  = weights[0], biases[0], self.out_projs[0]
    __lowercase							  = self._compute_logit(lowercase__					,lowercase__					,lowercase__					,lowercase__			)

    __lowercase							  = hidden.new_empty((head_logit.size(0			), self.n_token)			)
    __lowercase							  = nn.functional.log_softmax(lowercase__					,dim=1			)

    __lowercase							  = [0] + self.cutoffs
    for i in range(len(lowercase__			) - 1			):
     __lowercase  ,	__lowercase							  = cutoff_values[i], cutoff_values[i + 1]

     if i == 0:
      __lowercase							  = head_logprob[:, : self.cutoffs[0]]
     else:
      __lowercase  ,	__lowercase  ,	__lowercase							  = weights[i], biases[i], self.out_projs[i]

      __lowercase							  = self._compute_logit(lowercase__					,lowercase__					,lowercase__					,lowercase__			)
      __lowercase							  = nn.functional.log_softmax(lowercase__					,dim=1			)

      __lowercase							  = head_logprob[:, -i] + tail_logprob_i
      __lowercase							  = logprob_i

    return out

