


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 			lowerCAmelCase__(     snake_case__    ):






    '''simple docstring'''





    def __init__(						self					: Optional[int]							, __snake_case					: Optional[Any]							, __snake_case					: Optional[int]							, __snake_case					: List[Any]=False							, __snake_case					: List[str]=1_024							, __snake_case					: int=1_024							, __snake_case					: Tuple=3.6							, __snake_case					: List[str]=False							, ):





       '''simple docstring'''
       UpperCAmelCase_				:   Optional[int]							= tokenizer
       UpperCAmelCase_				:   List[Any]							= tokenizer.bos_token_id
       UpperCAmelCase_				:   Any							= dataset
       UpperCAmelCase_				:   Optional[int]							= seq_length
       UpperCAmelCase_				:   List[Any]							= 0
       UpperCAmelCase_				:   Any							= infinite
       UpperCAmelCase_				:   int							= 0
       UpperCAmelCase_				:   List[str]							= tokenized

       if self.tokenized:
          UpperCAmelCase_				:   str							= seq_length * num_of_sequences
          UpperCAmelCase_				:   str							= '''input_ids'''
       else:
          UpperCAmelCase_				:   Optional[int]							= seq_length * chars_per_token * num_of_sequences
          UpperCAmelCase_				:   Union[str, Any]							= '''content'''





    def __iter__(						self					: int						):





       '''simple docstring'''
       UpperCAmelCase_				:   List[str]							= iter(self.dataset						)
       UpperCAmelCase_				:   Optional[int]							= True
       while more_examples:
          UpperCAmelCase_		,   UpperCAmelCase_				:   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:
                   UpperCAmelCase_				:   Any							= iter(self.dataset						)
                   self.epoch += 1
                   logger.info(f'''Dataset epoch: {self.epoch}'''						)
                else:
                   UpperCAmelCase_				:   Dict							= False
                   break
          if self.tokenized:
             UpperCAmelCase_				:   List[Any]							= buffer
          else:
             UpperCAmelCase_				:   Tuple							= self.tokenizer(__snake_case							, truncation=__snake_case						)['''input_ids''']
          UpperCAmelCase_				:   Union[str, Any]							= []
          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						):
             UpperCAmelCase_				:   Union[str, Any]							= 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        _lowerCamelCase			(						self					: Any							, __snake_case					: List[str]=1_000						):





       '''simple docstring'''
       return ShufflerIterDataPipe(self							, buffer_size=__snake_case						)





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


# Settings
__UpperCamelCase					:	int          =				HfArgumentParser(TrainingArguments)
__UpperCamelCase					:	int          =				parser.parse_args()

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

__UpperCamelCase					:	Tuple          =				Namespace(**vars(args), **acc_state)
__UpperCamelCase					:	int          =				accelerator.state.num_processes * args.train_batch_size
set_seed(args.seed)

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

# Logging
__UpperCamelCase       ,       __UpperCamelCase					:	Dict          =				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
__UpperCamelCase					:	List[str]          =				AutoModelForCausalLM.from_pretrained(args.save_dir)
if args.gradient_checkpointing:
       model.gradient_checkpointing_enable()
__UpperCamelCase					:	List[str]          =				AutoTokenizer.from_pretrained(args.save_dir)

# Load dataset and dataloader
__UpperCamelCase       ,       __UpperCamelCase					:	Tuple          =				create_dataloaders(args)

# Prepare the optimizer and learning rate scheduler
__UpperCamelCase					:	int          =				AdamW(get_grouped_params(model, args), lr=args.learning_rate)
__UpperCamelCase					:	Dict          =				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   snake_case_    (			):
   return optimizer.param_groups[0]["lr"]


# Prepare everything with our `accelerator`.
__UpperCamelCase       ,       __UpperCamelCase       ,       __UpperCamelCase       ,       __UpperCamelCase					:	List[str]          =				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)
              __UpperCamelCase					:	Optional[int]          =				os.path.basename(args.resume_from_checkpoint)
       else:
              # Get the most recent checkpoint
              __UpperCamelCase					:	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)
              __UpperCamelCase					:	List[Any]          =				dirs[-1]  # Sorts folders by date modified, most recent checkpoint is the last
       # Extract the step of the checkpoint to continue from there
       __UpperCamelCase					:	Tuple          =				os.path.splitext(path)[0]
       __UpperCamelCase					:	str          =				int(training_difference.replace('step_', ''))

# Train model
model.train()
__UpperCamelCase					:	List[Any]          =				0
__UpperCamelCase					:	List[Any]          =				time.time()
__UpperCamelCase					:	List[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
       __UpperCamelCase					:	Optional[int]          =				model(batch, labels=batch, use_cache=False).loss
       __UpperCamelCase					:	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()})
       __UpperCamelCase					:	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:
              __UpperCamelCase					:	List[str]          =				get_lr()
              accelerator.backward(loss)
              accelerator.clip_grad_norm_(model.parameters(), 1.0)
              optimizer.step()
              lr_scheduler.step()
              optimizer.zero_grad()
              __UpperCamelCase					:	List[Any]          =				time.time() - t_start
              __UpperCamelCase					:	List[Any]          =				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,
                  },
              )
              __UpperCamelCase					:	int          =				time.time()
              __UpperCamelCase					:	int          =				0
              completed_steps += 1
       if step % args.save_checkpoint_steps == 0:
              logger.info('Evaluating and saving model checkpoint')
              __UpperCamelCase       ,       __UpperCamelCase					:	str          =				evaluate(args)
              log_metrics(step, {'loss/eval': eval_loss, 'perplexity': perplexity})
              accelerator.wait_for_everyone()
              __UpperCamelCase					:	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')
__UpperCamelCase       ,       __UpperCamelCase					:	List[Any]          =				evaluate(args)
log_metrics(step, {'loss/eval': eval_loss, 'perplexity': perplexity})
accelerator.wait_for_everyone()
__UpperCamelCase					:	List[str]          =				accelerator.unwrap_model(model)
unwrapped_model.save_pretrained(args.save_dir, save_function=accelerator.save)
__UpperCamelCase					:	str          =				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 os
import random
from pathlib import Path
from typing import List

import numpy as np
import torch
from torch.cuda.amp import GradScaler

from .utils import (
    MODEL_NAME,
    OPTIMIZER_NAME,
    RNG_STATE_NAME,
    SCALER_NAME,
    SCHEDULER_NAME,
    get_pretty_name,
    is_tpu_available,
    is_xpu_available,
    save,
)


if is_tpu_available(check_device=False):
       import torch_xla.core.xla_model as xm

from .logging import get_logger
from .state import PartialState


__UpperCamelCase					:	int          =				get_logger(__name__)
def   snake_case_    (			__lowercase      ,							__lowercase      ,							__lowercase      ,							__lowercase      ,							__lowercase      ,							__lowercase = None      ,							):
   # Model states
   for i, state in enumerate(__lowercase							):
      UpperCAmelCase_				:   Dict							= F'''{MODEL_NAME}.bin''' if i == 0 else F'''{MODEL_NAME}_{i}.bin'''
      UpperCAmelCase_				:   List[Any]							= os.path.join(__lowercase      ,							__lowercase							)
      save(__lowercase      ,							__lowercase							)
      logger.info(F'''Model weights saved in {output_model_file}'''							)
   # Optimizer states
   for i, opt in enumerate(__lowercase							):
      UpperCAmelCase_				:   Tuple							= opt.state_dict()
      UpperCAmelCase_				:   Any							= F'''{OPTIMIZER_NAME}.bin''' if i == 0 else F'''{OPTIMIZER_NAME}_{i}.bin'''
      UpperCAmelCase_				:   List[Any]							= os.path.join(__lowercase      ,							__lowercase							)
      save(__lowercase      ,							__lowercase							)
      logger.info(F'''Optimizer state saved in {output_optimizer_file}'''							)
   # Scheduler states
   for i, scheduler in enumerate(__lowercase							):
      UpperCAmelCase_				:   Tuple							= scheduler.state_dict()
      UpperCAmelCase_				:   Tuple							= F'''{SCHEDULER_NAME}.bin''' if i == 0 else F'''{SCHEDULER_NAME}_{i}.bin'''
      UpperCAmelCase_				:   Tuple							= os.path.join(__lowercase      ,							__lowercase							)
      save(__lowercase      ,							__lowercase							)
      logger.info(F'''Scheduler state saved in {output_scheduler_file}'''							)
   # GradScaler state
   if scaler is not None:
      UpperCAmelCase_				:   Union[str, Any]							= scaler.state_dict()
      UpperCAmelCase_				:   Union[str, Any]							= os.path.join(__lowercase      ,							__lowercase							)
      torch.save(__lowercase      ,							__lowercase							)
      logger.info(F'''Gradient scaler state saved in {output_scaler_file}'''							)
   # Random number generator states
   UpperCAmelCase_				:   Union[str, Any]							= {}
   UpperCAmelCase_				:   Tuple							= F'''{RNG_STATE_NAME}_{process_index}.pkl'''
   UpperCAmelCase_				:   List[Any]							= random.getstate()
   UpperCAmelCase_				:   Any							= np.random.get_state()
   UpperCAmelCase_				:   List[Any]							= torch.get_rng_state()
   if is_xpu_available():
      UpperCAmelCase_				:   Optional[int]							= torch.xpu.get_rng_state_all()
   else:
      UpperCAmelCase_				:   Any							= torch.cuda.get_rng_state_all()
   if is_tpu_available():
      UpperCAmelCase_				:   List[str]							= xm.get_rng_state()
   UpperCAmelCase_				:   Any							= os.path.join(__lowercase      ,							__lowercase							)
   torch.save(__lowercase      ,							__lowercase							)
   logger.info(F'''Random states saved in {output_states_file}'''							)
   return output_dir
def   snake_case_    (			__lowercase      ,							__lowercase      ,							__lowercase      ,							__lowercase      ,							__lowercase      ,							__lowercase=None      ,							__lowercase=None      ,							**__lowercase      ,							):
   if map_location not in [None, "cpu", "on_device"]:
      raise TypeError(
          '''Unsupported optimizer map location passed, please choose one of `None`, `\'cpu\'`, or `\'on_device\'`'''							)
   if map_location is None:
      UpperCAmelCase_				:   Optional[Any]							= '''cpu'''
   elif map_location == "on_device":
      UpperCAmelCase_				:   Optional[int]							= PartialState().device
   # Model states
   for i, model in enumerate(__lowercase							):
      UpperCAmelCase_				:   List[Any]							= F'''{MODEL_NAME}.bin''' if i == 0 else F'''{MODEL_NAME}_{i}.bin'''
      UpperCAmelCase_				:   int							= os.path.join(__lowercase      ,							__lowercase							)
      models[i].load_state_dict(torch.load(__lowercase      ,							map_location=__lowercase							)      ,							**__lowercase							)
   logger.info('''All model weights loaded successfully'''							)

   # Optimizer states
   for i, opt in enumerate(__lowercase							):
      UpperCAmelCase_				:   List[str]							= F'''{OPTIMIZER_NAME}.bin''' if i == 0 else F'''{OPTIMIZER_NAME}_{i}.bin'''
      UpperCAmelCase_				:   List[Any]							= os.path.join(__lowercase      ,							__lowercase							)
      UpperCAmelCase_				:   Tuple							= torch.load(__lowercase      ,							map_location=__lowercase							)
      optimizers[i].load_state_dict(__lowercase							)
   logger.info('''All optimizer states loaded successfully'''							)

   # Scheduler states
   for i, scheduler in enumerate(__lowercase							):
      UpperCAmelCase_				:   Dict							= F'''{SCHEDULER_NAME}.bin''' if i == 0 else F'''{SCHEDULER_NAME}_{i}.bin'''
      UpperCAmelCase_				:   int							= os.path.join(__lowercase      ,							__lowercase							)
      scheduler.load_state_dict(torch.load(__lowercase							)							)
   logger.info('''All scheduler states loaded successfully'''							)

   # GradScaler state
   if scaler is not None:
      UpperCAmelCase_				:   List[str]							= os.path.join(__lowercase      ,							__lowercase							)
      scaler.load_state_dict(torch.load(__lowercase							)							)
      logger.info('''GradScaler state loaded successfully'''							)

   # Random states
   try:
      UpperCAmelCase_				:   Optional[Any]							= torch.load(os.path.join(__lowercase      ,							F'''{RNG_STATE_NAME}_{process_index}.pkl'''							)							)
      random.setstate(states['''random_state''']							)
      np.random.set_state(states['''numpy_random_seed''']							)
      torch.set_rng_state(states['''torch_manual_seed''']							)
      if is_xpu_available():
         torch.xpu.set_rng_state_all(states['''torch_xpu_manual_seed''']							)
      else:
         torch.cuda.set_rng_state_all(states['''torch_cuda_manual_seed''']							)
      if is_tpu_available():
         xm.set_rng_state(states['''xm_seed''']							)
      logger.info('''All random states loaded successfully'''							)
   except Exception:
      logger.info('''Could not load random states'''							)
def   snake_case_    (			__lowercase      ,							__lowercase      ,							__lowercase = 0							):
   UpperCAmelCase_				:   Optional[int]							= Path(__lowercase							) / F'''custom_checkpoint_{index}.pkl'''
   logger.info(F'''Saving the state of {get_pretty_name(__lowercase							)} to {save_location}'''							)
   torch.save(obj.state_dict()      ,							__lowercase							)


def   snake_case_    (			__lowercase      ,							__lowercase      ,							__lowercase = 0							):
   UpperCAmelCase_				:   Dict							= F'''{path}/custom_checkpoint_{index}.pkl'''
   logger.info(F'''Loading the state of {get_pretty_name(__lowercase							)} from {load_location}'''							)
   obj.load_state_dict(torch.load(__lowercase      ,							map_location='''cpu'''							)							)