text
stringlengths
1
1.02k
class_index
int64
0
10.8k
source
stringlengths
85
188
class ExportableState: """ A class for objects that include the ability to have its state be saved during `Trainer._save_checkpoint` and loaded back in during `Trainer._load_from_checkpoint`. These must implement a `state` function that gets called during the respective Trainer function call. I...
253
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
def state(self) -> dict: return { "args": { "early_stopping_patience": self.early_stopping_patience, "early_stopping_threshold": self.early_stopping_threshold, }, "attributes": { "early_stopping_patie...
253
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
class TrainerControl(ExportableState): """ A class that handles the [`Trainer`] control flow. This class is used by the [`TrainerCallback`] to activate some switches in the training loop. Args: should_training_stop (`bool`, *optional*, defaults to `False`): Whether or not the traini...
254
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
If `True`, this variable will be set back to `False` at the beginning of the next step. should_evaluate (`bool`, *optional*, defaults to `False`): Whether or not the model should be evaluated at this step. If `True`, this variable will be set back to `False` at the beginning of the next...
254
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
def _new_epoch(self): """Internal method that resets the variable for a new epoch.""" self.should_epoch_stop = False def _new_step(self): """Internal method that resets the variable for a new step.""" self.should_save = False self.should_evaluate = False self.should_...
254
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
class TrainerCallback: # no-format """ A class for objects that will inspect the state of the training loop at some events and take some decisions. At each of those events the following arguments are available:
255
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
Args: args ([`TrainingArguments`]): The training arguments used to instantiate the [`Trainer`]. state ([`TrainerState`]): The current state of the [`Trainer`]. control ([`TrainerControl`]): The object that is returned to the [`Trainer`] and can be used to make...
255
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
The scheduler used for setting the learning rate. train_dataloader (`torch.utils.data.DataLoader`, *optional*): The current dataloader used for training. eval_dataloader (`torch.utils.data.DataLoader`, *optional*): The current dataloader used for evaluation. metrics (`Dic...
255
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
Those are only accessible in the event `on_evaluate`. logs (`Dict[str, float]`): The values to log. Those are only accessible in the event `on_log`. The `control` object is the only one that can be changed by the callback, in which case the event that changes it should return ...
255
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
def on_init_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): """ Event called at the end of the initialization of the [`Trainer`]. """ pass def on_train_begin(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kw...
255
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
def on_step_begin(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): """ Event called at the beginning of a training step. If using gradient accumulation, one training step might take several inputs. """ pass def on_pre_optimizer_step(sel...
255
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
def on_substep_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): """ Event called at the end of an substep during gradient accumulation. """ pass def on_step_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **...
255
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
def on_save(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): """ Event called after a checkpoint save. """ pass def on_log(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): """ Event called ...
255
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
class CallbackHandler(TrainerCallback): """Internal class that just calls the list of callbacks in order.""" def __init__(self, callbacks, model, processing_class, optimizer, lr_scheduler): self.callbacks = [] for cb in callbacks: self.add_callback(cb) self.model = model ...
256
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
def add_callback(self, callback): cb = callback() if isinstance(callback, type) else callback cb_class = callback if isinstance(callback, type) else callback.__class__ if cb_class in [c.__class__ for c in self.callbacks]: logger.warning( f"You are adding a {cb_class} ...
256
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
def remove_callback(self, callback): if isinstance(callback, type): for cb in self.callbacks: if isinstance(cb, callback): self.callbacks.remove(cb) return else: self.callbacks.remove(callback) @property def callbac...
256
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
def on_epoch_begin(self, args: TrainingArguments, state: TrainerState, control: TrainerControl): control.should_epoch_stop = False return self.call_event("on_epoch_begin", args, state, control) def on_epoch_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl): re...
256
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
def on_optimizer_step(self, args: TrainingArguments, state: TrainerState, control: TrainerControl): return self.call_event("on_optimizer_step", args, state, control) def on_substep_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl): return self.call_event("on_substep_e...
256
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
def on_save(self, args: TrainingArguments, state: TrainerState, control: TrainerControl): control.should_save = False return self.call_event("on_save", args, state, control) def on_log(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, logs): control.should_log = F...
256
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
def call_event(self, event, args, state, control, **kwargs): for callback in self.callbacks: result = getattr(callback, event)( args, state, control, model=self.model, processing_class=self.processing_class, ...
256
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
class DefaultFlowCallback(TrainerCallback): """ A [`TrainerCallback`] that handles the default flow of the training loop for logs, evaluation and checkpoints. """ def on_step_end(self, args: TrainingArguments, state: TrainerState, control: TrainerControl, **kwargs): # Log if state.globa...
257
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
# Save if ( args.save_strategy == SaveStrategy.STEPS and state.save_steps > 0 and state.global_step % state.save_steps == 0 ): control.should_save = True # End training if state.global_step >= state.max_steps: control.should_tr...
257
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
# Save if args.save_strategy == SaveStrategy.EPOCH: control.should_save = True return control
257
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
class ProgressCallback(TrainerCallback): """ A [`TrainerCallback`] that displays the progress of training or evaluation. You can modify `max_str_len` to control how long strings are truncated when logging. """ def __init__(self, max_str_len: int = 100): """ Initialize the callback w...
258
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
def on_step_end(self, args, state, control, **kwargs): if state.is_world_process_zero: self.training_bar.update(state.global_step - self.current_step) self.current_step = state.global_step def on_prediction_step(self, args, state, control, eval_dataloader=None, **kwargs): if...
258
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
def on_predict(self, args, state, control, **kwargs): if state.is_world_process_zero: if self.prediction_bar is not None: self.prediction_bar.close() self.prediction_bar = None
258
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
def on_log(self, args, state, control, logs=None, **kwargs): if state.is_world_process_zero and self.training_bar is not None: # make a shallow copy of logs so we can mutate the fields copied # but avoid doing any value pickling. shallow_logs = {} for k, v in logs...
258
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
def on_train_end(self, args, state, control, **kwargs): if state.is_world_process_zero: self.training_bar.close() self.training_bar = None
258
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
class PrinterCallback(TrainerCallback): """ A bare [`TrainerCallback`] that just prints the logs. """ def on_log(self, args, state, control, logs=None, **kwargs): _ = logs.pop("total_flos", None) if state.is_local_process_zero: print(logs)
259
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
class EarlyStoppingCallback(TrainerCallback, ExportableState): """ A [`TrainerCallback`] that handles early stopping. Args: early_stopping_patience (`int`): Use with `metric_for_best_model` to stop training when the specified metric worsens for `early_stopping_patience` eval...
260
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
def __init__(self, early_stopping_patience: int = 1, early_stopping_threshold: Optional[float] = 0.0): self.early_stopping_patience = early_stopping_patience self.early_stopping_threshold = early_stopping_threshold # early_stopping_patience_counter denotes the number of times validation metrics ...
260
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
def on_train_begin(self, args, state, control, **kwargs): if not args.load_best_model_at_end: logger.warning( "Using EarlyStoppingCallback without load_best_model_at_end=True. " "Once training is finished, the best model will not be loaded automatically." ...
260
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
if metric_value is None: logger.warning( f"early stopping required metric_for_best_model, but did not find {metric_to_check} so early stopping" " is disabled" ) return self.check_metric_value(args, state, control, metric_value) if self...
260
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
class DistributedSamplerWithLoop(DistributedSampler): """ Like a torch.utils.data.distributed.DistributedSampler` but loops at the end back to the beginning of the shuffled samples to make each process have a round multiple of batch_size samples. Args: dataset (`torch.utils.data.Dataset`): ...
261
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
def __iter__(self): indices = list(super().__iter__()) remainder = 0 if len(indices) % self.batch_size == 0 else self.batch_size - len(indices) % self.batch_size # DistributedSampler already added samples from the beginning to make the number of samples a round multiple # of the world si...
261
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
class EvalLoopContainer: """ Container to store intermediate results of evaluation loop Args: do_nested_concat (`bool`, *optional*, defaults to `True`): If set to `True`, each iteration will recursively concatenate a new object containing tensors to the existing stored tenso...
262
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
def add(self, tensors) -> None: """Add tensors to the stored objects. If `do_nested_concat=True`, the tensors will be concatenated recursively.""" if self.tensors is None: self.tensors = tensors if self.do_nested_concat else [tensors] elif self.do_nested_concat: self.tens...
262
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
# reset device tensors after adding to cpu self.tensors = None def get_arrays(self): """Returns the numpified and moved to CPU stored objects.""" self.to_cpu_and_numpy() return self.arrays
262
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
class SequentialDistributedSampler(Sampler): """ Distributed Sampler that subsamples indices sequentially, making it easier to collate all results at the end. Even though we only use this sampler for eval and predict (no training), which means that the model params won't have to be synced (i.e. will no...
263
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
def __init__(self, dataset, num_replicas=None, rank=None, batch_size=None): warnings.warn( "SequentialDistributedSampler is deprecated and will be removed in v5 of Transformers.", FutureWarning, ) if num_replicas is None: if not dist.is_available(): ...
263
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
self.num_samples = int(math.ceil(num_samples / num_replicas)) self.total_size = self.num_samples * self.num_replicas self.batch_size = batch_size
263
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
def __iter__(self): indices = list(range(len(self.dataset))) # add extra samples to make it evenly divisible indices += indices[: (self.total_size - len(indices))] assert ( len(indices) == self.total_size ), f"Indices length {len(indices)} and total size {self.total_...
263
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
class DistributedTensorGatherer: """ A class responsible for properly gathering tensors (or nested list/tuple of tensors) on the CPU by chunks. If our dataset has 16 samples with a batch size of 2 on 3 processes and we gather then transfer on CPU at every step, our sampler will generate the following i...
264
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
If we directly concatenate our results without taking any precautions, the user will then get the predictions for the indices in this order at the end of the prediction loop: `[0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11, 0, 1]` For some reason, that's not going to roll their boat. This class...
264
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
def __init__(self, world_size, num_samples, make_multiple_of=None, padding_index=-100): warnings.warn( "DistributedTensorGatherer is deprecated and will be removed in v5 of Transformers.", FutureWarning, ) self.world_size = world_size self.num_samples = num_sample...
264
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
def add_arrays(self, arrays): """ Add `arrays` to the internal storage, Will initialize the storage to the full size at the first arrays passed so that if we're bound to get an OOM, it happens at the beginning. """ if arrays is None: return if self._storage is...
264
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
def _nested_set_tensors(self, storage, arrays): if isinstance(arrays, (list, tuple)): result = [self._nested_set_tensors(x, y) for x, y in zip(storage, arrays)] return result[0][0], type(arrays)(r[1] for r in result) assert ( arrays.shape[0] % self.world_size == 0 ...
264
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
slice_len = arrays.shape[0] // self.world_size for i in range(self.world_size): if len(arrays.shape) == 1: storage[self._offsets[i] : self._offsets[i] + slice_len] = arrays[i * slice_len : (i + 1) * slice_len] else: # Expand the array on the fly if needed....
264
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
def finalize(self): """ Return the properly gathered arrays and truncate to the number of samples (since the sampler added some extras to get each process a dataset of the same length). """ if self._storage is None: return if self._offsets[0] != self.process_l...
264
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
class LabelSmoother: """ Adds label-smoothing on a pre-computed output from a Transformers model. Args: epsilon (`float`, *optional*, defaults to 0.1): The label smoothing factor. ignore_index (`int`, *optional*, defaults to -100): The index in the labels to ignore w...
265
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
padding_mask = labels.eq(self.ignore_index) # In case the ignore_index is -100, the gather will fail, so we replace labels by 0. The padding_mask # will ignore them in any case. labels = torch.clamp(labels, min=0) nll_loss = log_probs.gather(dim=-1, index=labels) # works for fp16...
265
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
class LengthGroupedSampler(Sampler): r""" Sampler that samples indices in a way that groups together features of the dataset of roughly the same length while keeping a bit of randomness. """ def __init__( self, batch_size: int, dataset: Optional[Dataset] = None, leng...
266
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
self.batch_size = batch_size if lengths is None: model_input_name = model_input_name if model_input_name is not None else "input_ids" if ( not (isinstance(dataset[0], dict) or isinstance(dataset[0], BatchEncoding)) or model_input_name not in dataset[0] ...
266
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
def __iter__(self): indices = get_length_grouped_indices(self.lengths, self.batch_size, generator=self.generator) return iter(indices)
266
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
class DistributedLengthGroupedSampler(DistributedSampler): r""" Distributed Sampler that samples indices in a way that groups together features of the dataset of roughly the same length while keeping a bit of randomness. """
267
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
# Copied and adapted from PyTorch DistributedSampler. def __init__( self, batch_size: int, dataset: Optional[Dataset] = None, num_replicas: Optional[int] = None, rank: Optional[int] = None, seed: int = 0, drop_last: bool = False, lengths: Optional[List...
267
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
self.batch_size = batch_size self.num_replicas = num_replicas self.rank = rank self.epoch = 0 self.drop_last = drop_last
267
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
if lengths is None: model_input_name = model_input_name if model_input_name is not None else "input_ids" if ( not (isinstance(dataset[0], dict) or isinstance(dataset[0], BatchEncoding)) or model_input_name not in dataset[0] ): raise Val...
267
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
# If the dataset length is evenly divisible by # of replicas, then there # is no need to drop any data, since the dataset will be split equally. if self.drop_last and len(self.lengths) % self.num_replicas != 0: # Split to nearest available length that is evenly divisible. # This ...
267
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
if not self.drop_last: # add extra samples to make it evenly divisible indices += indices[: (self.total_size - len(indices))] else: # remove tail of data to make it evenly divisible. indices = indices[: self.total_size] assert len(indices) == self.total_si...
267
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
class ShardSampler(Sampler): """ Sampler that shards batches between several processes. Dispatches indices batch by batch: on 2 processes with batch size 4, the first two batches are `[0, 1, 2, 3, 4, 5, 6, 7]` and `[8, 9, 10, 11, 12, 13, 14, 15]`, which shard into `[0, 1, 2, 3]` and `[8, 9, 10, 11]` for...
268
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
num_batches = len(dataset) // total_batch_size if drop_last else math.ceil(len(dataset) / total_batch_size) self.total_num_samples = num_batches * total_batch_size def __iter__(self): indices = list(range(len(self.dataset))) # Add extra samples to make it evenly divisible. While loop is th...
268
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
class IterableDatasetShard(IterableDataset): """ Wraps a PyTorch `IterableDataset` to generate samples for one of the processes only. Instances of this class will always yield a number of samples that is a round multiple of the actual batch size (which is `batch_size x num_processes`). Depending on the ...
269
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
If your IterableDataset implements some randomization that needs to be applied the same way on all processes (for instance, a shuffling), you should use a `torch.Generator` in a `generator` attribute of the `dataset` to generate your random numbers and call the [`~trainer_pt_utils.IterableDatasetShard.s...
269
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
Args: dataset (`torch.utils.data.IterableDataset`): The batch sampler to split in several shards. batch_size (`int`, *optional*, defaults to 1): The size of the batches per shard. drop_last (`bool`, *optional*, defaults to `False`): Whether or not to drop the ...
269
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
def __init__( self, dataset: IterableDataset, batch_size: int = 1, drop_last: bool = False, num_processes: int = 1, process_index: int = 0, seed: int = 0, ): self.dataset = dataset self.batch_size = batch_size self.drop_last = drop_last...
269
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
def __iter__(self): self.num_examples = 0 if ( not hasattr(self.dataset, "set_epoch") and hasattr(self.dataset, "generator") and isinstance(self.dataset.generator, torch.Generator) ): self.dataset.generator.manual_seed(self.seed + self.epoch) ...
269
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
# Finished if drop_last is True, otherwise complete the last batch with elements from the beginning. if not self.drop_last and len(current_batch) > 0: if first_batch is None: first_batch = current_batch.copy() while len(current_batch) < real_batch_size: cu...
269
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
class AcceleratorConfig: """ A subset of arguments relating to the underlying [`accelerate.Accelerator`] implementation utilized in the `Trainer` that can be customized. Mostly relating to data.
270
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
Parameters: split_batches (`bool`, *optional*, defaults to `False`): Whether or not the accelerator should split the batches yielded by the dataloaders across the devices. If `True` the actual batch size used will be the same on any kind of distributed processes, but it must be a ...
270
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
If set to `True`, in cases where the total batch size across all processes does not exactly divide the dataset, samples at the start of the dataset will be duplicated so the batch can be divided equally among all workers. use_seedable_sampler (`bool`, *optional*, defaults to `True`): ...
270
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
num_steps (`int`): Will take precedence over [`~.TrainingArguments.gradient_accumulation_steps`] if the latter is set to 1, otherwise an exception will be raised. adjust_scheduler (`bool`): Whether to adjust the scheduler steps to account for [`~.TrainingArguments.gradient_accumulation_ste...
270
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
Whether or not to use a pre-configured `AcceleratorState` or `PartialState` defined before calling `TrainingArguments`. If `True`, an `Accelerator` or `PartialState` must be initialized. May lead to issues using sweeps or hyperparameter tuning.
270
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
"""
270
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
# Data related arguments split_batches: bool = field( default=False, metadata={ "help": "Whether or not the accelerator should split the batches yielded by the dataloaders across the devices. If" " `True` the actual batch size used will be the same on any kind of distributed ...
270
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
default=True, metadata={ "help": "If set to `True`, in cases where the total batch size across all processes does not exactly divide the" " dataset, samples at the start of the dataset will be duplicated so the batch can be divided equally among" " all workers." }, ...
270
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
non_blocking: Optional[bool] = field( default=False, metadata={ "help": "Whether to use non-blocking CUDA calls to help minimize synchronization during " "distributed training with prepared `DataLoader` inputs being moved to device. " "Best if used with `pin_memory=Tr...
270
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
gradient_accumulation_kwargs: Optional[Dict] = field( default=None, metadata={ "help": "Additional kwargs to configure gradient accumulation, see [`accelerate.utils.GradientAccumulationPlugin`]. " "Any of the following (optional) keys are acceptable: " " num_steps (`...
270
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
metadata={ "help": "Whether or not to use a pre-configured `AcceleratorState` or `PartialState` defined before calling `TrainingArguments`." "If `True`, an `Accelerator` or `PartialState` must be initialized. May lead to issues using sweeps or hyperparameter tuning." }, )
270
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
@classmethod def from_json_file(cls, json_file): # Check if exists open_file = io.open if os.path.exists(json_file) else open with open_file(json_file, "r", encoding="utf-8") as f: config_dict = json.load(f) # Check for keys and load sensible defaults extra_keys =...
270
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
class LayerWiseDummyOptimizer(torch.optim.Optimizer): """ For Layer-wise optimizers such as GaLoRE optimizer, the optimization step is already done through the post gradient hooks. Therefore the trick is to create a dummy optimizer that can take arbitrary args and kwargs and return a no-op during tr...
271
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
class LayerWiseDummyScheduler(LRScheduler): """ For Layer-wise optimizers such as GaLoRE optimizer, the optimization and scheduling step are already done through the post gradient hooks. Therefore the trick is to create a dummy scheduler that can take arbitrary args and kwargs and return a no-op dur...
272
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
return lrs def _get_closed_form_lr(self): return self.base_lrs
272
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
class TFModelUtilsMixin: """ A few utilities for `keras.Model`, to be used as a mixin. """ def num_parameters(self, only_trainable: bool = False) -> int: """ Get the number of (optionally, trainable) parameters in the model. Args: only_trainable (`bool`, *optional*,...
273
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_utils.py
class TFCausalLanguageModelingLoss: """ Loss function suitable for causal language modeling (CLM), that is, the task of guessing the next token. <Tip> Any label of -100 will be ignored (along with the corresponding logits) in the loss computation. </Tip> """ def hf_compute_loss(self, lab...
274
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_utils.py
# Clip negative labels to zero here to avoid NaNs and errors - those positions will get masked later anyway unmasked_loss = loss_fn(tf.nn.relu(labels), logits) # make sure only labels that are not equal to -100 affect the loss loss_mask = tf.cast(labels != -100, dtype=unmasked_loss.dtype) ...
274
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_utils.py
class TFQuestionAnsweringLoss: """ Loss function suitable for question answering. """ def hf_compute_loss(self, labels, logits): loss_fn = keras.losses.SparseCategoricalCrossentropy(from_logits=True, reduction=keras.losses.Reduction.NONE) start_loss = loss_fn(labels["start_position"], l...
275
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_utils.py
class TFTokenClassificationLoss: """ Loss function suitable for token classification. <Tip> Any label of -100 will be ignored (along with the corresponding logits) in the loss computation. </Tip> """ def hf_compute_loss(self, labels, logits): loss_fn = keras.losses.SparseCategori...
276
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_utils.py
if self.config.tf_legacy_loss: # make sure only labels that are not equal to -100 # are taken into account as loss if tf.math.reduce_any(labels == -1): tf.print("Using `-1` to mask the loss for the token is deprecated. Please use `-100` instead.") acti...
276
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_utils.py
# Clip negative labels to zero here to avoid NaNs and errors - those positions will get masked later anyway unmasked_loss = loss_fn(tf.nn.relu(labels), logits) # make sure only labels that are not equal to -100 or -1 # are taken into account as loss loss_mask = tf.cast(labels >= 0, dtype...
276
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_utils.py
class TFSequenceClassificationLoss: """ Loss function suitable for sequence classification. """ def hf_compute_loss(self, labels, logits): if logits.shape.rank == 1 or logits.shape[1] == 1: loss_fn = keras.losses.MeanSquaredError(reduction=keras.losses.Reduction.NONE) if...
277
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_utils.py
class TFMultipleChoiceLoss: """Loss function suitable for multiple choice tasks.""" def hf_compute_loss(self, labels, logits): loss_fn = keras.losses.SparseCategoricalCrossentropy(from_logits=True, reduction=keras.losses.Reduction.NONE) return loss_fn(labels, logits)
278
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_utils.py
class TFMaskedLanguageModelingLoss(TFCausalLanguageModelingLoss): """ Loss function suitable for masked language modeling (MLM), that is, the task of guessing the masked tokens. <Tip> Any label of -100 will be ignored (along with the corresponding logits) in the loss computation. </Tip> """
279
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_utils.py
class TFNextSentencePredictionLoss: """ Loss function suitable for next sentence prediction (NSP), that is, the task of guessing the next sentence. <Tip> Any label of -100 will be ignored (along with the corresponding logits) in the loss computation. </Tip> """ def hf_compute_loss(self, ...
280
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_utils.py
# make sure only labels that are not equal to -100 # are taken into account as loss # Clip negative labels to zero here to avoid NaNs and errors - those positions will get masked later anyway unmasked_ns_loss = loss_fn(y_true=tf.nn.relu(labels), y_pred=logits) ns_loss_mask = tf.cast(lab...
280
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_utils.py
class TFPreTrainedModel(keras.Model, TFModelUtilsMixin, TFGenerationMixin, PushToHubMixin): r""" Base class for all TF models. [`TFPreTrainedModel`] takes care of storing the configuration of the models and handles methods for loading, downloading and saving models as well as a few methods common to al...
281
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_utils.py
- **config_class** ([`PretrainedConfig`]) -- A subclass of [`PretrainedConfig`] to use as configuration class for this model architecture. - **base_model_prefix** (`str`) -- A string indicating the attribute associated to the base model in derived classes of the same architecture adding modu...
281
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_utils.py
# a list of re pattern of tensor names to ignore from the model when loading the model weights # (and avoid unnecessary warnings). _keys_to_ignore_on_load_missing = None # a list of re pattern of tensor names to ignore from the weights when loading the model weights # (and avoid unnecessary warnings). ...
281
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_utils.py
Returns: `Dict[str, tf.Tensor]`: The dummy inputs. """ dummies = {} for key, spec in self.input_signature.items(): # 2 is the most correct arbitrary size. I will not be taking questions dummy_shape = [dim if dim is not None else 2 for dim in spec.shape] ...
281
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_utils.py
shape=(1, 2, self.config.hidden_size), dtype=tf.float32, name="encoder_hidden_states" ) else: raise NotImplementedError( "Model has cross-attention but we couldn't infer the shape for the encoder hidden states. Please manually override dumm...
281
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_utils.py