code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def nested_concat(tensors, new_tensors, padding_index=-100): """ Concat the `new_tensors` to `tensors` on the first dim and pad them on the second if needed. Works for tensors or nested list/tuples/dict of tensors. """ assert type(tensors) == type( new_tensors ), f"Expected `tensors` and...
Concat the `new_tensors` to `tensors` on the first dim and pad them on the second if needed. Works for tensors or nested list/tuples/dict of tensors.
nested_concat
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_pt_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_pt_utils.py
Apache-2.0
def find_batch_size(tensors): """ Find the first dimension of a tensor in a nested list/tuple/dict of tensors. """ if isinstance(tensors, (list, tuple)): for t in tensors: result = find_batch_size(t) if result is not None: return result elif isinstance...
Find the first dimension of a tensor in a nested list/tuple/dict of tensors.
find_batch_size
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_pt_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_pt_utils.py
Apache-2.0
def nested_numpify(tensors): "Numpify `tensors` (even if it's a nested list/tuple/dict of tensors)." if isinstance(tensors, (list, tuple)): return type(tensors)(nested_numpify(t) for t in tensors) if isinstance(tensors, Mapping): return type(tensors)({k: nested_numpify(t) for k, t in tensors...
Numpify `tensors` (even if it's a nested list/tuple/dict of tensors).
nested_numpify
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_pt_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_pt_utils.py
Apache-2.0
def torch_distributed_zero_first(local_rank: int): """ Decorator to make all processes in distributed training wait for each local_master to do something. Args: local_rank (`int`): The rank of the local process. """ if local_rank not in [-1, 0]: dist.barrier() yield if local...
Decorator to make all processes in distributed training wait for each local_master to do something. Args: local_rank (`int`): The rank of the local process.
torch_distributed_zero_first
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_pt_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_pt_utils.py
Apache-2.0
def nested_new_like(arrays, num_samples, padding_index=-100): """Create the same nested structure as `arrays` with a first dimension always at `num_samples`.""" if isinstance(arrays, (list, tuple)): return type(arrays)(nested_new_like(x, num_samples) for x in arrays) return np.full_like(arrays, padd...
Create the same nested structure as `arrays` with a first dimension always at `num_samples`.
nested_new_like
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_pt_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_pt_utils.py
Apache-2.0
def expand_like(arrays, new_seq_length, padding_index=-100): """Expand the `arrays` so that the second dimension grows to `new_seq_length`. Uses `padding_index` for padding.""" result = np.full_like(arrays, padding_index, shape=(arrays.shape[0], new_seq_length) + arrays.shape[2:]) result[:, : arrays.shape[1...
Expand the `arrays` so that the second dimension grows to `new_seq_length`. Uses `padding_index` for padding.
expand_like
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_pt_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_pt_utils.py
Apache-2.0
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...
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.
add_arrays
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_pt_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_pt_utils.py
Apache-2.0
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...
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).
finalize
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_pt_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_pt_utils.py
Apache-2.0
def get_length_grouped_indices(lengths, batch_size, mega_batch_mult=None, generator=None): """ Return a list of indices so that each slice of `batch_size` consecutive indices correspond to elements of similar lengths. To do this, the indices are: - randomly permuted - grouped in mega-batches of siz...
Return a list of indices so that each slice of `batch_size` consecutive indices correspond to elements of similar lengths. To do this, the indices are: - randomly permuted - grouped in mega-batches of size `mega_batch_mult * batch_size` - sorted by length in each mega-batch The result is the ...
get_length_grouped_indices
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_pt_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_pt_utils.py
Apache-2.0
def metrics_format(self, metrics: Dict[str, float]) -> Dict[str, float]: """ Reformat Trainer metrics values to a human-readable format Args: metrics (`Dict[str, float]`): The metrics returned from train/evaluate/predict Returns: metrics (`Dict[str, float]`): The reformatte...
Reformat Trainer metrics values to a human-readable format Args: metrics (`Dict[str, float]`): The metrics returned from train/evaluate/predict Returns: metrics (`Dict[str, float]`): The reformatted metrics
metrics_format
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_pt_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_pt_utils.py
Apache-2.0
def log_metrics(self, split, metrics): """ Log metrics in a specially formatted way Under distributed environment this is done only for a process with rank 0. Args: split (`str`): Mode/split name: one of `train`, `eval`, `test` metrics (`Dict[str, float]`): The ...
Log metrics in a specially formatted way Under distributed environment this is done only for a process with rank 0. Args: split (`str`): Mode/split name: one of `train`, `eval`, `test` metrics (`Dict[str, float]`): The metrics returned from train/evaluate/predictme...
log_metrics
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_pt_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_pt_utils.py
Apache-2.0
def save_metrics(self, split, metrics, combined=True): """ Save metrics into a json file for that split, e.g. `train_results.json`. Under distributed environment this is done only for a process with rank 0. Args: split (`str`): Mode/split name: one of `train`, `eval`, `test`, `all`...
Save metrics into a json file for that split, e.g. `train_results.json`. Under distributed environment this is done only for a process with rank 0. Args: split (`str`): Mode/split name: one of `train`, `eval`, `test`, `all` metrics (`Dict[str, float]`): The metrics...
save_metrics
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_pt_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_pt_utils.py
Apache-2.0
def save_state(self): """ Saves the Trainer state, since Trainer.save_model saves only the tokenizer with the model Under distributed environment this is done only for a process with rank 0. """ if not self.is_world_process_zero(): return path = os.path.join(self.args.output_dir, "trai...
Saves the Trainer state, since Trainer.save_model saves only the tokenizer with the model Under distributed environment this is done only for a process with rank 0.
save_state
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_pt_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_pt_utils.py
Apache-2.0
def get_parameter_names(model, forbidden_layer_types): """ Returns the names of the model parameters that are not inside a forbidden layer. """ result = [] for name, child in model.named_children(): result += [ f"{name}.{n}" for n in get_parameter_names(child, forbidd...
Returns the names of the model parameters that are not inside a forbidden layer.
get_parameter_names
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_pt_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_pt_utils.py
Apache-2.0
def get_module_class_from_name(module, name): """ Gets a class from a module by its name. Args: module (`torch.nn.Module`): The module to get the class from. name (`str`): The name of the class. """ modules_children = list(module.children()) if module.__class__.__name__ == name:...
Gets a class from a module by its name. Args: module (`torch.nn.Module`): The module to get the class from. name (`str`): The name of the class.
get_module_class_from_name
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_pt_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_pt_utils.py
Apache-2.0
def evaluate( self, eval_dataset: Optional[Dataset] = None, ignore_keys: Optional[List[str]] = None, metric_key_prefix: str = "eval", **gen_kwargs ) -> Dict[str, float]: """ Run evaluation and returns metrics. The calling script will be responsible fo...
Run evaluation and returns metrics. The calling script will be responsible for providing a method to compute metrics, as they are task-dependent (pass it to the init `compute_metrics` argument). You can also subclass and override this method to inject custom behavior. Args: ...
evaluate
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_seq2seq.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_seq2seq.py
Apache-2.0
def predict( self, test_dataset: Dataset, ignore_keys: Optional[List[str]] = None, metric_key_prefix: str = "test", **gen_kwargs ) -> PredictionOutput: """ Run prediction and returns predictions and potential metrics. Depending on the dataset and your...
Run prediction and returns predictions and potential metrics. Depending on the dataset and your use case, your test dataset may contain labels. In that case, this method will also return metrics, like in `evaluate()`. Args: test_dataset (`Dataset`): Dataset...
predict
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_seq2seq.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_seq2seq.py
Apache-2.0
def prediction_step( self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]], prediction_loss_only: bool, ignore_keys: Optional[List[str]] = None, ) -> Tuple[Optional[float], Optional[torch.Tensor], Optional[torch.Tensor]]: """ Perform an evaluatio...
Perform an evaluation step on `model` using `inputs`. Subclass and override to inject custom behavior. Args: model (`nn.Module`): The model to evaluate. inputs (`Dict[str, Union[torch.Tensor, Any]]`): The inputs and targets of the model....
prediction_step
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_seq2seq.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_seq2seq.py
Apache-2.0
def get_train_tfdataset(self) -> tf.data.Dataset: """ Returns the training [`~tf.data.Dataset`]. Subclass and override this method if you want to inject some custom behavior. """ if self.train_dataset is None: raise ValueError("Trainer: training requires a train_data...
Returns the training [`~tf.data.Dataset`]. Subclass and override this method if you want to inject some custom behavior.
get_train_tfdataset
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_tf.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_tf.py
Apache-2.0
def get_eval_tfdataset(self, eval_dataset: Optional[tf.data.Dataset] = None) -> tf.data.Dataset: """ Returns the evaluation [`~tf.data.Dataset`]. Args: eval_dataset ([`~tf.data.Dataset`], *optional*): If provided, will override *self.eval_dataset*. The dataset should...
Returns the evaluation [`~tf.data.Dataset`]. Args: eval_dataset ([`~tf.data.Dataset`], *optional*): If provided, will override *self.eval_dataset*. The dataset should yield tuples of `(features, labels)` where `features` is a dict of input features and `labe...
get_eval_tfdataset
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_tf.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_tf.py
Apache-2.0
def get_test_tfdataset(self, test_dataset: tf.data.Dataset) -> tf.data.Dataset: """ Returns a test [`~tf.data.Dataset`]. Args: test_dataset ([`~tf.data.Dataset`]): The dataset to use. The dataset should yield tuples of `(features, labels)` where `features` is a dict ...
Returns a test [`~tf.data.Dataset`]. Args: test_dataset ([`~tf.data.Dataset`]): The dataset to use. The dataset should yield tuples of `(features, labels)` where `features` is a dict of input features and `labels` is the labels. If `labels` is a tensor, the ...
get_test_tfdataset
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_tf.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_tf.py
Apache-2.0
def create_optimizer_and_scheduler(self, num_training_steps: int): """ Setup the optimizer and the learning rate scheduler. We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the TFTrainer's init through `optimizers`, or subclass ...
Setup the optimizer and the learning rate scheduler. We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the TFTrainer's init through `optimizers`, or subclass and override this method.
create_optimizer_and_scheduler
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_tf.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_tf.py
Apache-2.0
def setup_wandb(self): """ Setup the optional Weights & Biases (`wandb`) integration. One can subclass and override this method to customize the setup if needed. Find more information `here <https://docs.wandb.com/huggingface>`__. You can also override the following environment variable...
Setup the optional Weights & Biases (`wandb`) integration. One can subclass and override this method to customize the setup if needed. Find more information `here <https://docs.wandb.com/huggingface>`__. You can also override the following environment variables: Environment: ...
setup_wandb
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_tf.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_tf.py
Apache-2.0
def setup_comet(self): """ Setup the optional Comet.ml integration. Environment: COMET_MODE: (Optional): str - "OFFLINE", "ONLINE", or "DISABLED" COMET_PROJECT_NAME: (Optional): str - Comet.ml project name for experiments COMET...
Setup the optional Comet.ml integration. Environment: COMET_MODE: (Optional): str - "OFFLINE", "ONLINE", or "DISABLED" COMET_PROJECT_NAME: (Optional): str - Comet.ml project name for experiments COMET_OFFLINE_DIRECTORY: ...
setup_comet
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_tf.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_tf.py
Apache-2.0
def prediction_loop( self, dataset: tf.data.Dataset, steps: int, num_examples: int, description: str, prediction_loss_only: Optional[bool] = None, ) -> PredictionOutput: """ Prediction/evaluation loop, shared by [`~TFTrainer.evaluate`] and [`~TFTrainer...
Prediction/evaluation loop, shared by [`~TFTrainer.evaluate`] and [`~TFTrainer.predict`]. Works both with or without labels.
prediction_loop
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_tf.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_tf.py
Apache-2.0
def evaluate(self, eval_dataset: Optional[tf.data.Dataset] = None) -> Dict[str, float]: """ Run evaluation and returns metrics. The calling script will be responsible for providing a method to compute metrics, as they are task-dependent (pass it to the init `compute_metrics` argument). ...
Run evaluation and returns metrics. The calling script will be responsible for providing a method to compute metrics, as they are task-dependent (pass it to the init `compute_metrics` argument). Args: eval_dataset ([`~tf.data.Dataset`], *optional*): Pass a ...
evaluate
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_tf.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_tf.py
Apache-2.0
def prediction_step( self, features: tf.Tensor, labels: tf.Tensor, nb_instances_in_global_batch: tf.Tensor ) -> tf.Tensor: """ Compute the prediction on features and update the loss with labels. Subclass and override to inject some custom behavior. """ per_example_lo...
Compute the prediction on features and update the loss with labels. Subclass and override to inject some custom behavior.
prediction_step
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_tf.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_tf.py
Apache-2.0
def train(self) -> None: """ Train method to train the model. """ train_ds = self.get_train_tfdataset() if self.args.debug: tf.summary.trace_on(graph=True, profiler=True) self.gradient_accumulator.reset() num_update_steps_per_epoch = self.num_train_...
Train method to train the model.
train
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_tf.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_tf.py
Apache-2.0
def training_step(self, features, labels, nb_instances_in_global_batch): """ Perform a training step on features and labels. Subclass and override to inject some custom behavior. """ per_example_loss, _ = self.run_model(features, labels, True) scaled_loss = per_example_l...
Perform a training step on features and labels. Subclass and override to inject some custom behavior.
training_step
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_tf.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_tf.py
Apache-2.0
def run_model(self, features, labels, training): """ Computes the loss of the given features and labels pair. Subclass and override this method if you want to inject some custom behavior. Args: features (`tf.Tensor`): A batch of input features. labels (`tf.Tenso...
Computes the loss of the given features and labels pair. Subclass and override this method if you want to inject some custom behavior. Args: features (`tf.Tensor`): A batch of input features. labels (`tf.Tensor`): A batch of labels. training (`bool`): Wheth...
run_model
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_tf.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_tf.py
Apache-2.0
def predict(self, test_dataset: tf.data.Dataset) -> PredictionOutput: """ Run prediction and returns predictions and potential metrics. Depending on the dataset and your use case, your test dataset may contain labels. In that case, this method will also return metrics, like in `evaluate...
Run prediction and returns predictions and potential metrics. Depending on the dataset and your use case, your test dataset may contain labels. In that case, this method will also return metrics, like in `evaluate()`. Args: test_dataset ([`~tf.data.Dataset`]): ...
predict
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_tf.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_tf.py
Apache-2.0
def save_model(self, output_dir: Optional[str] = None): """ Will save the model, so you can reload it using `from_pretrained()`. """ output_dir = output_dir if output_dir is not None else self.args.output_dir logger.info(f"Saving model in {output_dir}") if not isinstanc...
Will save the model, so you can reload it using `from_pretrained()`.
save_model
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_tf.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_tf.py
Apache-2.0
def set_seed(seed: int): """ Helper function for reproducible behavior to set the seed in `random`, `numpy`, `torch` and/or `tf` (if installed). Args: seed (`int`): The seed to set. """ random.seed(seed) np.random.seed(seed) if is_torch_available(): torch.manual_seed(seed) ...
Helper function for reproducible behavior to set the seed in `random`, `numpy`, `torch` and/or `tf` (if installed). Args: seed (`int`): The seed to set.
set_seed
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_utils.py
Apache-2.0
def default_compute_objective(metrics: Dict[str, float]) -> float: """ The default objective to maximize/minimize when doing an hyperparameter search. It is the evaluation loss if no metrics are provided to the [`Trainer`], the sum of all metrics otherwise. Args: metrics (`Dict[str, float]`): T...
The default objective to maximize/minimize when doing an hyperparameter search. It is the evaluation loss if no metrics are provided to the [`Trainer`], the sum of all metrics otherwise. Args: metrics (`Dict[str, float]`): The metrics returned by the evaluate method. Return: `float`: ...
default_compute_objective
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_utils.py
Apache-2.0
def is_main_process(local_rank): """ Whether or not the current process is the local process, based on `xm.get_ordinal()` (for TPUs) first, then on `local_rank`. """ if is_torch_tpu_available(check_device=True): import torch_xla.core.xla_model as xm return xm.get_ordinal() == 0 ...
Whether or not the current process is the local process, based on `xm.get_ordinal()` (for TPUs) first, then on `local_rank`.
is_main_process
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_utils.py
Apache-2.0
def total_processes_number(local_rank): """ Return the number of processes launched in parallel. Works with `torch.distributed` and TPUs. """ if is_torch_tpu_available(check_device=True): import torch_xla.core.xla_model as xm return xm.xrt_world_size() elif local_rank != -1 and is_t...
Return the number of processes launched in parallel. Works with `torch.distributed` and TPUs.
total_processes_number
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_utils.py
Apache-2.0
def speed_metrics(split, start_time, num_samples=None, num_steps=None): """ Measure and return speed performance metrics. This function requires a time snapshot `start_time` before the operation to be measured starts and this function should be run immediately after the operation to be measured has com...
Measure and return speed performance metrics. This function requires a time snapshot `start_time` before the operation to be measured starts and this function should be run immediately after the operation to be measured has completed. Args: - split: name to prefix metric (like train, eval, test.....
speed_metrics
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_utils.py
Apache-2.0
def derive_stage(self): """derives the stage/caller name automatically""" caller = inspect.currentframe().f_back.f_back.f_code.co_name if caller in self.stages: return self.stages[caller] else: raise ValueError( f"was called from {caller}, but only...
derives the stage/caller name automatically
derive_stage
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_utils.py
Apache-2.0
def start(self): """start tracking for the caller's stage""" if self.skip_memory_metrics: return stage = self.derive_stage() # deal with nested calls of eval during train - simply ignore those if self.cur_stage is not None and self.cur_stage != stage: ret...
start tracking for the caller's stage
start
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_utils.py
Apache-2.0
def stop(self, stage): """stop tracking for the passed stage""" # deal with nested calls of eval during train - simply ignore those if self.cur_stage is not None and self.cur_stage != stage: return # this sends a signal to peak_monitor_func to complete its loop self...
stop tracking for the passed stage
stop
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_utils.py
Apache-2.0
def stop_and_update_metrics(self, metrics=None): """combine stop and metrics update in one call for simpler code""" if self.skip_memory_metrics: return stage = self.derive_stage() self.stop(stage) # init doesn't have metrics to update so we just save that data for l...
combine stop and metrics update in one call for simpler code
stop_and_update_metrics
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_utils.py
Apache-2.0
def has_length(dataset): """ Checks if the dataset implements __len__() and it doesn't raise an error """ try: return len(dataset) is not None except TypeError: # TypeError: len() of unsized object return False
Checks if the dataset implements __len__() and it doesn't raise an error
has_length
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_utils.py
Apache-2.0
def denumpify_detensorize(metrics): """ Recursively calls `.item()` on the element of the dictionary passed """ if isinstance(metrics, (list, tuple)): return type(metrics)(denumpify_detensorize(m) for m in metrics) elif isinstance(metrics, dict): return type(metrics)({k: denumpify_de...
Recursively calls `.item()` on the element of the dictionary passed
denumpify_detensorize
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_utils.py
Apache-2.0
def number_of_arguments(func): """ Return the number of arguments of the passed function, even if it's a partial function. """ if isinstance(func, functools.partial): total_args = len(inspect.signature(func.func).parameters) return total_args - len(func.args) - len(func.keywords) ret...
Return the number of arguments of the passed function, even if it's a partial function.
number_of_arguments
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_utils.py
Apache-2.0
def find_executable_batch_size( function: callable = None, starting_batch_size: int = 128, auto_find_batch_size: bool = False ): """ Args: A basic decorator that will try to execute `function`. If it fails from exceptions related to out-of-memory or CUDNN, the batch size is cut in half and passed to...
Args: A basic decorator that will try to execute `function`. If it fails from exceptions related to out-of-memory or CUDNN, the batch size is cut in half and passed to `function` `function` must take in a `batch_size` parameter as its first argument. function (`callable`, *optional*) ...
find_executable_batch_size
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/trainer_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/trainer_utils.py
Apache-2.0
def get_int_from_env(env_keys, default): """Returns the first positive env value found in the `env_keys` list or the default.""" for e in env_keys: val = int(os.environ.get(e, -1)) if val >= 0: return val return default
Returns the first positive env value found in the `env_keys` list or the default.
get_int_from_env
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/training_args.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/training_args.py
Apache-2.0
def get_xla_device_type(device: "torch.device") -> Optional[str]: """ Returns the xla device type (CPU|GPU|TPU) or None if the device is a non-xla device. """ if is_torch_tpu_available(): return xm.xla_real_devices([device])[0].split(":")[0] return None
Returns the xla device type (CPU|GPU|TPU) or None if the device is a non-xla device.
get_xla_device_type
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/training_args.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/training_args.py
Apache-2.0
def train_batch_size(self) -> int: """ The actual batch size for training (may differ from `per_gpu_train_batch_size` in distributed training). """ if self.per_gpu_train_batch_size: logger.warning( "Using deprecated `--per_gpu_train_batch_size` argument which ...
The actual batch size for training (may differ from `per_gpu_train_batch_size` in distributed training).
train_batch_size
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/training_args.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/training_args.py
Apache-2.0
def eval_batch_size(self) -> int: """ The actual batch size for evaluation (may differ from `per_gpu_eval_batch_size` in distributed training). """ if self.per_gpu_eval_batch_size: logger.warning( "Using deprecated `--per_gpu_eval_batch_size` argument which wi...
The actual batch size for evaluation (may differ from `per_gpu_eval_batch_size` in distributed training).
eval_batch_size
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/training_args.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/training_args.py
Apache-2.0
def n_gpu(self): """ The number of GPUs used by this process. Note: This will only be greater than one when you have multiple GPUs available but are not using distributed training. For distributed training, it will always be 1. """ # Make sure `self._n_gp...
The number of GPUs used by this process. Note: This will only be greater than one when you have multiple GPUs available but are not using distributed training. For distributed training, it will always be 1.
n_gpu
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/training_args.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/training_args.py
Apache-2.0
def parallel_mode(self): """ The current mode used for parallelism if multiple GPUs/TPU cores are available. One of: - `ParallelMode.NOT_PARALLEL`: no parallelism (CPU or one GPU). - `ParallelMode.NOT_DISTRIBUTED`: several GPUs in one single process (uses `torch.nn.DataParallel`). ...
The current mode used for parallelism if multiple GPUs/TPU cores are available. One of: - `ParallelMode.NOT_PARALLEL`: no parallelism (CPU or one GPU). - `ParallelMode.NOT_DISTRIBUTED`: several GPUs in one single process (uses `torch.nn.DataParallel`). - `ParallelMode.DISTRIBUTED`: sev...
parallel_mode
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/training_args.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/training_args.py
Apache-2.0
def world_size(self): """ The number of processes used in parallel. """ if is_torch_tpu_available(): return xm.xrt_world_size() elif is_sagemaker_mp_enabled(): return smp.dp_size() if not smp.state.cfg.prescaled_batch else smp.rdp_size() elif is_sa...
The number of processes used in parallel.
world_size
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/training_args.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/training_args.py
Apache-2.0
def process_index(self): """ The index of the current process used. """ if is_torch_tpu_available(): return xm.get_ordinal() elif is_sagemaker_mp_enabled(): return smp.dp_rank() if not smp.state.cfg.prescaled_batch else smp.rdp_rank() elif is_sagem...
The index of the current process used.
process_index
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/training_args.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/training_args.py
Apache-2.0
def local_process_index(self): """ The index of the local process used. """ if is_torch_tpu_available(): return xm.get_local_ordinal() elif is_sagemaker_mp_enabled(): return smp.local_rank() elif is_sagemaker_dp_enabled(): return dist.g...
The index of the local process used.
local_process_index
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/training_args.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/training_args.py
Apache-2.0
def should_log(self): """ Whether or not the current process should produce log. """ if self.log_on_each_node: return self.local_process_index == 0 else: if is_sagemaker_mp_enabled(): return smp.rank() == 0 else: ...
Whether or not the current process should produce log.
should_log
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/training_args.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/training_args.py
Apache-2.0
def should_save(self): """ Whether or not the current process should write to disk, e.g., to save models and checkpoints. """ if self.save_on_each_node: return self.local_process_index == 0 else: if is_sagemaker_mp_enabled(): return smp.ran...
Whether or not the current process should write to disk, e.g., to save models and checkpoints.
should_save
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/training_args.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/training_args.py
Apache-2.0
def get_process_log_level(self): """ Returns the log level to be used depending on whether this process is the main process of node 0, main process of node non-0, or a non-main process. For the main process the log level defaults to `logging.INFO` unless overridden by `log_level` argume...
Returns the log level to be used depending on whether this process is the main process of node 0, main process of node non-0, or a non-main process. For the main process the log level defaults to `logging.INFO` unless overridden by `log_level` argument. For the replica processes the l...
get_process_log_level
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/training_args.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/training_args.py
Apache-2.0
def main_process_first(self, local=True, desc="work"): """ A context manager for torch distributed environment where on needs to do something on the main process, while blocking replicas, and when it's finished releasing the replicas. One such use is for `datasets`'s `map` feature which...
A context manager for torch distributed environment where on needs to do something on the main process, while blocking replicas, and when it's finished releasing the replicas. One such use is for `datasets`'s `map` feature which to be efficient should be run once on the main process, w...
main_process_first
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/training_args.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/training_args.py
Apache-2.0
def get_warmup_steps(self, num_training_steps: int): """ Get number of steps used for a linear warmup. """ warmup_steps = ( self.warmup_steps if self.warmup_steps > 0 else math.ceil(num_training_steps * self.warmup_ratio) ) return warmup_steps
Get number of steps used for a linear warmup.
get_warmup_steps
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/training_args.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/training_args.py
Apache-2.0
def n_gpu(self) -> int: """ The number of replicas (CPUs, GPUs or TPU cores) used in this training. """ warnings.warn( "The n_gpu argument is deprecated and will be removed in a future version, use n_replicas instead.", FutureWarning, ) return self...
The number of replicas (CPUs, GPUs or TPU cores) used in this training.
n_gpu
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/training_args_tf.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/training_args_tf.py
Apache-2.0
def __init__(self, **kwargs): """ This __init__ is there for legacy code. When removing deprecated args completely, the class can simply be deleted """ for deprecated_arg in self.deprecated_args: if deprecated_arg in kwargs: positive_arg = deprecated_a...
This __init__ is there for legacy code. When removing deprecated args completely, the class can simply be deleted
__init__
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/benchmark/benchmark_args.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/benchmark/benchmark_args.py
Apache-2.0
def separate_process_wrapper_fn(func: Callable[[], None], do_multi_processing: bool) -> Callable[[], None]: """ This function wraps another function into its own separated process. In order to ensure accurate memory measurements it is important that the function is executed in a separate process Args: ...
This function wraps another function into its own separated process. In order to ensure accurate memory measurements it is important that the function is executed in a separate process Args: - `func`: (`callable`): function() -> ... generic function which will be executed in its own separate proce...
separate_process_wrapper_fn
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/benchmark/benchmark_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/benchmark/benchmark_utils.py
Apache-2.0
def measure_peak_memory_cpu(function: Callable[[], None], interval=0.5, device_idx=None) -> int: """ measures peak cpu memory consumption of a given `function` running the function for at least interval seconds and at most 20 * interval seconds. This function is heavily inspired by: `memory_usage` of the pa...
measures peak cpu memory consumption of a given `function` running the function for at least interval seconds and at most 20 * interval seconds. This function is heavily inspired by: `memory_usage` of the package `memory_profiler`: https://github.com/pythonprofilers/memory_profiler/blob/895c4ac7a08020d...
measure_peak_memory_cpu
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/benchmark/benchmark_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/benchmark/benchmark_utils.py
Apache-2.0
def get_cpu_memory(process_id: int) -> int: """ measures current cpu memory usage of a given `process_id` Args: - `process_id`: (`int`) process_id for which to measure memory Returns - `memory`: (`int`) consumed memory in Bytes """ process = psu...
measures current cpu memory usage of a given `process_id` Args: - `process_id`: (`int`) process_id for which to measure memory Returns - `memory`: (`int`) consumed memory in Bytes
get_cpu_memory
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/benchmark/benchmark_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/benchmark/benchmark_utils.py
Apache-2.0
def traceit(frame, event, args): """ Tracing method executed before running each line in a module or sub-module Record memory allocated in a list with debugging information """ global _is_memory_tracing_enabled if not _is_memory_tracing_enabled: return tracei...
Tracing method executed before running each line in a module or sub-module Record memory allocated in a list with debugging information
traceit
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/benchmark/benchmark_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/benchmark/benchmark_utils.py
Apache-2.0
def stop_memory_tracing( memory_trace: Optional[MemoryTrace] = None, ignore_released_memory: bool = True ) -> Optional[MemorySummary]: """ Stop memory tracing cleanly and return a summary of the memory trace if a trace is given. Args: `memory_trace` (optional output of start_memory_tracing, def...
Stop memory tracing cleanly and return a summary of the memory trace if a trace is given. Args: `memory_trace` (optional output of start_memory_tracing, default: None): memory trace to convert in summary `ignore_released_memory` (boolean, default: None): if True we only...
stop_memory_tracing
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/benchmark/benchmark_utils.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/benchmark/benchmark_utils.py
Apache-2.0
def find_indent(line: str) -> int: """ Returns the number of spaces that start a line indent. """ search = re.search("^(\s*)(?:\S|$)", line) if search is None: return 0 return len(search.groups()[0])
Returns the number of spaces that start a line indent.
find_indent
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
Apache-2.0
def parse_module_content(content: str) -> List[str]: """ Parse the content of a module in the list of objects it defines. Args: content (`str`): The content to parse Returns: `List[str]`: The list of objects defined in the module. """ objects = [] current_object = [] li...
Parse the content of a module in the list of objects it defines. Args: content (`str`): The content to parse Returns: `List[str]`: The list of objects defined in the module.
parse_module_content
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
Apache-2.0
def add_content_to_text( text: str, content: str, add_after: Optional[Union[str, Pattern]] = None, add_before: Optional[Union[str, Pattern]] = None, exact_match: bool = False, ) -> str: """ A utility to add some content inside a given text. Args: text (`str`): The text in which w...
A utility to add some content inside a given text. Args: text (`str`): The text in which we want to insert some content. content (`str`): The content to add. add_after (`str` or `Pattern`): The pattern to test on a line of `text`, the new content is added after the first instan...
add_content_to_text
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
Apache-2.0
def add_content_to_file( file_name: Union[str, os.PathLike], content: str, add_after: Optional[Union[str, Pattern]] = None, add_before: Optional[Union[str, Pattern]] = None, exact_match: bool = False, ): """ A utility to add some content inside a given file. Args: file_name (`str...
A utility to add some content inside a given file. Args: file_name (`str` or `os.PathLike`): The name of the file in which we want to insert some content. content (`str`): The content to add. add_after (`str` or `Pattern`): The pattern to test on a line of `text`, the new conte...
add_content_to_file
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
Apache-2.0
def replace_model_patterns( text: str, old_model_patterns: ModelPatterns, new_model_patterns: ModelPatterns ) -> Tuple[str, str]: """ Replace all patterns present in a given text. Args: text (`str`): The text to treat. old_model_patterns (`ModelPatterns`): The patterns for the old model...
Replace all patterns present in a given text. Args: text (`str`): The text to treat. old_model_patterns (`ModelPatterns`): The patterns for the old model. new_model_patterns (`ModelPatterns`): The patterns for the new model. Returns: `Tuple(str, str)`: A tuple of with the ...
replace_model_patterns
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
Apache-2.0
def simplify_replacements(replacements): """ Simplify a list of replacement patterns to make sure there are no needless ones. For instance in the sequence "Bert->BertNew, BertConfig->BertNewConfig, bert->bert_new", the replacement "BertConfig->BertNewConfig" is implied by "Bert->BertNew" so not needed....
Simplify a list of replacement patterns to make sure there are no needless ones. For instance in the sequence "Bert->BertNew, BertConfig->BertNewConfig, bert->bert_new", the replacement "BertConfig->BertNewConfig" is implied by "Bert->BertNew" so not needed. Args: replacements (`List[Tuple[st...
simplify_replacements
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
Apache-2.0
def get_module_from_file(module_file: Union[str, os.PathLike]) -> str: """ Returns the module name corresponding to a module file. """ full_module_path = Path(module_file).absolute() module_parts = full_module_path.with_suffix("").parts # Find the first part named transformers, starting from th...
Returns the module name corresponding to a module file.
get_module_from_file
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
Apache-2.0
def duplicate_module( module_file: Union[str, os.PathLike], old_model_patterns: ModelPatterns, new_model_patterns: ModelPatterns, dest_file: Optional[str] = None, add_copied_from: bool = True, ): """ Create a new module from an existing one and adapting all function and classes names from ol...
Create a new module from an existing one and adapting all function and classes names from old patterns to new ones. Args: module_file (`str` or `os.PathLike`): Path to the module to duplicate. old_model_patterns (`ModelPatterns`): The patterns for the old model. new_model_patterns (`Mo...
duplicate_module
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
Apache-2.0
def filter_framework_files( files: List[Union[str, os.PathLike]], frameworks: Optional[List[str]] = None ) -> List[Union[str, os.PathLike]]: """ Filter a list of files to only keep the ones corresponding to a list of frameworks. Args: files (`List[Union[str, os.PathLike]]`): The list of files t...
Filter a list of files to only keep the ones corresponding to a list of frameworks. Args: files (`List[Union[str, os.PathLike]]`): The list of files to filter. frameworks (`List[str]`, *optional*): The list of allowed frameworks. Returns: `List[Union[str, os.PathLike]]`: The list ...
filter_framework_files
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
Apache-2.0
def get_model_files(model_type: str, frameworks: Optional[List[str]] = None) -> Dict[str, Union[Path, List[Path]]]: """ Retrieves all the files associated to a model. Args: model_type (`str`): A valid model type (like "bert" or "gpt2") frameworks (`List[str]`, *optional*): If pa...
Retrieves all the files associated to a model. Args: model_type (`str`): A valid model type (like "bert" or "gpt2") frameworks (`List[str]`, *optional*): If passed, will only keep the model files corresponding to the passed frameworks. Returns: `Dict[str, Union[Path, L...
get_model_files
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
Apache-2.0
def find_base_model_checkpoint( model_type: str, model_files: Optional[Dict[str, Union[Path, List[Path]]]] = None ) -> str: """ Finds the model checkpoint used in the docstrings for a given model. Args: model_type (`str`): A valid model type (like "bert" or "gpt2") model_files (`Dict[st...
Finds the model checkpoint used in the docstrings for a given model. Args: model_type (`str`): A valid model type (like "bert" or "gpt2") model_files (`Dict[str, Union[Path, List[Path]]`, *optional*): The files associated to `model_type`. Can be passed to speed up the function, oth...
find_base_model_checkpoint
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
Apache-2.0
def get_default_frameworks(): """ Returns the list of frameworks (PyTorch, TensorFlow, Flax) that are installed in the environment. """ frameworks = [] if is_torch_available(): frameworks.append("pt") if is_tf_available(): frameworks.append("tf") if is_flax_available(): ...
Returns the list of frameworks (PyTorch, TensorFlow, Flax) that are installed in the environment.
get_default_frameworks
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
Apache-2.0
def retrieve_model_classes(model_type: str, frameworks: Optional[List[str]] = None) -> Dict[str, List[str]]: """ Retrieve the model classes associated to a given model. Args: model_type (`str`): A valid model type (like "bert" or "gpt2") frameworks (`List[str]`, *optional*): The...
Retrieve the model classes associated to a given model. Args: model_type (`str`): A valid model type (like "bert" or "gpt2") frameworks (`List[str]`, *optional*): The frameworks to look for. Will default to `["pt", "tf", "flax"]`, passing a smaller list will restrict th...
retrieve_model_classes
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
Apache-2.0
def retrieve_info_for_model(model_type, frameworks: Optional[List[str]] = None): """ Retrieves all the information from a given model_type. Args: model_type (`str`): A valid model type (like "bert" or "gpt2") frameworks (`List[str]`, *optional*): If passed, will only keep the in...
Retrieves all the information from a given model_type. Args: model_type (`str`): A valid model type (like "bert" or "gpt2") frameworks (`List[str]`, *optional*): If passed, will only keep the info corresponding to the passed frameworks. Returns: `Dict`: A dictionary wi...
retrieve_info_for_model
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
Apache-2.0
def clean_frameworks_in_init( init_file: Union[str, os.PathLike], frameworks: Optional[List[str]] = None, keep_processing: bool = True ): """ Removes all the import lines that don't belong to a given list of frameworks or concern tokenizers/feature extractors/processors in an init. Args: in...
Removes all the import lines that don't belong to a given list of frameworks or concern tokenizers/feature extractors/processors in an init. Args: init_file (`str` or `os.PathLike`): The path to the init to treat. frameworks (`List[str]`, *optional*): If passed, this will remove...
clean_frameworks_in_init
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
Apache-2.0
def add_model_to_main_init( old_model_patterns: ModelPatterns, new_model_patterns: ModelPatterns, frameworks: Optional[List[str]] = None, with_processing: bool = True, ): """ Add a model to the main init of Transformers. Args: old_model_patterns (`ModelPatterns`): The patterns for t...
Add a model to the main init of Transformers. Args: old_model_patterns (`ModelPatterns`): The patterns for the old model. new_model_patterns (`ModelPatterns`): The patterns for the new model. frameworks (`List[str]`, *optional*): If specified, only the models implemented in...
add_model_to_main_init
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
Apache-2.0
def insert_tokenizer_in_auto_module(old_model_patterns: ModelPatterns, new_model_patterns: ModelPatterns): """ Add a tokenizer to the relevant mappings in the auto module. Args: old_model_patterns (`ModelPatterns`): The patterns for the old model. new_model_patterns (`ModelPatterns`): The p...
Add a tokenizer to the relevant mappings in the auto module. Args: old_model_patterns (`ModelPatterns`): The patterns for the old model. new_model_patterns (`ModelPatterns`): The patterns for the new model.
insert_tokenizer_in_auto_module
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
Apache-2.0
def add_model_to_auto_classes( old_model_patterns: ModelPatterns, new_model_patterns: ModelPatterns, model_classes: Dict[str, List[str]] ): """ Add a model to the relevant mappings in the auto module. Args: old_model_patterns (`ModelPatterns`): The patterns for the old model. new_model_...
Add a model to the relevant mappings in the auto module. Args: old_model_patterns (`ModelPatterns`): The patterns for the old model. new_model_patterns (`ModelPatterns`): The patterns for the new model. model_classes (`Dict[str, List[str]]`): A dictionary framework to list of model cla...
add_model_to_auto_classes
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
Apache-2.0
def duplicate_doc_file( doc_file: Union[str, os.PathLike], old_model_patterns: ModelPatterns, new_model_patterns: ModelPatterns, dest_file: Optional[Union[str, os.PathLike]] = None, frameworks: Optional[List[str]] = None, ): """ Duplicate a documentation file and adapts it for a new model. ...
Duplicate a documentation file and adapts it for a new model. Args: module_file (`str` or `os.PathLike`): Path to the doc file to duplicate. old_model_patterns (`ModelPatterns`): The patterns for the old model. new_model_patterns (`ModelPatterns`): The patterns for the new model. ...
duplicate_doc_file
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
Apache-2.0
def get_user_field( question: str, default_value: Optional[str] = None, is_valid_answer: Optional[Callable] = None, convert_to: Optional[Callable] = None, fallback_message: Optional[str] = None, ) -> Any: """ A utility function that asks a question to the user to get an answer, potentially l...
A utility function that asks a question to the user to get an answer, potentially looping until it gets a valid answer. Args: question (`str`): The question to ask the user. default_value (`str`, *optional*): A potential default value that will be used when the answer is empty. is_...
get_user_field
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
Apache-2.0
def get_user_input(): """ Ask the user for the necessary inputs to add the new model. """ model_types = list(auto_module.configuration_auto.MODEL_NAMES_MAPPING.keys()) # Get old model type valid_model_type = False while not valid_model_type: old_model_type = input( "What...
Ask the user for the necessary inputs to add the new model.
get_user_input
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/commands/add_new_model_like.py
Apache-2.0
def convert_command_factory(args: Namespace): """ Factory function used to convert a model TF 1.0 checkpoint in a PyTorch checkpoint. Returns: ServeCommand """ return ConvertCommand( args.model_type, args.tf_checkpoint, args.pytorch_dump_output, args.config, args.finetuning_task_name )
Factory function used to convert a model TF 1.0 checkpoint in a PyTorch checkpoint. Returns: ServeCommand
convert_command_factory
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/commands/convert.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/commands/convert.py
Apache-2.0
def register_subcommand(parser: ArgumentParser): """ Register this command to argparse so it's available for the transformer-cli Args: parser: Root parser to register command-specific arguments """ train_parser = parser.add_parser( "convert", ...
Register this command to argparse so it's available for the transformer-cli Args: parser: Root parser to register command-specific arguments
register_subcommand
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/commands/convert.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/commands/convert.py
Apache-2.0
def convert_command_factory(args: Namespace): """ Factory function used to convert a model PyTorch checkpoint in a TensorFlow 2 checkpoint. Returns: ServeCommand """ return PTtoTFCommand( args.model_name, args.local_dir, args.max_error, args.new_weights, args...
Factory function used to convert a model PyTorch checkpoint in a TensorFlow 2 checkpoint. Returns: ServeCommand
convert_command_factory
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/commands/pt_to_tf.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/commands/pt_to_tf.py
Apache-2.0
def find_pt_tf_differences(pt_outputs, tf_outputs): """ Compares the TensorFlow and PyTorch outputs, returning a dictionary with all tensor differences. """ # 1. All output attributes must be the same pt_out_attrs = set(pt_outputs.keys()) tf_out_attrs = set(tf_outputs.key...
Compares the TensorFlow and PyTorch outputs, returning a dictionary with all tensor differences.
find_pt_tf_differences
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/commands/pt_to_tf.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/commands/pt_to_tf.py
Apache-2.0
def get_inputs(self, pt_model, config): """ Returns the right inputs for the model, based on its signature. """ def _get_audio_input(): ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") speech_samples = ds.sort("id").sele...
Returns the right inputs for the model, based on its signature.
get_inputs
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/commands/pt_to_tf.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/commands/pt_to_tf.py
Apache-2.0
def serve_command_factory(args: Namespace): """ Factory function used to instantiate serving server from provided command line arguments. Returns: ServeCommand """ nlp = pipeline( task=args.task, model=args.model if args.model else None, config=args.config, tokenizer...
Factory function used to instantiate serving server from provided command line arguments. Returns: ServeCommand
serve_command_factory
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/commands/serving.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/commands/serving.py
Apache-2.0
def tokenize(self, text_input: str = Body(None, embed=True), return_ids: bool = Body(False, embed=True)): """ Tokenize the provided input and eventually returns corresponding tokens id: - **text_input**: String to tokenize - **return_ids**: Boolean flags indicating if the tokens have to be conve...
Tokenize the provided input and eventually returns corresponding tokens id: - **text_input**: String to tokenize - **return_ids**: Boolean flags indicating if the tokens have to be converted to their integer mapping.
tokenize
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/commands/serving.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/commands/serving.py
Apache-2.0
def detokenize( self, tokens_ids: List[int] = Body(None, embed=True), skip_special_tokens: bool = Body(False, embed=True), cleanup_tokenization_spaces: bool = Body(True, embed=True), ): """ Detokenize the provided tokens ids to readable text: - **tokens_ids**: List of...
Detokenize the provided tokens ids to readable text: - **tokens_ids**: List of tokens ids - **skip_special_tokens**: Flag indicating to not try to decode special tokens - **cleanup_tokenization_spaces**: Flag indicating to remove all leading/trailing spaces and intermediate ones.
detokenize
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/commands/serving.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/commands/serving.py
Apache-2.0
def tabulate(rows: List[List[Union[str, int]]], headers: List[str]) -> str: """ Inspired by: - stackoverflow.com/a/8356620/593036 - stackoverflow.com/questions/9535954/printing-lists-as-tabular-data """ col_widths = [max(len(str(x)) for x in col) for col in zip(*rows, headers)] row_format =...
Inspired by: - stackoverflow.com/a/8356620/593036 - stackoverflow.com/questions/9535954/printing-lists-as-tabular-data
tabulate
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/commands/user.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/commands/user.py
Apache-2.0
def default_data_collator(features: List[InputDataClass], return_tensors="pt") -> Dict[str, Any]: """ Very simple data collator that simply collates batches of dict-like objects and performs special handling for potential keys named: - `label`: handles a single value (int or float) per object ...
Very simple data collator that simply collates batches of dict-like objects and performs special handling for potential keys named: - `label`: handles a single value (int or float) per object - `label_ids`: handles a list of values per object Does not do any additional preprocessing: prop...
default_data_collator
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/data/data_collator.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/data/data_collator.py
Apache-2.0
def _torch_collate_batch(examples, tokenizer, pad_to_multiple_of: Optional[int] = None): """Collate `examples` into a batch, using the information in `tokenizer` for padding if necessary.""" import torch # Tensorize if necessary. if isinstance(examples[0], (list, tuple, np.ndarray)): examples =...
Collate `examples` into a batch, using the information in `tokenizer` for padding if necessary.
_torch_collate_batch
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/data/data_collator.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/data/data_collator.py
Apache-2.0
def _whole_word_mask(self, input_tokens: List[str], max_predictions=512): """ Get 0/1 labels for masked tokens with whole word mask proxy """ if not isinstance(self.tokenizer, (BertTokenizer, BertTokenizerFast)): warnings.warn( "DataCollatorForWholeWordMask is...
Get 0/1 labels for masked tokens with whole word mask proxy
_whole_word_mask
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/data/data_collator.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/data/data_collator.py
Apache-2.0
def torch_mask_tokens(self, inputs: Any, mask_labels: Any) -> Tuple[Any, Any]: """ Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original. Set 'mask_labels' means we use whole word mask (wwm), we directly mask idxs according to it's ref. """ ...
Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original. Set 'mask_labels' means we use whole word mask (wwm), we directly mask idxs according to it's ref.
torch_mask_tokens
python
FMInference/FlexLLMGen
benchmark/third_party/transformers/src/transformers/data/data_collator.py
https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/data/data_collator.py
Apache-2.0