



import logging
import os
import time
from argparse import Namespace
from pathlib import Path

import datasets
import torch
from accelerate import Accelerator, DistributedType
from accelerate.utils import ProjectConfiguration
from arguments import TrainingArguments
from datasets import load_dataset
from huggingface_hub import Repository
from torch.optim import AdamW
from torch.utils.data import IterableDataset
from torch.utils.data.dataloader import DataLoader
from torch.utils.data.datapipes.iter.combinatorics import ShufflerIterDataPipe

import transformers
from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, get_scheduler, set_seed




class  snake_case__						(	lowerCAmelCase_					):






     """simple docstring"""


     def __init__(	self  :  Any,			_snake_case  :  Tuple,			_snake_case  :  Tuple,			_snake_case  :  List[str]=False,			_snake_case  :  List[Any]=1_0_2_4,			_snake_case  :  str=1_0_2_4,			_snake_case  :  Optional[Any]=3.6,			_snake_case  :  Tuple=False,			)       ->Tuple:
            snake_case__							:     str            =     tokenizer
            snake_case__							:     int            =     tokenizer.bos_token_id
            snake_case__							:     List[Any]            =     dataset
            snake_case__							:     Optional[int]            =     seq_length
            snake_case__							:     Optional[int]            =     0
            snake_case__							:     Optional[Any]            =     infinite
            snake_case__							:     List[Any]            =     0
            snake_case__							:     List[Any]            =     tokenized

            if self.tokenized:
                   snake_case__							:     int            =     seq_length * num_of_sequences
                   snake_case__							:     Any            =     'input_ids'
            else:
                   snake_case__							:     Any            =     seq_length * chars_per_token * num_of_sequences
                   snake_case__							:     List[str]            =     'content'






     def __iter__(	self  :  Optional[Any] )       ->str:
            snake_case__							:     Optional[Any]            =     iter(self.dataset )
            snake_case__							:     Union[str, Any]            =     True
            while more_examples:
                   snake_case__     ,    snake_case__							:     List[Any]            =     [], 0
                   while True:
                          if buffer_len >= self.max_buffer_size:
                                 break
                          try:
                                 buffer.append(next(_snake_case )[self.content_field] )
                                 buffer_len += len(buffer[-1] )
                          except StopIteration:
                                 if self.infinite:
                                        snake_case__							:     Union[str, Any]            =     iter(self.dataset )
                                        self.epoch += 1
                                        logger.info(F'''Dataset epoch: {self.epoch}''' )
                                 else:
                                        snake_case__							:     Dict            =     False
                                        break
                   if self.tokenized:
                          snake_case__							:     Optional[Any]            =     buffer
                   else:
                          snake_case__							:     Optional[Any]            =     self.tokenizer(_snake_case,			truncation=_snake_case )['input_ids']
                   snake_case__							:     str            =     []
                   for tokenized_input in tokenized_inputs:
                          all_token_ids.extend(tokenized_input + [self.concat_token_id] )
                   for i in range(0,			len(_snake_case ),			self.seq_length ):
                          snake_case__							:     Tuple            =     all_token_ids[i : i + self.seq_length]
                          if len(_snake_case ) == self.seq_length:
                                 self.current_size += 1
                                 yield torch.tensor(_snake_case )






     def        lowercase_       (	self  :  Dict,			_snake_case  :  int=1_0_0_0 )       ->Optional[Any]:
            return ShufflerIterDataPipe(self,			buffer_size=_snake_case )


def 	lowercase_							(A			:			str				):
       snake_case__							:     Optional[Any]            =     args.model_ckpt.split('/'				)[-1]
       snake_case__							:     Dict            =     logging.getLogger(__name__				)
       snake_case__							:     Tuple            =     Path(args.save_dir				) / 'log/'
       log_dir.mkdir(exist_ok=A				)
       snake_case__							:     List[Any]            =     F'''debug_{accelerator.process_index}.log'''
       logging.basicConfig(
           format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'		, datefmt='%m/%d/%Y %H:%M:%S'		, level=logging.INFO		, handlers=[logging.FileHandler(log_dir / filename				), logging.StreamHandler()]		, )
       if accelerator.is_main_process:  # we only want to setup logging once
              accelerator.init_trackers(A		, vars(A				)				)
              snake_case__							:     Optional[int]            =     accelerator.trackers[0].run.name
              logger.setLevel(logging.INFO				)
              datasets.utils.logging.set_verbosity_info()
              transformers.utils.logging.set_verbosity_info()
       else:
              snake_case__							:     Any            =     ''
              logger.setLevel(logging.ERROR				)
              datasets.utils.logging.set_verbosity_error()
              transformers.utils.logging.set_verbosity_error()
       return logger, run_name
def 	lowercase_							(A			:			List[Any]				):
       snake_case__							:     Optional[Any]            =     {'streaming': True}
       snake_case__							:     List[str]            =     load_dataset(args.dataset_name_train		, split='train'		, **A				)
       snake_case__							:     Any            =     train_data.shuffle(buffer_size=args.shuffle_buffer		, seed=args.seed				)
       snake_case__							:     List[str]            =     load_dataset(args.dataset_name_valid		, split='train'		, **A				)
       snake_case__							:     List[str]            =     ConstantLengthDataset(
           A		, A		, infinite=A		, seq_length=args.seq_length		, tokenized=args.tokenized				)
       snake_case__							:     Union[str, Any]            =     ConstantLengthDataset(
           A		, A		, infinite=A		, seq_length=args.seq_length		, tokenized=args.tokenized				)
       snake_case__							:     Dict            =     train_dataset.shuffle(buffer_size=args.shuffle_buffer				)
       snake_case__							:     Any            =     DataLoader(A		, batch_size=args.train_batch_size		, shuffle=A				)
       snake_case__							:     int            =     DataLoader(A		, batch_size=args.valid_batch_size				)
       return train_dataloader, eval_dataloader
def 	lowercase_							(A			:			int		, A			:			Any		, A			:			List[Any]=["bias", "ln_1.weight", "ln_2.weight", "ln_f.weight"]				):
       snake_case__     ,    snake_case__							:     Dict            =     [], []
       for n, p in model.named_parameters():
              if any(nd in n for nd in no_decay				):
                     params_without_wd.append(A				)
              else:
                     params_with_wd.append(A				)
       return [
           {"params": params_with_wd, "weight_decay": args.weight_decay},
           {"params": params_without_wd, "weight_decay": 0.0},
       ]
def 	lowercase_							(A			:			List[Any]		, A			:			Optional[int]				):
       logger.info(F'''Step {step}: {metrics}'''				)
       if accelerator.is_main_process:
              accelerator.log(A		, A				)
def 	lowercase_							(A			:			Any		, A			:			List[str]		, A			:			Dict				):
       # TFLOPs formula (from Equation 3 in Section 5.1 of https://arxiv.org/pdf/2104.04473.pdf).
       snake_case__							:     str            =     accelerator.unwrap_model(A				).config
       snake_case__							:     List[str]            =     4 if args.gradient_checkpointing else 3
       snake_case__							:     Optional[int]            =     args.train_batch_size * accelerator.state.num_processes * args.gradient_accumulation_steps
       snake_case__							:     List[Any]            =     2_4 * checkpoint_factor * batch_size * args.seq_length * config_model.n_layer * (config_model.n_embd**2)
       snake_case__							:     Any            =     factor * (
           1.0
           + (args.seq_length / (6.0 * config_model.n_embd))
           + (tokenizer.vocab_size / (16.0 * config_model.n_layer * config_model.n_embd))
       )
       snake_case__							:     List[str]            =     flops_per_iteration / (elapsed_time * accelerator.state.num_processes * (1_0**1_2))
       return tflops
def 	lowercase_							(A			:			Optional[Any]				):
       model.eval()
       snake_case__							:     Optional[Any]            =     []
       for step, batch in enumerate(A				):
              with torch.no_grad():
                     snake_case__							:     Optional[Any]            =     model(A		, labels=A				)
              snake_case__							:     Union[str, Any]            =     outputs.loss.repeat(args.valid_batch_size				)
              losses.append(accelerator.gather(A				)				)
              if args.max_eval_steps > 0 and step >= args.max_eval_steps:
                     break
       snake_case__							:     Optional[int]            =     torch.cat(A				)
       snake_case__							:     Optional[Any]            =     losses[: eval_dataloader.dataset.current_size].mean()
       try:
              snake_case__							:     Optional[int]            =     torch.exp(A				)
       except OverflowError:
              snake_case__							:     str            =     float('inf'				)
       return loss.item(), perplexity.item()


# Settings
a_       :str				  =				HfArgumentParser(TrainingArguments)
a_       :List[str]				  =				parser.parse_args()

# Accelerator
a_       :List[Any]				  =				ProjectConfiguration(project_dir=args.save_dir, logging_dir="log")
a_       :Dict				  =				Accelerator(log_with=["wandb", "tensorboard"], project_config=config)
a_       :Union[str, Any]				  =				{str(k): str(v) for k, v in accelerator.state.__dict__.items()}

a_       :Optional[Any]				  =				Namespace(**vars(args), **acc_state)
a_       :List[Any]				  =				accelerator.state.num_processes * args.train_batch_size
set_seed(args.seed)

# Clone model repository
if accelerator.is_main_process:
 a_       :Any				  =				Repository(args.save_dir, clone_from=args.model_ckpt)

# Logging
a_  ,						a_       :int				  =				setup_logging(args)
logger.info(accelerator.state)

# Checkout new branch on repo
if accelerator.is_main_process:
 hf_repo.git_checkout(run_name, create_branch_ok=True)

# Load model and tokenizer
a_       :str				  =				AutoModelForCausalLM.from_pretrained(args.save_dir)
if args.gradient_checkpointing:
 model.gradient_checkpointing_enable()
a_       :Union[str, Any]				  =				AutoTokenizer.from_pretrained(args.save_dir)

# Load dataset and dataloader
a_  ,						a_       :List[str]				  =				create_dataloaders(args)

# Prepare the optimizer and learning rate scheduler
a_       :List[Any]				  =				AdamW(get_grouped_params(model, args), lr=args.learning_rate)
a_       :List[Any]				  =				get_scheduler(
    name=args.lr_scheduler_type,
    optimizer=optimizer,
    num_warmup_steps=args.num_warmup_steps,
    num_training_steps=args.max_train_steps,
)
accelerator.register_for_checkpointing(lr_scheduler)
def 	lowercase_							():
       return optimizer.param_groups[0]["lr"]


# Prepare everything with our `accelerator`.
a_  ,						a_  ,						a_  ,						a_       :Any				  =				accelerator.prepare(
    model, optimizer, train_dataloader, eval_dataloader
)

# load in the weights and states from a previous save
if args.resume_from_checkpoint:
 if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
  accelerator.print(F"""Resumed from checkpoint: {args.resume_from_checkpoint}""")
  accelerator.load_state(args.resume_from_checkpoint)
  a_       :int				  =				os.path.basename(args.resume_from_checkpoint)
 else:
  # Get the most recent checkpoint
  a_       :List[Any]				  =				[f.name for f in os.scandir(args.save_dir) if f.is_dir() and "step" in str(f)]
  dirs.sort(key=os.path.getctime)
  a_       :str				  =				dirs[-1]  # Sorts folders by date modified, most recent checkpoint is the last
 # Extract the step of the checkpoint to continue from there
 a_       :Tuple				  =				os.path.splitext(path)[0]
 a_       :Any				  =				int(training_difference.replace("step_", ""))

# Train model
model.train()
a_       :Any				  =				0
a_       :List[Any]				  =				time.time()
a_       :Any				  =				0
for step, batch in enumerate(train_dataloader, start=1):
 if args.resume_from_checkpoint and step < resume_step:
  continue  # we need to skip steps until we reach the resumed step
 a_       :Union[str, Any]				  =				model(batch, labels=batch, use_cache=False).loss
 a_       :Union[str, Any]				  =				accelerator.gather(loss.repeat(args.train_batch_size)).mean()
 loss_tracking += avg_loss.item() / args.gradient_accumulation_steps
 log_metrics(step, {"samples": step * samples_per_step, "loss_per_step/train": loss.item()})
 a_       :Optional[int]				  =				loss / args.gradient_accumulation_steps
 if step % args.gradient_accumulation_steps != 0:
  # Prevent backward from doing gradient all_reduce in every step
  if accelerator.distributed_type == DistributedType.MULTI_GPU:
   with model.no_sync():
    accelerator.backward(loss)
  else:
   accelerator.backward(loss)
 else:
  a_       :Tuple				  =				get_lr()
  accelerator.backward(loss)
  accelerator.clip_grad_norm_(model.parameters(), 1.0)
  optimizer.step()
  lr_scheduler.step()
  optimizer.zero_grad()
  a_       :List[Any]				  =				time.time() - t_start
  a_       :str				  =				compute_tflops(elapsed_time, accelerator, args)
  log_metrics(
      step,
      {
          "steps": completed_steps,
          "loss/train": loss_tracking,
          "lr": lr,
          "tflops": tflops,
          "time_per_iteration": elapsed_time,
      },
  )
  a_       :Optional[Any]				  =				time.time()
  a_       :Tuple				  =				0
  completed_steps += 1
 if step % args.save_checkpoint_steps == 0:
  logger.info("Evaluating and saving model checkpoint")
  a_  ,						a_       :Tuple				  =				evaluate(args)
  log_metrics(step, {"loss/eval": eval_loss, "perplexity": perplexity})
  accelerator.wait_for_everyone()
  a_       :Union[str, Any]				  =				os.path.join(args.save_dir, F"""step_{step}""")
  accelerator.save_state(save_dir)
  if accelerator.is_main_process:
   hf_repo.push_to_hub(commit_message=F"""step {step}""")
  model.train()
 if completed_steps >= args.max_train_steps:
  break

# Evaluate and save the last checkpoint
logger.info("Evaluating and saving model after training")
a_  ,						a_       :Optional[int]				  =				evaluate(args)
log_metrics(step, {"loss/eval": eval_loss, "perplexity": perplexity})
accelerator.wait_for_everyone()
a_       :Any				  =				accelerator.unwrap_model(model)
unwrapped_model.save_pretrained(args.save_dir, save_function=accelerator.save)
a_       :Optional[Any]				  =				os.path.join(args.save_dir, F"""step_{step}""")
accelerator.save_state(save_dir)
if accelerator.is_main_process:
 hf_repo.push_to_hub(commit_message="final model")











import shutil
import tempfile
import unittest

import pytest

from transformers import WhisperTokenizer, is_speech_available
from transformers.testing_utils import require_sentencepiece, require_torch, require_torchaudio

from .test_feature_extraction_whisper import floats_list


if is_speech_available():
 from transformers import WhisperFeatureExtractor, WhisperProcessor


a_       :List[Any]				  =				50_358
a_       :int				  =				50_362




@require_torch
@require_torchaudio
@require_sentencepiece
class  snake_case__						(	unittest.TestCase					):






     """simple docstring"""


     def        lowercase_       (	self  :  Dict )       ->List[Any]:
            snake_case__							:     int            =     'openai/whisper-small.en'
            snake_case__							:     List[Any]            =     tempfile.mkdtemp()






     def        lowercase_       (	self  :  Any,			**_snake_case  :  List[str] )       ->Union[str, Any]:
            return WhisperTokenizer.from_pretrained(self.checkpoint,			**_snake_case )






     def        lowercase_       (	self  :  Union[str, Any],			**_snake_case  :  int )       ->Optional[int]:
            return WhisperFeatureExtractor.from_pretrained(self.checkpoint,			**_snake_case )






     def        lowercase_       (	self  :  Any )       ->Union[str, Any]:
            shutil.rmtree(self.tmpdirname )






     def        lowercase_       (	self  :  Dict )       ->Tuple:
            snake_case__							:     Dict            =     self.get_tokenizer()
            snake_case__							:     List[str]            =     self.get_feature_extractor()

            snake_case__							:     List[Any]            =     WhisperProcessor(tokenizer=_snake_case,			feature_extractor=_snake_case )

            processor.save_pretrained(self.tmpdirname )
            snake_case__							:     Dict            =     WhisperProcessor.from_pretrained(self.tmpdirname )

            self.assertEqual(processor.tokenizer.get_vocab(),			tokenizer.get_vocab() )
            self.assertIsInstance(processor.tokenizer,			_snake_case )

            self.assertEqual(processor.feature_extractor.to_json_string(),			feature_extractor.to_json_string() )
            self.assertIsInstance(processor.feature_extractor,			_snake_case )






     def        lowercase_       (	self  :  List[Any] )       ->str:
            snake_case__							:     str            =     WhisperProcessor(tokenizer=self.get_tokenizer(),			feature_extractor=self.get_feature_extractor() )
            processor.save_pretrained(self.tmpdirname )

            snake_case__							:     Dict            =     self.get_tokenizer(bos_token='(BOS)',			eos_token='(EOS)' )
            snake_case__							:     List[str]            =     self.get_feature_extractor(do_normalize=_snake_case,			padding_value=1.0 )

            snake_case__							:     List[Any]            =     WhisperProcessor.from_pretrained(
                self.tmpdirname,			bos_token='(BOS)',			eos_token='(EOS)',			do_normalize=_snake_case,			padding_value=1.0 )

            self.assertEqual(processor.tokenizer.get_vocab(),			tokenizer_add_kwargs.get_vocab() )
            self.assertIsInstance(processor.tokenizer,			_snake_case )

            self.assertEqual(processor.feature_extractor.to_json_string(),			feature_extractor_add_kwargs.to_json_string() )
            self.assertIsInstance(processor.feature_extractor,			_snake_case )






     def        lowercase_       (	self  :  Union[str, Any] )       ->Dict:
            snake_case__							:     Dict            =     self.get_feature_extractor()
            snake_case__							:     Dict            =     self.get_tokenizer()

            snake_case__							:     List[Any]            =     WhisperProcessor(tokenizer=_snake_case,			feature_extractor=_snake_case )

            snake_case__							:     int            =     floats_list((3, 1_0_0_0) )

            snake_case__							:     Optional[int]            =     feature_extractor(_snake_case,			return_tensors='np' )
            snake_case__							:     Optional[int]            =     processor(_snake_case,			return_tensors='np' )

            for key in input_feat_extract.keys():
                   self.assertAlmostEqual(input_feat_extract[key].sum(),			input_processor[key].sum(),			delta=1e-2 )






     def        lowercase_       (	self  :  Dict )       ->Any:
            snake_case__							:     Tuple            =     self.get_feature_extractor()
            snake_case__							:     Optional[int]            =     self.get_tokenizer()

            snake_case__							:     Optional[int]            =     WhisperProcessor(tokenizer=_snake_case,			feature_extractor=_snake_case )

            snake_case__							:     Any            =     'This is a test string'

            snake_case__							:     Dict            =     processor(text=_snake_case )

            snake_case__							:     List[str]            =     tokenizer(_snake_case )

            for key in encoded_tok.keys():
                   self.assertListEqual(encoded_tok[key],			encoded_processor[key] )






     def        lowercase_       (	self  :  Dict )       ->Dict:
            snake_case__							:     Optional[Any]            =     self.get_feature_extractor()
            snake_case__							:     Optional[int]            =     self.get_tokenizer()

            snake_case__							:     Optional[int]            =     WhisperProcessor(tokenizer=_snake_case,			feature_extractor=_snake_case )

            snake_case__							:     Union[str, Any]            =     [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

            snake_case__							:     List[str]            =     processor.batch_decode(_snake_case )
            snake_case__							:     Dict            =     tokenizer.batch_decode(_snake_case )

            self.assertListEqual(_snake_case,			_snake_case )






     def        lowercase_       (	self  :  Union[str, Any] )       ->Optional[Any]:
            snake_case__							:     str            =     self.get_feature_extractor()
            snake_case__							:     Dict            =     self.get_tokenizer()

            snake_case__							:     Any            =     WhisperProcessor(tokenizer=_snake_case,			feature_extractor=_snake_case )

            self.assertListEqual(
                processor.model_input_names,			feature_extractor.model_input_names,			msg='`processor` and `feature_extractor` model input names do not match',			)






     def        lowercase_       (	self  :  int )       ->Dict:
            snake_case__							:     Tuple            =     self.get_feature_extractor()
            snake_case__							:     Tuple            =     self.get_tokenizer()

            snake_case__							:     Optional[int]            =     WhisperProcessor(tokenizer=_snake_case,			feature_extractor=_snake_case )
            snake_case__							:     Any            =     processor.get_decoder_prompt_ids(task='transcribe',			no_timestamps=_snake_case )

            self.assertIsInstance(_snake_case,			_snake_case )
            for ids in forced_decoder_ids:
                   self.assertIsInstance(_snake_case,			(list, tuple) )

            snake_case__							:     List[str]            =     [TRANSCRIBE, NOTIMESTAMPS]
            self.assertListEqual([ids[-1] for ids in forced_decoder_ids],			_snake_case )






     def        lowercase_       (	self  :  Optional[int] )       ->int:
            snake_case__							:     List[Any]            =     WhisperProcessor(tokenizer=self.get_tokenizer(),			feature_extractor=self.get_feature_extractor() )
            snake_case__							:     Optional[Any]            =     processor.get_prompt_ids('Mr. Quilter' )
            snake_case__							:     List[Any]            =     processor.tokenizer.decode(_snake_case )

            self.assertListEqual(prompt_ids.tolist(),			[5_0_3_6_0, 1_7_7_0, 1_3, 2_2_6_4, 3_4_6, 3_5_3] )
            self.assertEqual(_snake_case,			'<|startofprev|> Mr. Quilter' )






     def        lowercase_       (	self  :  Tuple )       ->Tuple:
            snake_case__							:     int            =     WhisperProcessor(tokenizer=self.get_tokenizer(),			feature_extractor=self.get_feature_extractor() )
            snake_case__							:     List[str]            =     processor.get_prompt_ids('' )
            snake_case__							:     List[Any]            =     processor.tokenizer.decode(_snake_case )

            self.assertListEqual(prompt_ids.tolist(),			[5_0_3_6_0, 2_2_0] )
            self.assertEqual(_snake_case,			'<|startofprev|> ' )






     def        lowercase_       (	self  :  Tuple )       ->str:
            snake_case__							:     Any            =     WhisperProcessor(tokenizer=self.get_tokenizer(),			feature_extractor=self.get_feature_extractor() )

            def _test_prompt_error_raised_helper(_snake_case  :  str,			_snake_case  :  int ):
                   with pytest.raises(_snake_case ) as excinfo:
                          processor.get_prompt_ids(_snake_case )
                   snake_case__							:     Dict            =     F'''Encountered text in the prompt corresponding to disallowed special token: {special_token}.'''
                   self.assertEqual(_snake_case,			str(excinfo.value ) )

            _test_prompt_error_raised_helper('<|startofprev|> test',			'<|startofprev|>' )
            _test_prompt_error_raised_helper('test <|notimestamps|>',			'<|notimestamps|>' )
            _test_prompt_error_raised_helper('test <|zh|> test <|transcribe|>',			'<|zh|>' )






