




'''simple docstring'''
from typing import Any, Dict, List, Optional, Tuple, Union

import torch
from torch import nn
from torch.utils.data import DistributedSampler, RandomSampler

from transformers import PreTrainedModel, Trainer, logging
from transformers.integrations import is_fairscale_available
from transformers.models.fsmt.configuration_fsmt import FSMTConfig
from transformers.optimization import (
    Adafactor,
    AdamW,
    get_constant_schedule,
    get_constant_schedule_with_warmup,
    get_cosine_schedule_with_warmup,
    get_cosine_with_hard_restarts_schedule_with_warmup,
    get_linear_schedule_with_warmup,
    get_polynomial_decay_schedule_with_warmup,
)
from transformers.trainer_pt_utils import get_tpu_sampler
from transformers.training_args import ParallelMode
from transformers.utils import is_torch_tpu_available


if is_fairscale_available():
							from fairscale.optim import OSS


_SCREAMING_SNAKE_CASE			=						logging.get_logger(__name__)

_SCREAMING_SNAKE_CASE			=						{
    "linear": get_linear_schedule_with_warmup,
    "cosine": get_cosine_schedule_with_warmup,
    "cosine_w_restarts": get_cosine_with_hard_restarts_schedule_with_warmup,
    "polynomial": get_polynomial_decay_schedule_with_warmup,
    "constant": get_constant_schedule,
    "constant_w_warmup": get_constant_schedule_with_warmup,
}
class   __UpperCAmelCase				(     lowerCAmelCase				):



					'''simple docstring'''





					def __init__(	self     :						List[str]      ,       _lowercase     :						List[str]=None      ,       _lowercase     :						str=None      ,       *_lowercase     :						Dict      ,       **_lowercase     :						List[Any])    ->							Any:
								super().__init__(*_lowercase      ,       **_lowercase)

								if config is None:
											assert isinstance(self.model      ,       _lowercase), (
											    "If no `config` is passed the model to be trained has to be of type `PreTrainedModel`, but is"
											    F' {self.model.__class__}'
											)
											A_									= self.model.config
								else:
											A_									= config

								A_									= data_args
								A_									= self.config.tgt_vocab_size if isinstance(self.config      ,       _lowercase) else self.config.vocab_size

								if self.args.label_smoothing != 0 or (self.data_args is not None and self.data_args.ignore_pad_token_for_loss):
											assert self.config.pad_token_id is not None, (
											    "Make sure that `config.pad_token_id` is correcly defined when ignoring `pad_token` for loss"
											    " calculation or doing label smoothing."
											)

								if self.config.pad_token_id is None and self.config.eos_token_id is not None:
											logger.warning(
											    F'The `config.pad_token_id` is `None`. Using `config.eos_token_id` = {self.config.eos_token_id} for'
											    ' padding..')

								if self.args.label_smoothing == 0:
											A_									= torch.nn.CrossEntropyLoss(ignore_index=self.config.pad_token_id)
								else:
											# dynamically import label_smoothed_nll_loss
											from utils import label_smoothed_nll_loss

											A_									= label_smoothed_nll_loss



					def     __snake_case						(	self     :						Any      ,       _lowercase     :						int)    ->							Optional[int]:
								if self.optimizer is None:
											A_									= ['bias', 'LayerNorm.weight']
											A_									= [
											    {
											        'params': [p for n, p in self.model.named_parameters() if not any(nd in n for nd in no_decay)],
											        'weight_decay': self.args.weight_decay,
											    },
											    {
											        'params': [p for n, p in self.model.named_parameters() if any(nd in n for nd in no_decay)],
											        'weight_decay': 0.0,
											    },
											]
											A_									= Adafactor if self.args.adafactor else AdamW
											if self.args.adafactor:
														A_									= Adafactor
														A_									= {'scale_parameter': False, 'relative_step': False}
											else:
														A_									= AdamW
														A_									= {
														    'betas': (self.args.adam_betaa, self.args.adam_betaa),
														    'eps': self.args.adam_epsilon,
														}
											A_									= self.args.learning_rate
											if self.sharded_ddp:
														A_									= OSS(
														    params=_lowercase      ,       optim=_lowercase      ,       **_lowercase      ,       )
											else:
														A_									= optimizer_cls(_lowercase      ,       **_lowercase)

								if self.lr_scheduler is None:
											A_									= self._get_lr_scheduler(_lowercase)
								else:  # ignoring --lr_scheduler
											logger.warning('scheduler is passed to `Seq2SeqTrainer`, `--lr_scheduler` arg is ignored.')



					def     __snake_case						(	self     :						Optional[Any]      ,       _lowercase     :						Optional[int])    ->							str:
								A_									= arg_to_scheduler[self.args.lr_scheduler]
								if self.args.lr_scheduler == "constant":
											A_									= schedule_func(self.optimizer)
								elif self.args.lr_scheduler == "constant_w_warmup":
											A_									= schedule_func(self.optimizer      ,       num_warmup_steps=self.args.warmup_steps)
								else:
											A_									= schedule_func(
											    self.optimizer      ,       num_warmup_steps=self.args.warmup_steps      ,       num_training_steps=_lowercase)
								return scheduler



					def     __snake_case						(	self     :						str)    ->							Optional[torch.utils.data.Sampler]:
								if isinstance(self.train_dataset      ,       torch.utils.data.IterableDataset):
											return None
								elif is_torch_tpu_available():
											return get_tpu_sampler(self.train_dataset)
								else:
											if self.args.sortish_sampler:
														self.train_dataset.make_sortish_sampler(
														    self.args.per_device_train_batch_size      ,       distributed=(self.args.parallel_mode == ParallelMode.DISTRIBUTED)      ,       )

											return (
											    RandomSampler(self.train_dataset)
											    if self.args.local_rank == -1
											    else DistributedSampler(self.train_dataset)
											)



					def     __snake_case						(	self     :						str      ,       _lowercase     :						str      ,       _lowercase     :						List[Any]      ,       _lowercase     :						Dict)    ->							Any:
								if self.args.label_smoothing == 0:
											if self.data_args is not None and self.data_args.ignore_pad_token_for_loss:
														# force training to ignore pad token
														A_									= model(**_lowercase      ,       use_cache=_lowercase)[0]
														A_									= self.loss_fn(logits.view(-1      ,       logits.shape[-1])      ,       labels.view(-1))
											else:
														# compute usual loss via models
														A_		, A_									= model(**_lowercase      ,       labels=_lowercase      ,       use_cache=_lowercase)[:2]
								else:
											# compute label smoothed loss
											A_									= model(**_lowercase      ,       use_cache=_lowercase)[0]
											A_									= torch.nn.functional.log_softmax(_lowercase      ,       dim=-1)
											A_		, A_									= self.loss_fn(_lowercase      ,       _lowercase      ,       self.args.label_smoothing      ,       ignore_index=self.config.pad_token_id)
								return loss, logits



					def     __snake_case						(	self     :						List[Any]      ,       _lowercase     :						Dict      ,       _lowercase     :						Tuple)    ->							Optional[int]:
								A_									= inputs.pop('labels')
								A_		, A_									= self._compute_loss(_lowercase      ,       _lowercase      ,       _lowercase)
								return loss



					def     __snake_case						(	self     :						Optional[Any]      ,       _lowercase     :						nn.Module      ,       _lowercase     :						Dict[str, Union[torch.Tensor, Any]]      ,       _lowercase     :						bool      ,       _lowercase     :						Optional[List[str]] = None      ,       )    ->							Tuple[Optional[float], Optional[torch.Tensor], Optional[torch.Tensor]]:
								A_									= self._prepare_inputs(_lowercase)

								A_									= {
								    'max_length': self.data_args.val_max_target_length
								    if self.data_args is not None
								    else self.config.max_length,
								    'num_beams': self.data_args.eval_beams if self.data_args is not None else self.config.num_beams,
								}

								if self.args.predict_with_generate and not self.args.prediction_loss_only:
											A_									= self.model.generate(
											    inputs['input_ids']      ,       attention_mask=inputs['attention_mask']      ,       **_lowercase      ,       )
											# in case the batch is shorter than max length, the output should be padded
											if generated_tokens.shape[-1] < gen_kwargs["max_length"]:
														A_									= self._pad_tensors_to_max_len(_lowercase      ,       gen_kwargs['max_length'])

								A_									= inputs.pop('labels')
								with torch.no_grad():
											# compute loss on predict data
											A_		, A_									= self._compute_loss(_lowercase      ,       _lowercase      ,       _lowercase)

								A_									= loss.mean().detach()
								if self.args.prediction_loss_only:
											return (loss, None, None)

								A_									= generated_tokens if self.args.predict_with_generate else logits

								if labels.shape[-1] < gen_kwargs["max_length"]:
											A_									= self._pad_tensors_to_max_len(_lowercase      ,       gen_kwargs['max_length'])

								return (loss, logits, labels)



					def     __snake_case						(	self     :						List[str]      ,       _lowercase     :						Any      ,       _lowercase     :						int)    ->							str:
								# If PAD token is not defined at least EOS token has to be defined
								A_									= self.config.pad_token_id if self.config.pad_token_id is not None else self.config.eos_token_id

								if pad_token_id is None:
											raise ValueError(
											    'Make sure that either `config.pad_token_id` or `config.eos_token_id` is defined if tensor has to be'
											    F' padded to `max_length`={max_length}')

								A_									= pad_token_id * torch.ones(
								    (tensor.shape[0], max_length)      ,       dtype=tensor.dtype      ,       device=tensor.device)
								A_									= tensor
								return padded_tensor










'''simple docstring'''
import re
import time
from typing import Optional

import IPython.display as disp

from ..trainer_callback import TrainerCallback
from ..trainer_utils import IntervalStrategy, has_length





def 			lowerCamelCase(							SCREAMING_SNAKE_CASE_     )		->		str:
			A_									= int(SCREAMING_SNAKE_CASE_     )
			A_		, A_		, A_									= t // 3600, (t // 60) % 60, t % 60
			return F'{h}:{m:02d}:{s:02d}' if h != 0 else F'{m:02d}:{s:02d}'





def 			lowerCamelCase(							SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_=300     )		->		Dict:
			# docstyle-ignore
			return F'\n    <div>\n      {prefix}\n      <progress value=\'{value}\' max=\'{total}\' style=\'width:{width}px; height:20px; vertical-align: middle;\'></progress>\n      {label}\n    </div>\n    '





def 			lowerCamelCase(							SCREAMING_SNAKE_CASE_     )		->		List[str]:
			A_									= '<table border="1" class="dataframe">\n'
			html_code += """  <thead>\n <tr style="text-align: left;">\n"""
			for i in items[0]:
						html_code += F'      <th>{i}</th>\n'
			html_code += "    </tr>\n  </thead>\n  <tbody>\n"
			for line in items[1:]:
						html_code += "    <tr>\n"
						for elt in line:
									A_									= F'{elt:.6f}' if isinstance(SCREAMING_SNAKE_CASE_       ,SCREAMING_SNAKE_CASE_     ) else str(SCREAMING_SNAKE_CASE_     )
									html_code += F'      <td>{elt}</td>\n'
						html_code += "    </tr>\n"
			html_code += "  </tbody>\n</table><p>"
			return html_code
class   __UpperCAmelCase				:



					'''simple docstring'''





					_UpperCamelCase							=		5
					_UpperCamelCase							=		0.2



					def __init__(	self     :						Tuple      ,       _lowercase     :						int      ,       _lowercase     :						Optional[str] = None      ,       _lowercase     :						bool = True      ,       _lowercase     :						Optional["NotebookTrainingTracker"] = None      ,       _lowercase     :						int = 300      ,       )    ->							Dict:
								A_									= total
								A_									= '' if prefix is None else prefix
								A_									= leave
								A_									= parent
								A_									= width
								A_									= None
								A_									= None
								A_									= None



					def     __snake_case						(	self     :						Optional[int]      ,       _lowercase     :						int      ,       _lowercase     :						bool = False      ,       _lowercase     :						str = None)    ->							Dict:
								A_									= value
								if comment is not None:
											A_									= comment
								if self.last_value is None:
											A_									= A_									= time.time()
											A_									= A_									= value
											A_									= A_									= None
											A_									= self.warmup
											A_									= 1
											self.update_bar(_lowercase)
								elif value <= self.last_value and not force_update:
											return
								elif force_update or self.first_calls > 0 or value >= min(self.last_value + self.wait_for      ,       self.total):
											if self.first_calls > 0:
														self.first_calls -= 1
											A_									= time.time()
											A_									= current_time - self.start_time
											# We could have value = self.start_value if the update is called twixe with the same start value.
											if value > self.start_value:
														A_									= self.elapsed_time / (value - self.start_value)
											else:
														A_									= None
											if value >= self.total:
														A_									= self.total
														A_									= None
														if not self.leave:
																	self.close()
											elif self.average_time_per_item is not None:
														A_									= self.average_time_per_item * (self.total - value)
											self.update_bar(_lowercase)
											A_									= value
											A_									= current_time
											if self.average_time_per_item is None:
														A_									= 1
											else:
														A_									= max(int(self.update_every / self.average_time_per_item)      ,       1)



					def     __snake_case						(	self     :						str      ,       _lowercase     :						List[Any]      ,       _lowercase     :						Optional[int]=None)    ->							str:
								A_									= ' ' * (len(str(self.total)) - len(str(_lowercase))) + str(_lowercase)
								if self.elapsed_time is None:
											A_									= F'[{spaced_value}/{self.total} : < :'
								elif self.predicted_remaining is None:
											A_									= F'[{spaced_value}/{self.total} {format_time(self.elapsed_time)}'
								else:
											A_									= (
											    F'[{spaced_value}/{self.total} {format_time(self.elapsed_time)} <'
											    F' {format_time(self.predicted_remaining)}'
											)
											self.label += F', {1/self.average_time_per_item:.2f} it/s'
								self.label += "]" if self.comment is None or len(self.comment) == 0 else F', {self.comment}]'
								self.display()



					def     __snake_case						(	self     :						Optional[int])    ->							Dict:
								A_									= html_progress_bar(self.value      ,       self.total      ,       self.prefix      ,       self.label      ,       self.width)
								if self.parent is not None:
											# If this is a child bar, the parent will take care of the display.
											self.parent.display()
											return
								if self.output is None:
											A_									= disp.display(disp.HTML(self.html_code)      ,       display_id=_lowercase)
								else:
											self.output.update(disp.HTML(self.html_code))



					def     __snake_case						(	self     :						List[Any])    ->							Optional[Any]:
								if self.parent is None and self.output is not None:
											self.output.update(disp.HTML(''))





class   __UpperCAmelCase				(     lowerCAmelCase				):



					'''simple docstring'''





					def __init__(	self     :						int      ,       _lowercase     :						Union[str, Any]      ,       _lowercase     :						str=None)    ->							str:
								super().__init__(_lowercase)
								A_									= None if column_names is None else [column_names]
								A_									= None



					def     __snake_case						(	self     :						Dict)    ->							List[Any]:
								A_									= html_progress_bar(self.value      ,       self.total      ,       self.prefix      ,       self.label      ,       self.width)
								if self.inner_table is not None:
											self.html_code += text_to_html_table(self.inner_table)
								if self.child_bar is not None:
											self.html_code += self.child_bar.html_code
								if self.output is None:
											A_									= disp.display(disp.HTML(self.html_code)      ,       display_id=_lowercase)
								else:
											self.output.update(disp.HTML(self.html_code))



					def     __snake_case						(	self     :						str      ,       _lowercase     :						int)    ->							Optional[int]:
								if self.inner_table is None:
											A_									= [list(values.keys()), list(values.values())]
								else:
											A_									= self.inner_table[0]
											if len(self.inner_table) == 1:
														# We give a chance to update the column names at the first iteration
														for key in values.keys():
																	if key not in columns:
																				columns.append(_lowercase)
														A_									= columns
											self.inner_table.append([values[c] for c in columns])



					def     __snake_case						(	self     :						List[Any]      ,       _lowercase     :						Union[str, Any]      ,       _lowercase     :						str=None      ,       _lowercase     :						Optional[int]=300)    ->							Dict:
								A_									= NotebookProgressBar(_lowercase      ,       prefix=_lowercase      ,       parent=self      ,       width=_lowercase)
								return self.child_bar



					def     __snake_case						(	self     :						Any)    ->							int:
								A_									= None
								self.display()





class   __UpperCAmelCase				(     lowerCAmelCase				):



					'''simple docstring'''





					def __init__(	self     :						Dict)    ->							Tuple:
								A_									= None
								A_									= None
								A_									= False



					def     __snake_case						(	self     :						int      ,       _lowercase     :						str      ,       _lowercase     :						str      ,       _lowercase     :						str      ,       **_lowercase     :						List[Any])    ->							List[Any]:
								A_									= 'Epoch' if args.evaluation_strategy == IntervalStrategy.EPOCH else 'Step'
								A_									= 0
								A_									= 0
								A_									= [self.first_column] + ['Training Loss']
								if args.evaluation_strategy != IntervalStrategy.NO:
											column_names.append('Validation Loss')
								A_									= NotebookTrainingTracker(state.max_steps      ,       _lowercase)



					def     __snake_case						(	self     :						Tuple      ,       _lowercase     :						Union[str, Any]      ,       _lowercase     :						List[Any]      ,       _lowercase     :						List[str]      ,       **_lowercase     :						Union[str, Any])    ->							str:
								A_									= int(state.epoch) if int(state.epoch) == state.epoch else F'{state.epoch:.2f}'
								self.training_tracker.update(
								    state.global_step + 1      ,       comment=F'Epoch {epoch}/{state.num_train_epochs}'      ,       force_update=self._force_next_update      ,       )
								A_									= False



					def     __snake_case						(	self     :						Union[str, Any]      ,       _lowercase     :						Any      ,       _lowercase     :						int      ,       _lowercase     :						Optional[int]      ,       _lowercase     :						List[Any]=None      ,       **_lowercase     :						Any)    ->							Union[str, Any]:
								if not has_length(_lowercase):
											return
								if self.prediction_bar is None:
											if self.training_tracker is not None:
														A_									= self.training_tracker.add_child(len(_lowercase))
											else:
														A_									= NotebookProgressBar(len(_lowercase))
											self.prediction_bar.update(1)
								else:
											self.prediction_bar.update(self.prediction_bar.value + 1)



					def     __snake_case						(	self     :						List[Any]      ,       _lowercase     :						List[str]      ,       _lowercase     :						Any      ,       _lowercase     :						Union[str, Any]      ,       **_lowercase     :						Optional[int])    ->							Optional[Any]:
								if self.prediction_bar is not None:
											self.prediction_bar.close()
								A_									= None



					def     __snake_case						(	self     :						Dict      ,       _lowercase     :						Dict      ,       _lowercase     :						str      ,       _lowercase     :						str      ,       _lowercase     :						Optional[Any]=None      ,       **_lowercase     :						Dict)    ->							Optional[int]:
								# Only for when there is no evaluation
								if args.evaluation_strategy == IntervalStrategy.NO and "loss" in logs:
											A_									= {'Training Loss': logs['loss']}
											# First column is necessarily Step sine we're not in epoch eval strategy
											A_									= state.global_step
											self.training_tracker.write_line(_lowercase)



					def     __snake_case						(	self     :						List[Any]      ,       _lowercase     :						Any      ,       _lowercase     :						Optional[int]      ,       _lowercase     :						str      ,       _lowercase     :						Optional[Any]=None      ,       **_lowercase     :						Union[str, Any])    ->							Union[str, Any]:
								if self.training_tracker is not None:
											A_									= {'Training Loss': 'No log', 'Validation Loss': 'No log'}
											for log in reversed(state.log_history):
														if "loss" in log:
																	A_									= log['loss']
																	break

											if self.first_column == "Epoch":
														A_									= int(state.epoch)
											else:
														A_									= state.global_step
											A_									= 'eval'
											for k in metrics:
														if k.endswith('_loss'):
																	A_									= re.sub(r'\_loss$'      ,       ''      ,       _lowercase)
											A_									= metrics.pop('total_flos'      ,       _lowercase)
											A_									= metrics.pop('epoch'      ,       _lowercase)
											A_									= metrics.pop(F'{metric_key_prefix}_runtime'      ,       _lowercase)
											A_									= metrics.pop(F'{metric_key_prefix}_samples_per_second'      ,       _lowercase)
											A_									= metrics.pop(F'{metric_key_prefix}_steps_per_second'      ,       _lowercase)
											A_									= metrics.pop(F'{metric_key_prefix}_jit_compilation_time'      ,       _lowercase)
											for k, v in metrics.items():
														if k == F'{metric_key_prefix}_loss':
																	A_									= v
														else:
																	A_									= k.split('_')
																	A_									= ' '.join([part.capitalize() for part in splits[1:]])
																	A_									= v
											self.training_tracker.write_line(_lowercase)
											self.training_tracker.remove_child()
											A_									= None
											# Evaluation takes a long time so we should force the next update.
											A_									= True



					def     __snake_case						(	self     :						Tuple      ,       _lowercase     :						Dict      ,       _lowercase     :						str      ,       _lowercase     :						List[str]      ,       **_lowercase     :						str)    ->							Optional[int]:
								self.training_tracker.update(
								    state.global_step      ,       comment=F'Epoch {int(state.epoch)}/{state.num_train_epochs}'      ,       force_update=_lowercase)
								A_									= None




