text
stringlengths
31
243k
type
stringclasses
1 value
start
int64
36
275k
end
int64
286
280k
depth
int64
0
1
filepath
stringlengths
85
188
parent_class
stringclasses
3 values
class_index
int64
0
10.8k
class FlaxCausalLMOutputWithCrossAttentions(ModelOutput): """ Base class for causal language model (or autoregressive) outputs. Args: logits (`jnp.ndarray` of shape `(batch_size, sequence_length, config.vocab_size)`): Prediction scores of the language modeling head (scores for each voca...
class_definition
19,231
21,757
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_outputs.py
null
200
class FlaxMaskedLMOutput(ModelOutput): """ Base class for masked language models outputs. Args: logits (`jnp.ndarray` of shape `(batch_size, sequence_length, config.vocab_size)`): Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). ...
class_definition
21,783
23,097
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_outputs.py
null
201
class FlaxSeq2SeqLMOutput(ModelOutput): """ Base class for sequence-to-sequence language models outputs. Args: logits (`jnp.ndarray` of shape `(batch_size, sequence_length, config.vocab_size)`): Prediction scores of the language modeling head (scores for each vocabulary token before Sof...
class_definition
23,165
27,095
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_outputs.py
null
202
class FlaxNextSentencePredictorOutput(ModelOutput): """ Base class for outputs of models predicting if two sentences are consecutive or not. Args: logits (`jnp.ndarray` of shape `(batch_size, 2)`): Prediction scores of the next sequence prediction (classification) head (scores of True/F...
class_definition
27,121
28,490
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_outputs.py
null
203
class FlaxSequenceClassifierOutput(ModelOutput): """ Base class for outputs of sentence classification models. Args: logits (`jnp.ndarray` of shape `(batch_size, config.num_labels)`): Classification (or regression if config.num_labels==1) scores (before SoftMax). hidden_states (...
class_definition
28,516
29,815
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_outputs.py
null
204
class FlaxSeq2SeqSequenceClassifierOutput(ModelOutput): """ Base class for outputs of sequence-to-sequence sentence classification models. Args: logits (`jnp.ndarray` of shape `(batch_size, config.num_labels)`): Classification (or regression if config.num_labels==1) scores (before SoftM...
class_definition
29,841
33,769
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_outputs.py
null
205
class FlaxMultipleChoiceModelOutput(ModelOutput): """ Base class for outputs of multiple choice models. Args: logits (`jnp.ndarray` of shape `(batch_size, num_choices)`): *num_choices* is the second dimension of the input tensors. (see *input_ids* above). Classification sco...
class_definition
33,795
35,139
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_outputs.py
null
206
class FlaxTokenClassifierOutput(ModelOutput): """ Base class for outputs of token classification models. Args: logits (`jnp.ndarray` of shape `(batch_size, sequence_length, config.num_labels)`): Classification scores (before SoftMax). hidden_states (`tuple(jnp.ndarray)`, *option...
class_definition
35,165
36,435
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_outputs.py
null
207
class FlaxQuestionAnsweringModelOutput(ModelOutput): """ Base class for outputs of question answering models. Args: start_logits (`jnp.ndarray` of shape `(batch_size, sequence_length)`): Span-start scores (before SoftMax). end_logits (`jnp.ndarray` of shape `(batch_size, sequenc...
class_definition
36,461
37,883
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_outputs.py
null
208
class FlaxSeq2SeqQuestionAnsweringModelOutput(ModelOutput): """ Base class for outputs of sequence-to-sequence question answering models. Args: start_logits (`jnp.ndarray` of shape `(batch_size, sequence_length)`): Span-start scores (before SoftMax). end_logits (`jnp.ndarray` of...
class_definition
37,909
41,960
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_outputs.py
null
209
class Cache(torch.nn.Module): """ Base, abstract class for all caches. The actual data structure is specific to each subclass. """ def __init__(self): super().__init__() def update( self, key_states: torch.Tensor, value_states: torch.Tensor, layer_idx: int, ...
class_definition
542
4,041
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py
null
210
class CacheConfig: """ Base class for cache configs """ cache_implementation: None @classmethod def from_dict(cls, config_dict, **kwargs): """ Constructs a CacheConfig instance from a dictionary of parameters. Args: config_dict (Dict[str, Any]): Dictionary c...
class_definition
4,055
7,863
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py
null
211
class QuantizedCacheConfig(CacheConfig): """ Configuration class for quantized cache settings. Attributes: backend (`str`, *optional*, defaults to `"quanto"`): Backend to use when performing quantization, Can be one of [`quanto`, `HQQ`] nbits (`Optional[int]`, *optional*, defaul...
class_definition
7,877
12,016
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py
null
212
class StaticCacheConfig(CacheConfig): """ Configuration class for static cache settings. """ cache_implementation = "static" def __init__(self, batch_size: int, max_cache_len: int, device="cpu"): self.batch_size = batch_size self.max_cache_len = max_cache_len self.device = ...
class_definition
12,030
13,173
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py
null
213
class DynamicCache(Cache): """ A cache that grows dynamically as more tokens are generated. This is the default for generative models. It stores the Key and Value states as a list of tensors, one for each layer. The expected shape for each tensor is `[batch_size, num_heads, seq_len, head_dim]`. Ex...
class_definition
13,176
22,658
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py
null
214
class OffloadedCache(DynamicCache): """ A drop-in replacement for DynamicCache that conserves GPU memory at the expense of more CPU memory. Useful for generating from models with very long context. In addition to the default CUDA stream, where all forward() computations happen, this class uses anot...
class_definition
22,661
28,434
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py
null
215
class QuantizedCache(DynamicCache): """ A quantizer cache similar to what is described in the [KIVI: A Tuning-Free Asymmetric 2bit Quantization for KV Cache paper](https://arxiv.org/abs/2402.02750). It allows the model to generate longer sequence length without allocating too much memory for Key and Value c...
class_definition
28,437
33,697
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py
null
216
class QuantoQuantizedCache(QuantizedCache): """ Quantized Cache class that uses `quanto` as a backend to perform quantization. Current implementation supports `int2` and `int4` dtypes only. Parameters: cache_config (`QuantizedCacheConfig`): A configuration containing all the arguments t...
class_definition
33,700
36,767
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py
null
217
class HQQQuantizedCache(QuantizedCache): """ Quantized Cache class that uses `HQQ` as a backend to perform quantization. Current implementation supports `int2`, `int4`, `int8` dtypes. Parameters: cache_config (`QuantizedCacheConfig`): A configuration containing all the arguments to be u...
class_definition
36,770
39,346
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py
null
218
class SinkCache(Cache): """ A cache that as described in the [Attention Sinks paper](https://arxiv.org/abs/2309.17453). It allows the model to generate beyond the length of its context window, without losing fluency in the conversation. As it discards past tokens, the model will lose the ability to gene...
class_definition
39,349
48,396
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py
null
219
class StaticCache(Cache): """ Static Cache class to be used with `torch.compile(model)` and `torch.export()`. Parameters: config (`PretrainedConfig`): The configuration file defining the shape-related attributes required to initialize the static cache. batch_size (`int`): ...
class_definition
48,399
57,273
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py
null
220
class SlidingWindowCache(StaticCache): """ Sliding Window Cache class to be used with `torch.compile` for models like Mistral that support sliding window attention. Every time when we try to update the cache, we compute the `indices` based on `cache_position >= self.config.sliding_window - 1`, if true(w...
class_definition
57,276
64,330
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py
null
221
class EncoderDecoderCache(Cache): """ Base, abstract class for all encoder-decoder caches. Can be used to hold combinations of self-attention and cross-attention caches. Example: ```python >>> from transformers import AutoProcessor, AutoModelForCausalLM, DynamicCache, EncoderDecoderCac...
class_definition
64,333
73,469
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py
null
222
class HybridCache(Cache): """ Hybrid Cache class to be used with `torch.compile` for Gemma2 models that alternate between a local sliding window attention and global attention in every other layer. Under the hood, Hybrid Cache leverages ["SlidingWindowCache"] for sliding window attention and ["StaticCac...
class_definition
73,472
83,284
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py
null
223
class MambaCache: """ Cache for mamba model which does not have attention mechanism and key value states. Arguments: config (`PretrainedConfig): The configuration file defining the shape-related attributes required to initialize the static cache. batch_size (`int`): ...
class_definition
83,287
88,150
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py
null
224
class OffloadedStaticCache(StaticCache): """ Static cache class to be used with `torch.compile(model)` that offloads to the CPU or another device. Args: config (`PretrainedConfig): The configuration file defining the shape-related attributes required to initialize the st...
class_definition
88,153
100,342
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py
null
225
class AttentionMaskConverter: """ A utility attention mask class that allows one to: - Create a causal 4d mask - Create a causal 4d mask with slided window - Convert a 2d attention mask (batch_size, query_length) to a 4d attention mask (batch_size, 1, query_length, key_value_le...
class_definition
773
13,019
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_attn_mask_utils.py
null
226
class TransposeType(ExplicitEnum): """ Possible ... """ NO = "no" SIMPLE = "simple" CONV1D = "conv1d" CONV2D = "conv2d"
class_definition
1,132
1,280
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_pytorch_utils.py
null
227
class PreTrainedTokenizerFast(PreTrainedTokenizerBase): """ Base class for all fast tokenizers (wrapping HuggingFace tokenizers library). Inherits from [`~tokenization_utils_base.PreTrainedTokenizerBase`]. Handles all the shared methods for tokenization and special tokens, as well as methods for d...
class_definition
2,915
40,723
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py
null
228
class ModuleUtilsMixin: """ A few utilities for `torch.nn.Modules`, to be used as a mixin. """ @staticmethod def _hook_rss_memory_pre_forward(module, *args, **kwargs): try: import psutil except ImportError: raise ImportError("You need to install psutil (pip i...
class_definition
35,280
49,598
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
null
229
class PreTrainedModel(nn.Module, ModuleUtilsMixin, GenerationMixin, PushToHubMixin, PeftAdapterMixin): r""" Base class for all models. [`PreTrainedModel`] 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...
class_definition
49,662
259,106
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
null
230
class PoolerStartLogits(nn.Module): """ Compute SQuAD start logits from sequence hidden states. Args: config ([`PretrainedConfig`]): The config used by the model, will be used to grab the `hidden_size` of the model. """ def __init__(self, config: PretrainedConfig): supe...
class_definition
259,400
260,716
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
null
231
class PoolerEndLogits(nn.Module): """ Compute SQuAD end logits from sequence hidden states. Args: config ([`PretrainedConfig`]): The config used by the model, will be used to grab the `hidden_size` of the model and the `layer_norm_eps` to use. """ def __init__(self,...
class_definition
260,719
263,574
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
null
232
class PoolerAnswerClass(nn.Module): """ Compute SQuAD 2.0 answer class from classification and start tokens hidden states. Args: config ([`PretrainedConfig`]): The config used by the model, will be used to grab the `hidden_size` of the model. """ def __init__(self, config): ...
class_definition
263,577
266,361
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
null
233
class SquadHeadOutput(ModelOutput): """ Base class for outputs of question answering models using a [`~modeling_utils.SQuADHead`]. Args: loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned if both `start_positions` and `end_positions` are provided): Classification loss as th...
class_definition
266,375
268,500
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
null
234
class SQuADHead(nn.Module): r""" A SQuAD head inspired by XLNet. Args: config ([`PretrainedConfig`]): The config used by the model, will be used to grab the `hidden_size` of the model and the `layer_norm_eps` to use. """ def __init__(self, config): super()._...
class_definition
268,503
274,587
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
null
235
class SequenceSummary(nn.Module): r""" Compute a single vector summary of a sequence hidden states. Args: config ([`PretrainedConfig`]): The config used by the model. Relevant arguments in the config class of the model are (refer to the actual config class of your model for ...
class_definition
274,590
279,614
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py
null
236
class AffineTransformed(TransformedDistribution): def __init__(self, base_distribution: Distribution, loc=None, scale=None, event_dim=0): self.scale = 1.0 if scale is None else scale self.loc = 0.0 if loc is None else loc super().__init__(base_distribution, [AffineTransform(loc=self.loc, sc...
class_definition
1,002
1,849
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/time_series_utils.py
null
237
class ParameterProjection(nn.Module): def __init__( self, in_features: int, args_dim: Dict[str, int], domain_map: Callable[..., Tuple[torch.Tensor]], **kwargs ) -> None: super().__init__(**kwargs) self.args_dim = args_dim self.proj = nn.ModuleList([nn.Linear(in_features, dim) for...
class_definition
1,852
2,410
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/time_series_utils.py
null
238
class LambdaLayer(nn.Module): def __init__(self, function): super().__init__() self.function = function def forward(self, x, *args): return self.function(x, *args)
class_definition
2,413
2,609
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/time_series_utils.py
null
239
class DistributionOutput: distribution_class: type in_features: int args_dim: Dict[str, int] def __init__(self, dim: int = 1) -> None: self.dim = dim self.args_dim = {k: dim * self.args_dim[k] for k in self.args_dim} def _base_distribution(self, distr_args): if self.dim == ...
class_definition
2,612
5,334
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/time_series_utils.py
null
240
class StudentTOutput(DistributionOutput): """ Student-T distribution output class. """ args_dim: Dict[str, int] = {"df": 1, "loc": 1, "scale": 1} distribution_class: type = StudentT @classmethod def domain_map(cls, df: torch.Tensor, loc: torch.Tensor, scale: torch.Tensor): scale = ...
class_definition
5,337
5,822
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/time_series_utils.py
null
241
class NormalOutput(DistributionOutput): """ Normal distribution output class. """ args_dim: Dict[str, int] = {"loc": 1, "scale": 1} distribution_class: type = Normal @classmethod def domain_map(cls, loc: torch.Tensor, scale: torch.Tensor): scale = cls.squareplus(scale).clamp_min(to...
class_definition
5,825
6,222
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/time_series_utils.py
null
242
class NegativeBinomialOutput(DistributionOutput): """ Negative Binomial distribution output class. """ args_dim: Dict[str, int] = {"total_count": 1, "logits": 1} distribution_class: type = NegativeBinomial @classmethod def domain_map(cls, total_count: torch.Tensor, logits: torch.Tensor): ...
class_definition
6,225
7,520
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/time_series_utils.py
null
243
class Trainer: """ Trainer is a simple but feature-complete training and eval loop for PyTorch, optimized for 🤗 Transformers. Args: model ([`PreTrainedModel`] or `torch.nn.Module`, *optional*): The model to train, evaluate or use for predictions. If not provided, a `model_init` must be...
class_definition
9,609
253,063
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer.py
null
244
class HyperParamSearchBackendBase: name: str pip_package: str = None @staticmethod def is_available(): raise NotImplementedError def run(self, trainer, n_trials: int, direction: str, **kwargs): raise NotImplementedError def default_hp_space(self, trial): raise NotImple...
class_definition
1,078
1,736
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/hyperparameter_search.py
null
245
class OptunaBackend(HyperParamSearchBackendBase): name = "optuna" @staticmethod def is_available(): return is_optuna_available() def run(self, trainer, n_trials: int, direction: str, **kwargs): return run_hp_search_optuna(trainer, n_trials, direction, **kwargs) def default_hp_spac...
class_definition
1,739
2,120
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/hyperparameter_search.py
null
246
class RayTuneBackend(HyperParamSearchBackendBase): name = "ray" pip_package = "'ray[tune]'" @staticmethod def is_available(): return is_ray_tune_available() def run(self, trainer, n_trials: int, direction: str, **kwargs): return run_hp_search_ray(trainer, n_trials, direction, **kwa...
class_definition
2,123
2,530
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/hyperparameter_search.py
null
247
class SigOptBackend(HyperParamSearchBackendBase): name = "sigopt" @staticmethod def is_available(): return is_sigopt_available() def run(self, trainer, n_trials: int, direction: str, **kwargs): return run_hp_search_sigopt(trainer, n_trials, direction, **kwargs) def default_hp_spac...
class_definition
2,533
2,914
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/hyperparameter_search.py
null
248
class WandbBackend(HyperParamSearchBackendBase): name = "wandb" @staticmethod def is_available(): return is_wandb_available() def run(self, trainer, n_trials: int, direction: str, **kwargs): return run_hp_search_wandb(trainer, n_trials, direction, **kwargs) def default_hp_space(se...
class_definition
2,917
3,293
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/hyperparameter_search.py
null
249
class KerasMetricCallback(keras.callbacks.Callback): """ Callback to compute metrics at the end of every epoch. Unlike normal Keras metrics, these do not need to be compilable by TF. It is particularly useful for common NLP metrics like BLEU and ROUGE that require string operations or generation loops t...
class_definition
430
13,457
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/keras_callbacks.py
null
250
class PushToHubCallback(keras.callbacks.Callback): """ Callback that will save and push the model to the Hub regularly. By default, it pushes once per epoch, but this can be changed with the `save_strategy` argument. Pushed models can be accessed like any other model on the hub, such as with the `from_p...
class_definition
13,460
20,674
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/keras_callbacks.py
null
251
class TrainerState: """ A class containing the [`Trainer`] inner state that will be saved along the model and optimizer when checkpointing and passed to the [`TrainerCallback`]. <Tip> In all this class, one step is to be understood as one update step. When using gradient accumulation, one update ...
class_definition
1,050
6,994
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
null
252
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...
class_definition
6,997
8,743
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
null
253
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...
class_definition
8,757
11,209
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
null
254
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: Args: args ([`TrainingArguments`]): The training arguments used to i...
class_definition
11,212
17,078
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
null
255
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 ...
class_definition
17,081
23,033
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
null
256
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...
class_definition
23,036
24,906
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
null
257
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...
class_definition
24,909
28,058
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
null
258
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)
class_definition
28,061
28,345
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
null
259
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...
class_definition
28,348
31,866
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_callback.py
null
260
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`): ...
class_definition
9,937
11,171
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
null
261
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...
class_definition
11,174
13,295
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
null
262
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...
class_definition
13,298
15,757
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
null
263
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...
class_definition
17,124
22,050
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
null
264
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...
class_definition
22,064
23,900
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
null
265
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...
class_definition
25,750
27,460
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
null
266
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. """ # Copied and adapted from PyTorch DistributedSampler. def __init__( ...
class_definition
27,463
31,148
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
null
267
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...
class_definition
31,151
33,051
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
null
268
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 ...
class_definition
33,054
37,781
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
null
269
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. Parameters: split_batches (`bool`, *optional*, defaults to `False`): Whether or not ...
class_definition
50,573
58,541
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
null
270
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...
class_definition
58,544
59,455
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
null
271
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...
class_definition
59,458
60,566
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_pt_utils.py
null
272
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*,...
class_definition
3,632
4,300
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_utils.py
null
273
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...
class_definition
6,775
8,159
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_utils.py
null
274
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...
class_definition
8,162
8,599
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_utils.py
null
275
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...
class_definition
8,602
10,607
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_utils.py
null
276
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...
class_definition
10,610
11,310
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_utils.py
null
277
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)
class_definition
11,313
11,605
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_utils.py
null
278
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> """
class_definition
11,608
11,926
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_utils.py
null
279
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, ...
class_definition
11,929
13,440
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_utils.py
null
280
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...
class_definition
47,939
154,641
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_utils.py
null
281
class TFConv1D(keras.layers.Layer): """ 1D-convolutional layer as defined by Radford et al. for OpenAI GPT (and also used in GPT-2). Basically works like a linear layer but the weights are transposed. Args: nf (`int`): The number of output features. nx (`int`): ...
class_definition
154,644
156,043
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_utils.py
null
282
class TFSharedEmbeddings(keras.layers.Layer): r""" Construct shared token embeddings. The weights of the embedding layer is usually shared with the weights of the linear decoder when doing language modeling. Args: vocab_size (`int`): The size of the vocabulary, e.g., the number...
class_definition
156,046
160,275
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_utils.py
null
283
class TFSequenceSummary(keras.layers.Layer): """ Compute a single vector summary of a sequence hidden states. Args: config ([`PretrainedConfig`]): The config used by the model. Relevant arguments in the config class of the model are (refer to the actual config class of your ...
class_definition
160,278
166,498
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_utils.py
null
284
class DebugUnderflowOverflow: """ This debug class helps detect and understand where the model starts getting very large or very small, and more importantly `nan` or `inf` weight and activation elements. There are 2 working modes: 1. Underflow/overflow detection (default) 2. Specific batch abs...
class_definition
774
11,162
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/debug_utils.py
null
285
class DebugOption(ExplicitEnum): UNDERFLOW_OVERFLOW = "underflow_overflow" TPU_METRICS_DEBUG = "tpu_metrics_debug"
class_definition
12,784
12,906
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/debug_utils.py
null
286
class TFBaseModelOutput(ModelOutput): """ Base class for model's outputs, with potential hidden states and attentions. Args: last_hidden_state (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`): Sequence of hidden-states at the output of the last layer of the model. ...
class_definition
804
2,119
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_outputs.py
null
287
class TFBaseModelOutputWithNoAttention(ModelOutput): """ Base class for model's outputs, with potential hidden states. Args: last_hidden_state (`tf.Tensor` shape `(batch_size, num_channels, height, width)`): Sequence of hidden-states at the output of the last layer of the model. ...
class_definition
2,133
3,028
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_outputs.py
null
288
class TFBaseModelOutputWithPooling(ModelOutput): """ Base class for model's outputs that also contains a pooling of the last hidden states. Args: last_hidden_state (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`): Sequence of hidden-states at the output of the last la...
class_definition
3,042
5,000
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_outputs.py
null
289
class TFBaseModelOutputWithPoolingAndNoAttention(ModelOutput): """ Base class for model's outputs that also contains a pooling of the last hidden states. Args: last_hidden_state (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`): Sequence of hidden-states at the output o...
class_definition
5,014
6,146
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_outputs.py
null
290
class TFBaseModelOutputWithPoolingAndCrossAttentions(ModelOutput): """ Base class for model's outputs that also contains a pooling of the last hidden states. Args: last_hidden_state (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`): Sequence of hidden-states at the out...
class_definition
6,160
9,186
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_outputs.py
null
291
class TFBaseModelOutputWithPast(ModelOutput): """ Base class for model's outputs that may also contain a past key/values (to speed up sequential decoding). Args: last_hidden_state (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`): Sequence of hidden-states at the outpu...
class_definition
9,200
11,228
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_outputs.py
null
292
class TFBaseModelOutputWithCrossAttentions(ModelOutput): """ Base class for model's outputs, with potential hidden states and attentions. Args: last_hidden_state (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`): Sequence of hidden-states at the output of the last laye...
class_definition
11,242
13,094
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_outputs.py
null
293
class TFBaseModelOutputWithPastAndCrossAttentions(ModelOutput): """ Base class for model's outputs that may also contain a past key/values (to speed up sequential decoding). Args: last_hidden_state (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`): Sequence of hidden-s...
class_definition
13,108
15,677
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_outputs.py
null
294
class TFSeq2SeqModelOutput(ModelOutput): """ Base class for model encoder's outputs that also contains : pre-computed hidden states that can speed up sequential decoding. Args: last_hidden_state (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`): Sequence of hidden-...
class_definition
15,691
19,600
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_outputs.py
null
295
class TFCausalLMOutput(ModelOutput): """ Base class for causal language model (or autoregressive) outputs. Args: loss (`tf.Tensor` of shape `(n,)`, *optional*, where n is the number of non-masked labels, returned when `labels` is provided): Language modeling loss (for next-token predict...
class_definition
19,614
21,157
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_outputs.py
null
296
class TFCausalLMOutputWithPast(ModelOutput): """ Base class for causal language model (or autoregressive) outputs. Args: loss (`tf.Tensor` of shape `(n,)`, *optional*, where n is the number of non-masked labels, returned when `labels` is provided): Language modeling loss (for next-token...
class_definition
21,171
23,254
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_outputs.py
null
297
class TFCausalLMOutputWithCrossAttentions(ModelOutput): """ Base class for causal language model (or autoregressive) outputs. Args: loss (`tf.Tensor` of shape `(n,)`, *optional*, where n is the number of non-masked labels, returned when `labels` is provided): Language modeling loss (for...
class_definition
23,268
25,880
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_outputs.py
null
298
class TFMaskedLMOutput(ModelOutput): """ Base class for masked language models outputs. Args: loss (`tf.Tensor` of shape `(n,)`, *optional*, where n is the number of non-masked labels, returned when `labels` is provided): Masked language modeling (MLM) loss. logits (`tf.Tensor` ...
class_definition
25,894
27,403
0
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_outputs.py
null
299