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 load_state_dict(self, state_dict, optimizer_overrides=None): """Load an LR scheduler state dict.""" for k, state in state_dict.items(): if k not in self.optimizers: # skip extra keys like "loss_scale" added by fp16 optimizer continue overrides...
Load an LR scheduler state dict.
load_state_dict
python
OFA-Sys/OFA
fairseq/fairseq/optim/composite.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/optim/composite.py
Apache-2.0
def optimizer(self): """Return a torch.optim.optimizer.Optimizer instance.""" if not hasattr(self, "_optimizer"): raise NotImplementedError if not isinstance(self._optimizer, torch.optim.Optimizer): raise ValueError("_optimizer must be an instance of torch.optim.Optimizer...
Return a torch.optim.optimizer.Optimizer instance.
optimizer
python
OFA-Sys/OFA
fairseq/fairseq/optim/fairseq_optimizer.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/optim/fairseq_optimizer.py
Apache-2.0
def params(self): """Return an iterable of the parameters held by the optimizer.""" for param_group in self.param_groups: for p in param_group["params"]: yield p
Return an iterable of the parameters held by the optimizer.
params
python
OFA-Sys/OFA
fairseq/fairseq/optim/fairseq_optimizer.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/optim/fairseq_optimizer.py
Apache-2.0
def load_state_dict(self, state_dict, optimizer_overrides=None): """Load an optimizer state dict. In general we should prefer the configuration of the existing optimizer instance (e.g., learning rate) over that found in the state_dict. This allows us to resume training from a checkpoint...
Load an optimizer state dict. In general we should prefer the configuration of the existing optimizer instance (e.g., learning rate) over that found in the state_dict. This allows us to resume training from a checkpoint using a new set of optimizer args.
load_state_dict
python
OFA-Sys/OFA
fairseq/fairseq/optim/fairseq_optimizer.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/optim/fairseq_optimizer.py
Apache-2.0
def zero_grad(self): """Clears the gradients of all optimized parameters.""" for p in self.params: p.grad = None self.optimizer.zero_grad()
Clears the gradients of all optimized parameters.
zero_grad
python
OFA-Sys/OFA
fairseq/fairseq/optim/fairseq_optimizer.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/optim/fairseq_optimizer.py
Apache-2.0
def supports_flat_params(self): """ Whether the optimizer supports collapsing of the model parameters/gradients into a single contiguous Tensor. """ if hasattr(self.optimizer, "supports_flat_params"): return self.optimizer.supports_flat_params return False
Whether the optimizer supports collapsing of the model parameters/gradients into a single contiguous Tensor.
supports_flat_params
python
OFA-Sys/OFA
fairseq/fairseq/optim/fairseq_optimizer.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/optim/fairseq_optimizer.py
Apache-2.0
def broadcast_global_state_dict(self, state_dict): """ Broadcasts a global state dict to all ranks. Useful for optimizers that shard state between ranks. """ if hasattr(self.optimizer, "broadcast_global_state_dict"): return self.optimizer.broadcast_global_state_dict(s...
Broadcasts a global state dict to all ranks. Useful for optimizers that shard state between ranks.
broadcast_global_state_dict
python
OFA-Sys/OFA
fairseq/fairseq/optim/fairseq_optimizer.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/optim/fairseq_optimizer.py
Apache-2.0
def backward(self, loss): """Computes the sum of gradients of the given tensor w.r.t. graph leaves. Compared to :func:`fairseq.optim.FairseqOptimizer.backward`, this function additionally dynamically scales the loss to avoid gradient underflow. """ if self.scaler is not ...
Computes the sum of gradients of the given tensor w.r.t. graph leaves. Compared to :func:`fairseq.optim.FairseqOptimizer.backward`, this function additionally dynamically scales the loss to avoid gradient underflow.
backward
python
OFA-Sys/OFA
fairseq/fairseq/optim/fp16_optimizer.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/optim/fp16_optimizer.py
Apache-2.0
def clip_grad_norm(self, max_norm, aggregate_norm_fn=None): """Clips gradient norm and updates dynamic loss scaler.""" self._sync_fp16_grads_to_fp32() grad_norm = self._multiply_factor * self.fp32_optimizer.clip_grad_norm( 0, aggregate_norm_fn ) if self.scaler is no...
Clips gradient norm and updates dynamic loss scaler.
clip_grad_norm
python
OFA-Sys/OFA
fairseq/fairseq/optim/fp16_optimizer.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/optim/fp16_optimizer.py
Apache-2.0
def build_optimizer(cls, cfg: DictConfig, params, **kwargs): """ Args: args (argparse.Namespace): fairseq args params (iterable): iterable of parameters to optimize """ fp16_optimizer = optim.build_optimizer(cfg.optimizer, params) return cls(cfg, params, f...
Args: args (argparse.Namespace): fairseq args params (iterable): iterable of parameters to optimize
build_optimizer
python
OFA-Sys/OFA
fairseq/fairseq/optim/fp16_optimizer.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/optim/fp16_optimizer.py
Apache-2.0
def get_fused_adam_class(): """ Look for the FusedAdam optimizer from apex. We first try to load the "contrib" interface, which is a bit faster than the main interface, but is technically deprecated. """ try: # The "deprecated" interface in recent versions of apex is a bit # fast...
Look for the FusedAdam optimizer from apex. We first try to load the "contrib" interface, which is a bit faster than the main interface, but is technically deprecated.
get_fused_adam_class
python
OFA-Sys/OFA
fairseq/fairseq/optim/fused_adam.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/optim/fused_adam.py
Apache-2.0
def step(self, closure=None, grads=None, scale=1.0, grad_norms=None): """Performs a single optimization step. Args: closure (callable, optional): A closure that reevaluates the model and returns the loss. grads (list of tensors, optional): weight gradient to use f...
Performs a single optimization step. Args: closure (callable, optional): A closure that reevaluates the model and returns the loss. grads (list of tensors, optional): weight gradient to use for the optimizer update. If gradients have type torch.half, param...
step
python
OFA-Sys/OFA
fairseq/fairseq/optim/fused_adam.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/optim/fused_adam.py
Apache-2.0
def broadcast_global_state_dict( self, state_dict: Dict[str, Any] ) -> Dict[str, Any]: """ Broadcasts the entire state_dict to all other ranks each rank is responsible to load their own partition of data """ return utils.broadcast_object( ...
Broadcasts the entire state_dict to all other ranks each rank is responsible to load their own partition of data
broadcast_global_state_dict
python
OFA-Sys/OFA
fairseq/fairseq/optim/shard.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/optim/shard.py
Apache-2.0
def step(self, epoch, val_loss=None): """Update the learning rate at the end of the given epoch.""" super().step(epoch, val_loss) # we don't change the learning rate at epoch boundaries return self.optimizer.get_lr()
Update the learning rate at the end of the given epoch.
step
python
OFA-Sys/OFA
fairseq/fairseq/optim/lr_scheduler/cosine_lr_scheduler.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/optim/lr_scheduler/cosine_lr_scheduler.py
Apache-2.0
def add_args(cls, parser): """Add arguments to the parser for this LR scheduler.""" dc = getattr(cls, "__dataclass", None) if dc is not None: gen_parser_from_dataclass(parser, dc())
Add arguments to the parser for this LR scheduler.
add_args
python
OFA-Sys/OFA
fairseq/fairseq/optim/lr_scheduler/fairseq_lr_scheduler.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/optim/lr_scheduler/fairseq_lr_scheduler.py
Apache-2.0
def step_begin_epoch(self, epoch): """Update the learning rate at the beginning of the given epoch.""" self.lr = self.get_next_lr(epoch) self.optimizer.set_lr(self.warmup_factor * self.lr) return self.optimizer.get_lr()
Update the learning rate at the beginning of the given epoch.
step_begin_epoch
python
OFA-Sys/OFA
fairseq/fairseq/optim/lr_scheduler/fixed_schedule.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/optim/lr_scheduler/fixed_schedule.py
Apache-2.0
def state_dict(self): """Return the LR scheduler state dict.""" return { "best": self.lr_scheduler.best, "last_epoch": self.lr_scheduler.last_epoch, }
Return the LR scheduler state dict.
state_dict
python
OFA-Sys/OFA
fairseq/fairseq/optim/lr_scheduler/reduce_lr_on_plateau.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/optim/lr_scheduler/reduce_lr_on_plateau.py
Apache-2.0
def step(self, epoch, val_loss=None): """ Update the learning rate at the end of the given epoch if warmup finishes otherwise no update of lr on epoch boundaries """ if val_loss is not None and self.warmup_end is True: self.lr_scheduler.step(val_loss) else: ...
Update the learning rate at the end of the given epoch if warmup finishes otherwise no update of lr on epoch boundaries
step
python
OFA-Sys/OFA
fairseq/fairseq/optim/lr_scheduler/reduce_lr_on_plateau.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/optim/lr_scheduler/reduce_lr_on_plateau.py
Apache-2.0
def step_update(self, num_updates): """ Update the learning rate after each update.""" # if there is warmup if self.cfg.warmup_updates > 0: if num_updates <= self.cfg.warmup_updates: self.lr = self.cfg.warmup_init_lr + num_updates * self.lr_step ...
Update the learning rate after each update.
step_update
python
OFA-Sys/OFA
fairseq/fairseq/optim/lr_scheduler/reduce_lr_on_plateau.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/optim/lr_scheduler/reduce_lr_on_plateau.py
Apache-2.0
def _decide_stage(self, update_step): """ return stage, and the corresponding steps within the current stage """ if update_step < self.warmup_steps: # warmup state return 0, update_step offset = self.warmup_steps if update_step < offset + self.ho...
return stage, and the corresponding steps within the current stage
_decide_stage
python
OFA-Sys/OFA
fairseq/fairseq/optim/lr_scheduler/tri_stage_lr_scheduler.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/optim/lr_scheduler/tri_stage_lr_scheduler.py
Apache-2.0
def remove_punctuation(cls, sent: str): """Remove punctuation based on Unicode category.""" return cls.SPACE.join( t for t in sent.split(cls.SPACE) if not all(unicodedata.category(c)[0] == "P" for c in t) )
Remove punctuation based on Unicode category.
remove_punctuation
python
OFA-Sys/OFA
fairseq/fairseq/scoring/tokenizer.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/scoring/tokenizer.py
Apache-2.0
def _lang_to_id(self, languages: str): """ Build a map from languages to ids. These ids are used as segment labels for cross-lingual LM training. """ lang2id = {} langs = [l.strip() for l in languages.split(",")] for id, lang in enumerate(langs): lang2...
Build a map from languages to ids. These ids are used as segment labels for cross-lingual LM training.
_lang_to_id
python
OFA-Sys/OFA
fairseq/fairseq/tasks/cross_lingual_lm.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/tasks/cross_lingual_lm.py
Apache-2.0
def build_dataset_for_inference(self, src_tokens, src_lengths, **kwargs): """ Generate batches for inference. We assume that the input begins with a bos symbol (`<s>`) and ends with an eos symbol (`</s>`). """ pad = self.source_dictionary.pad() eos = self.source_dictionar...
Generate batches for inference. We assume that the input begins with a bos symbol (`<s>`) and ends with an eos symbol (`</s>`).
build_dataset_for_inference
python
OFA-Sys/OFA
fairseq/fairseq/tasks/denoising.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/tasks/denoising.py
Apache-2.0
def build_dictionary( cls, filenames, workers=1, threshold=-1, nwords=-1, padding_factor=8 ): """Build the dictionary Args: filenames (list): list of filenames workers (int): number of concurrent workers threshold (int): defines the minimum word count ...
Build the dictionary Args: filenames (list): list of filenames workers (int): number of concurrent workers threshold (int): defines the minimum word count nwords (int): defines the total number of words in the final dictionary, including special s...
build_dictionary
python
OFA-Sys/OFA
fairseq/fairseq/tasks/fairseq_task.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/tasks/fairseq_task.py
Apache-2.0
def load_dataset( self, split: str, combine: bool = False, task_cfg: FairseqDataclass = None, **kwargs ): """Load a given dataset split. Args: split (str): name of the split (e.g., train, valid, test) combine (bool): combines a split s...
Load a given dataset split. Args: split (str): name of the split (e.g., train, valid, test) combine (bool): combines a split segmented into pieces into one dataset task_cfg (FairseqDataclass): optional task configuration stored in the checkpoint that can be used ...
load_dataset
python
OFA-Sys/OFA
fairseq/fairseq/tasks/fairseq_task.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/tasks/fairseq_task.py
Apache-2.0
def dataset(self, split): """ Return a loaded dataset split. Args: split (str): name of the split (e.g., train, valid, test) Returns: a :class:`~fairseq.data.FairseqDataset` corresponding to *split* """ from fairseq.data import FairseqDataset ...
Return a loaded dataset split. Args: split (str): name of the split (e.g., train, valid, test) Returns: a :class:`~fairseq.data.FairseqDataset` corresponding to *split*
dataset
python
OFA-Sys/OFA
fairseq/fairseq/tasks/fairseq_task.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/tasks/fairseq_task.py
Apache-2.0
def filter_indices_by_size( self, indices, dataset, max_positions=None, ignore_invalid_inputs=False ): """ Filter examples that are too large Args: indices (np.array): original array of sample indices dataset (~fairseq.data.FairseqDataset): dataset to batch ...
Filter examples that are too large Args: indices (np.array): original array of sample indices dataset (~fairseq.data.FairseqDataset): dataset to batch max_positions (optional): max sentence length supported by the model (default: None). i...
filter_indices_by_size
python
OFA-Sys/OFA
fairseq/fairseq/tasks/fairseq_task.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/tasks/fairseq_task.py
Apache-2.0
def get_batch_iterator( self, dataset, max_tokens=None, max_sentences=None, max_positions=None, ignore_invalid_inputs=False, required_batch_size_multiple=1, seed=1, num_shards=1, shard_id=0, num_workers=0, epoch=1, d...
Get an iterator that yields batches of data from the given dataset. Args: dataset (~fairseq.data.FairseqDataset): dataset to batch max_tokens (int, optional): max number of tokens in each batch (default: None). max_sentences (int, optional): max numb...
get_batch_iterator
python
OFA-Sys/OFA
fairseq/fairseq/tasks/fairseq_task.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/tasks/fairseq_task.py
Apache-2.0
def build_model(self, cfg: FairseqDataclass): """ Build the :class:`~fairseq.models.BaseFairseqModel` instance for this task. Args: cfg (FairseqDataclass): configuration object Returns: a :class:`~fairseq.models.BaseFairseqModel` instance """ ...
Build the :class:`~fairseq.models.BaseFairseqModel` instance for this task. Args: cfg (FairseqDataclass): configuration object Returns: a :class:`~fairseq.models.BaseFairseqModel` instance
build_model
python
OFA-Sys/OFA
fairseq/fairseq/tasks/fairseq_task.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/tasks/fairseq_task.py
Apache-2.0
def build_criterion(self, cfg: DictConfig): """ Build the :class:`~fairseq.criterions.FairseqCriterion` instance for this task. Args: cfg (omegaconf.DictConfig): configration object Returns: a :class:`~fairseq.criterions.FairseqCriterion` instance ...
Build the :class:`~fairseq.criterions.FairseqCriterion` instance for this task. Args: cfg (omegaconf.DictConfig): configration object Returns: a :class:`~fairseq.criterions.FairseqCriterion` instance
build_criterion
python
OFA-Sys/OFA
fairseq/fairseq/tasks/fairseq_task.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/tasks/fairseq_task.py
Apache-2.0
def build_generator( self, models, args, seq_gen_cls=None, extra_gen_cls_kwargs=None, prefix_allowed_tokens_fn=None, ): """ Build a :class:`~fairseq.SequenceGenerator` instance for this task. Args: models (List[~fairseq.models.FairseqModel]): ensemble of models ...
Build a :class:`~fairseq.SequenceGenerator` instance for this task. Args: models (List[~fairseq.models.FairseqModel]): ensemble of models args (fairseq.dataclass.configs.GenerationConfig): configuration object (dataclass) for generation extra...
build_generator
python
OFA-Sys/OFA
fairseq/fairseq/tasks/fairseq_task.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/tasks/fairseq_task.py
Apache-2.0
def train_step( self, sample, model, criterion, optimizer, update_num, ignore_grad=False, **extra_kwargs ): """ Do forward and backward, and return the loss as computed by *criterion* for the given *model* and *sample*. Args: sample (dict): the mini-batch. The fo...
Do forward and backward, and return the loss as computed by *criterion* for the given *model* and *sample*. Args: sample (dict): the mini-batch. The format is defined by the :class:`~fairseq.data.FairseqDataset`. model (~fairseq.models.BaseFairseqModel):...
train_step
python
OFA-Sys/OFA
fairseq/fairseq/tasks/fairseq_task.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/tasks/fairseq_task.py
Apache-2.0
def aggregate_logging_outputs(self, logging_outputs, criterion): """[deprecated] Aggregate logging outputs from data parallel training.""" utils.deprecation_warning( "The aggregate_logging_outputs API is deprecated. " "Please use the reduce_metrics API instead." ) ...
[deprecated] Aggregate logging outputs from data parallel training.
aggregate_logging_outputs
python
OFA-Sys/OFA
fairseq/fairseq/tasks/fairseq_task.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/tasks/fairseq_task.py
Apache-2.0
def build_model(self, args: Namespace): """ Build the :class:`~fairseq.models.BaseFairseqModel` instance for this task. Args: args (argparse.Namespace): parsed command-line arguments Returns: a :class:`~fairseq.models.BaseFairseqModel` instance "...
Build the :class:`~fairseq.models.BaseFairseqModel` instance for this task. Args: args (argparse.Namespace): parsed command-line arguments Returns: a :class:`~fairseq.models.BaseFairseqModel` instance
build_model
python
OFA-Sys/OFA
fairseq/fairseq/tasks/fairseq_task.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/tasks/fairseq_task.py
Apache-2.0
def build_criterion(self, args: Namespace): """ Build the :class:`~fairseq.criterions.FairseqCriterion` instance for this task. Args: args (argparse.Namespace): parsed command-line arguments Returns: a :class:`~fairseq.criterions.FairseqCriterion` instan...
Build the :class:`~fairseq.criterions.FairseqCriterion` instance for this task. Args: args (argparse.Namespace): parsed command-line arguments Returns: a :class:`~fairseq.criterions.FairseqCriterion` instance
build_criterion
python
OFA-Sys/OFA
fairseq/fairseq/tasks/fairseq_task.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/tasks/fairseq_task.py
Apache-2.0
def setup_task(cls, args, **kwargs): """Setup the task (e.g., load dictionaries). Args: args (argparse.Namespace): parsed command-line arguments """ dictionary, output_dictionary = cls.setup_dictionary(args, **kwargs) # upgrade old checkpoints if getattr(arg...
Setup the task (e.g., load dictionaries). Args: args (argparse.Namespace): parsed command-line arguments
setup_task
python
OFA-Sys/OFA
fairseq/fairseq/tasks/language_modeling.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/tasks/language_modeling.py
Apache-2.0
def load_dataset( self, split: str, epoch=1, combine=False, **kwargs ) -> MonolingualDataset: """Load a given dataset split. Args: split (str): name of the split (e.g., train, valid, valid1, test) """ paths = utils.split_paths(self.args.data) assert len(p...
Load a given dataset split. Args: split (str): name of the split (e.g., train, valid, valid1, test)
load_dataset
python
OFA-Sys/OFA
fairseq/fairseq/tasks/language_modeling.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/tasks/language_modeling.py
Apache-2.0
def build_dataset_for_inference(self, src_tokens, src_lengths, **kwargs): """ Generate batches for inference. We prepend an eos token to src_tokens (or bos if `--add-bos-token` is set) and we append a <pad> to target. This is convenient both for generation with a prefix and LM scoring. ...
Generate batches for inference. We prepend an eos token to src_tokens (or bos if `--add-bos-token` is set) and we append a <pad> to target. This is convenient both for generation with a prefix and LM scoring.
build_dataset_for_inference
python
OFA-Sys/OFA
fairseq/fairseq/tasks/language_modeling.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/tasks/language_modeling.py
Apache-2.0
def _get_sample_prob(self, dataset_lens): """ Get smoothed sampling porbability by languages. This helps low resource languages by upsampling them. """ prob = dataset_lens / dataset_lens.sum() smoothed_prob = prob ** self.args.multilang_sampling_alpha smoothed_pro...
Get smoothed sampling porbability by languages. This helps low resource languages by upsampling them.
_get_sample_prob
python
OFA-Sys/OFA
fairseq/fairseq/tasks/multilingual_denoising.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/tasks/multilingual_denoising.py
Apache-2.0
def max_positions(self): """Return the max sentence length allowed by the task.""" if len(self.datasets.values()) == 0: return { "%s-%s" % (self.args.source_lang, self.args.target_lang): ( self.args.max_source_positions, ...
Return the max sentence length allowed by the task.
max_positions
python
OFA-Sys/OFA
fairseq/fairseq/tasks/multilingual_translation.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/tasks/multilingual_translation.py
Apache-2.0
def from_string(configuration: str) -> "PiecewiseLinearFn": """ Parse the configuration of lambda coefficient (for scheduling). x = "3" # lambda will be a constant equal to x x = "0:1,1000:0" # lambda will start from 1 and linearly decrease ...
Parse the configuration of lambda coefficient (for scheduling). x = "3" # lambda will be a constant equal to x x = "0:1,1000:0" # lambda will start from 1 and linearly decrease # to 0 during the first 1000 iterations x = "0:0,100...
from_string
python
OFA-Sys/OFA
fairseq/fairseq/tasks/online_backtranslation.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/tasks/online_backtranslation.py
Apache-2.0
def load_train_dataset(self, data_path: str) -> FairseqDataset: """The training dataset is made of backtranslation dataset and denoising dataset.""" data = [] for lang in self.mono_langs: train_path = os.path.join(data_path, lang, "train") # TODO: could we do the BT using...
The training dataset is made of backtranslation dataset and denoising dataset.
load_train_dataset
python
OFA-Sys/OFA
fairseq/fairseq/tasks/online_backtranslation.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/tasks/online_backtranslation.py
Apache-2.0
def load_bt_dataset(self, data_path: str, lang: str) -> FairseqDataset: """The BT dataset is generated with (tgt, tgt) pairs. The actual translation to a (generated_src, tgt) pair is done on the fly during training. """ mono_dataset = data_utils.load_indexed_dataset( ...
The BT dataset is generated with (tgt, tgt) pairs. The actual translation to a (generated_src, tgt) pair is done on the fly during training.
load_bt_dataset
python
OFA-Sys/OFA
fairseq/fairseq/tasks/online_backtranslation.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/tasks/online_backtranslation.py
Apache-2.0
def backtranslate_sample(self, smp, orig_lang, other_lang) -> None: """ * WARNING: smp is modified in place. * At the start of this function, `smp` has the same input and target: |--------------------------------------------------------| | smp['net_input']['src_tokens'] | sm...
* WARNING: smp is modified in place. * At the start of this function, `smp` has the same input and target: |--------------------------------------------------------| | smp['net_input']['src_tokens'] | smp['target'] | | (from data) __en__ hello world | __en__ hello...
backtranslate_sample
python
OFA-Sys/OFA
fairseq/fairseq/tasks/online_backtranslation.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/tasks/online_backtranslation.py
Apache-2.0
def parse_lambda_config(x): """ Parse the configuration of lambda coefficient (for scheduling). x = "3" # lambda will be a constant equal to x x = "0:1,1000:0" # lambda will start from 1 and linearly decrease # to 0 during the first 1000 iterations ...
Parse the configuration of lambda coefficient (for scheduling). x = "3" # lambda will be a constant equal to x x = "0:1,1000:0" # lambda will start from 1 and linearly decrease # to 0 during the first 1000 iterations x = "0:0,1000:0,2000:1" # lambd...
parse_lambda_config
python
OFA-Sys/OFA
fairseq/fairseq/tasks/semisupervised_translation.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/tasks/semisupervised_translation.py
Apache-2.0
def lambda_step_func(config, n_iter): """ Update a lambda value according to its schedule configuration. """ ranges = [ i for i in range(len(config) - 1) if config[i][0] <= n_iter < config[i + 1][0] ] ...
Update a lambda value according to its schedule configuration.
lambda_step_func
python
OFA-Sys/OFA
fairseq/fairseq/tasks/semisupervised_translation.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/tasks/semisupervised_translation.py
Apache-2.0
def antidiag_indices(offset, min_i=0, max_i=None, min_j=0, max_j=None): """ for a (3, 4) matrix with min_i=1, max_i=3, min_j=1, max_j=4, outputs offset=2 (1, 1), offset=3 (2, 1), (1, 2) offset=4 (2, 2), (1, 3) offset=5 (2, 3) constraints: i + j = offset min_j <= j < max_j ...
for a (3, 4) matrix with min_i=1, max_i=3, min_j=1, max_j=4, outputs offset=2 (1, 1), offset=3 (2, 1), (1, 2) offset=4 (2, 2), (1, 3) offset=5 (2, 3) constraints: i + j = offset min_j <= j < max_j min_i <= offset - j < max_i
antidiag_indices
python
OFA-Sys/OFA
fairseq/fairseq/tasks/text_to_speech.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/tasks/text_to_speech.py
Apache-2.0
def batch_dynamic_time_warping(distance, shapes=None): """full batched DTW without any constraints distance: (batchsize, max_M, max_N) matrix shapes: (batchsize,) vector specifying (M, N) for each entry """ # ptr: 0=left, 1=up-left, 2=up ptr2dij = {0: (0, -1), 1: (-1, -1), 2: (-1, 0)} bsz...
full batched DTW without any constraints distance: (batchsize, max_M, max_N) matrix shapes: (batchsize,) vector specifying (M, N) for each entry
batch_dynamic_time_warping
python
OFA-Sys/OFA
fairseq/fairseq/tasks/text_to_speech.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/tasks/text_to_speech.py
Apache-2.0
def batch_mel_cepstral_distortion( y1, y2, sr, normalize_type="path", mfcc_fn=None ): """ https://arxiv.org/pdf/2011.03568.pdf The root mean squared error computed on 13-dimensional MFCC using DTW for alignment. MFCC features are computed from an 80-channel log-mel spectrogram using a 50ms ...
ERROR: type should be string, got "\n https://arxiv.org/pdf/2011.03568.pdf\n\n The root mean squared error computed on 13-dimensional MFCC using DTW for\n alignment. MFCC features are computed from an 80-channel log-mel\n spectrogram using a 50ms Hann window and hop of 12.5ms.\n\n y1: list of waveforms\n y2: list of waveforms\n sr: sampling rate\n "
batch_mel_cepstral_distortion
python
OFA-Sys/OFA
fairseq/fairseq/tasks/text_to_speech.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/tasks/text_to_speech.py
Apache-2.0
def get_batch_iterator( self, dataset, max_tokens=None, max_sentences=None, max_positions=None, ignore_invalid_inputs=False, required_batch_size_multiple=1, seed=1, num_shards=1, shard_id=0, num_workers=0, epoch=1, d...
Get an iterator that yields batches of data from the given dataset. Args: dataset (~fairseq.data.FairseqDataset): dataset to batch max_tokens (int, optional): max number of tokens in each batch (default: None). max_sentences (int, optional): max numb...
get_batch_iterator
python
OFA-Sys/OFA
fairseq/fairseq/tasks/translation_multi_simple_epoch.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/tasks/translation_multi_simple_epoch.py
Apache-2.0
def register_task(name, dataclass=None): """ New tasks can be added to fairseq with the :func:`~fairseq.tasks.register_task` function decorator. For example:: @register_task('classification') class ClassificationTask(FairseqTask): (...) .. note:: All Tasks mus...
New tasks can be added to fairseq with the :func:`~fairseq.tasks.register_task` function decorator. For example:: @register_task('classification') class ClassificationTask(FairseqTask): (...) .. note:: All Tasks must implement the :class:`~fairseq.tasks.FairseqTa...
register_task
python
OFA-Sys/OFA
fairseq/fairseq/tasks/__init__.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/tasks/__init__.py
Apache-2.0
def eval_lm( models: List[fairseq.models.FairseqModel], source_dictionary: fairseq.data.Dictionary, batch_iterator: Iterable, post_process: Optional[str] = None, output_word_probs: bool = False, output_word_stats: bool = False, target_dictionary: Optional[fairseq.data.Dictionary] = None, ...
Args: models (List[~fairseq.models.FairseqModel]): list of models to evaluate. Models are essentially `nn.Module` instances, but must be compatible with fairseq's `SequenceScorer`. source_dictionary (~fairseq.data.Dictionary): dictionary for applying any relevant...
eval_lm
python
OFA-Sys/OFA
fairseq/fairseq_cli/eval_lm.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq_cli/eval_lm.py
Apache-2.0
def add(self, log_prob, next_word_prob): """increments counters for the sum of log probs of current word and next word (given context ending at current word). Since the next word might be at the end of the example, or it might be not counted because it is not an ending subword unit, also...
increments counters for the sum of log probs of current word and next word (given context ending at current word). Since the next word might be at the end of the example, or it might be not counted because it is not an ending subword unit, also keeps track of how many of those we have seen
add
python
OFA-Sys/OFA
fairseq/fairseq_cli/eval_lm.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq_cli/eval_lm.py
Apache-2.0
def average_checkpoints(inputs): """Loads checkpoints from inputs and returns a model with averaged weights. Args: inputs: An iterable of string paths of checkpoints to load from. Returns: A dict of string keys mapping to various values. The 'model' key from the returned dict should corr...
Loads checkpoints from inputs and returns a model with averaged weights. Args: inputs: An iterable of string paths of checkpoints to load from. Returns: A dict of string keys mapping to various values. The 'model' key from the returned dict should correspond to an OrderedDict mapping s...
average_checkpoints
python
OFA-Sys/OFA
fairseq/scripts/average_checkpoints.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/scripts/average_checkpoints.py
Apache-2.0
def test_activation_offloading_does_not_change_metrics(self): """Neither ----checkpoint-activations nor --offload-activations should change loss""" with tempfile.TemporaryDirectory("test_transformer_with_act_cpt") as data_dir: with self.assertLogs(): create_dummy_data(data_d...
Neither ----checkpoint-activations nor --offload-activations should change loss
test_activation_offloading_does_not_change_metrics
python
OFA-Sys/OFA
fairseq/tests/test_binaries.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/tests/test_binaries.py
Apache-2.0
def test_activation_checkpointing_does_not_change_metrics(self): """--checkpoint-activations should not change loss""" with tempfile.TemporaryDirectory("test_transformer_with_act_cpt") as data_dir: with self.assertLogs(): create_dummy_data(data_dir, num_examples=20) ...
--checkpoint-activations should not change loss
test_activation_checkpointing_does_not_change_metrics
python
OFA-Sys/OFA
fairseq/tests/test_binaries.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/tests/test_binaries.py
Apache-2.0
def test_packing(self): """Ensures the list of lists of tensors gets packed correctly.""" for batch_constraints, expected_tensor in self.examples: packed = pack_constraints(batch_constraints) assert torch.equal(packed, expected_tensor)
Ensures the list of lists of tensors gets packed correctly.
test_packing
python
OFA-Sys/OFA
fairseq/tests/test_constraints.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/tests/test_constraints.py
Apache-2.0
def test_graphs(self): """ Test whether unordered graph systems are created correctly. """ for example in self.examples: constraints, expected, gold_counts = example c = ConstraintNode.create(constraints) assert ( ConstraintNode.print_g...
Test whether unordered graph systems are created correctly.
test_graphs
python
OFA-Sys/OFA
fairseq/tests/test_constraints.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/tests/test_constraints.py
Apache-2.0
def test_next_tokens(self): """ Tests that the set of next tokens is correct. """ for example in self.examples: constraints, expected, gold_counts = example root = ConstraintNode.create(constraints) root_tokens = set(root.children.keys()) ...
Tests that the set of next tokens is correct.
test_next_tokens
python
OFA-Sys/OFA
fairseq/tests/test_constraints.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/tests/test_constraints.py
Apache-2.0
def batch_by_size_baseline( cls, indices, num_tokens_vec, max_tokens, max_sentences, bsz_mult, ): """Simple, reliable and slow implementation of batch by size """ batches = [] start = 0 while start < len(indices): for end in...
Simple, reliable and slow implementation of batch by size
batch_by_size_baseline
python
OFA-Sys/OFA
fairseq/tests/test_data_utils.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/tests/test_data_utils.py
Apache-2.0
def _run_compare_with_baseline_sweep(self, batch_by_size_impl): """Compare reference batch_by_size implementation with batch_by_size_baseline across a dense grid of hyperparam values""" MAX_MAX_TOKENS = 10 NUM_TOKENS_VECS_COUNT = 5 for indices_len in [10, 11]: # try odd and even...
Compare reference batch_by_size implementation with batch_by_size_baseline across a dense grid of hyperparam values
_run_compare_with_baseline_sweep
python
OFA-Sys/OFA
fairseq/tests/test_data_utils.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/tests/test_data_utils.py
Apache-2.0
def __init__(self) -> None: """LightningModule for testing purposes Args: epoch_min_loss_override (int, optional): Pass in an epoch that will be set to the minimum validation loss for testing purposes (zero based). If None this is ignored. Defaults to None. """ ...
LightningModule for testing purposes Args: epoch_min_loss_override (int, optional): Pass in an epoch that will be set to the minimum validation loss for testing purposes (zero based). If None this is ignored. Defaults to None.
__init__
python
OFA-Sys/OFA
fairseq/tests/test_ema.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/tests/test_ema.py
Apache-2.0
def get_dummy_task_and_parser(): """ Return a dummy task and argument parser, which can be used to create a model/criterion. """ parser = argparse.ArgumentParser( description="test_dummy_s2s_task", argument_default=argparse.SUPPRESS ) DummyTask.add_args(parser) args = parser.pars...
Return a dummy task and argument parser, which can be used to create a model/criterion.
get_dummy_task_and_parser
python
OFA-Sys/OFA
fairseq/tests/test_export.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/tests/test_export.py
Apache-2.0
def get_dummy_task_and_parser(): """ to build a fariseq model, we need some dummy parse and task. This function is used to create dummy task and parser to faciliate model/criterion test Note: we use FbSpeechRecognitionTask as the dummy task. You may want to use other task by providing another funct...
to build a fariseq model, we need some dummy parse and task. This function is used to create dummy task and parser to faciliate model/criterion test Note: we use FbSpeechRecognitionTask as the dummy task. You may want to use other task by providing another function
get_dummy_task_and_parser
python
OFA-Sys/OFA
fairseq/tests/test_lstm_jitable.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/tests/test_lstm_jitable.py
Apache-2.0
def _get_test_data_with_bpe_cont_marker(self, append_eos=True): """ Args: append_eos: if True, each input sentence in the source tokens tensor will have an EOS appended to the end. Returns: vocabs: BPE vocab with continuation markers as suffixes to denote...
Args: append_eos: if True, each input sentence in the source tokens tensor will have an EOS appended to the end. Returns: vocabs: BPE vocab with continuation markers as suffixes to denote non-end of word tokens. This is the standard BPE format us...
_get_test_data_with_bpe_cont_marker
python
OFA-Sys/OFA
fairseq/tests/test_noising.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/tests/test_noising.py
Apache-2.0
def _get_test_data_with_bpe_end_marker(self, append_eos=True): """ Args: append_eos: if True, each input sentence in the source tokens tensor will have an EOS appended to the end. Returns: vocabs: BPE vocab with end-of-word markers as suffixes to denote ...
Args: append_eos: if True, each input sentence in the source tokens tensor will have an EOS appended to the end. Returns: vocabs: BPE vocab with end-of-word markers as suffixes to denote tokens at the end of a word. This is an alternative to fair...
_get_test_data_with_bpe_end_marker
python
OFA-Sys/OFA
fairseq/tests/test_noising.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/tests/test_noising.py
Apache-2.0
def _get_test_data_with_word_vocab(self, append_eos=True): """ Args: append_eos: if True, each input sentence in the source tokens tensor will have an EOS appended to the end. Returns: vocabs: word vocab x: input tensor containing numberized s...
Args: append_eos: if True, each input sentence in the source tokens tensor will have an EOS appended to the end. Returns: vocabs: word vocab x: input tensor containing numberized source tokens, with EOS at the end if append_eos is tru...
_get_test_data_with_word_vocab
python
OFA-Sys/OFA
fairseq/tests/test_noising.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/tests/test_noising.py
Apache-2.0
def assert_eos_at_end(self, x, x_len, eos): """Asserts last token of every sentence in x is EOS """ for i in range(len(x_len)): self.assertEqual( x[x_len[i] - 1][i], eos, ( "Expected eos (token id {eos}) at the end of senten...
Asserts last token of every sentence in x is EOS
assert_eos_at_end
python
OFA-Sys/OFA
fairseq/tests/test_noising.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/tests/test_noising.py
Apache-2.0
def assert_word_shuffle_matches_expected( self, x, x_len, max_shuffle_distance: int, vocab: Dictionary, expected_shufle_maps: List[Dict[int, int]], expect_eos_at_end: bool, bpe_end_marker=None, ): """ This verifies that with a given x, ...
This verifies that with a given x, x_len, max_shuffle_distance, and vocab, we get the expected shuffle result. Args: x: Tensor of shape (T x B) = (sequence_length, batch_size) x_len: Tensor of length B = batch_size max_shuffle_distance: arg to pass to noisin...
assert_word_shuffle_matches_expected
python
OFA-Sys/OFA
fairseq/tests/test_noising.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/tests/test_noising.py
Apache-2.0
def test_word_shuffle_with_eos_nonbpe(self): """The purpose of this is to test shuffling logic with word vocabs""" vocab, x, x_len = self._get_test_data_with_word_vocab(append_eos=True) # Assert word shuffle with max shuffle distance 0 causes input to be # unchanged self.assert_...
The purpose of this is to test shuffling logic with word vocabs
test_word_shuffle_with_eos_nonbpe
python
OFA-Sys/OFA
fairseq/tests/test_noising.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/tests/test_noising.py
Apache-2.0
def test_word_shuffle_without_eos(self): """Same result as word shuffle with eos except no EOS at end""" vocab, x, x_len = self._get_test_data_with_bpe_cont_marker(append_eos=False) # Assert word shuffle with max shuffle distance 0 causes input to be # unchanged self.assert_word...
Same result as word shuffle with eos except no EOS at end
test_word_shuffle_without_eos
python
OFA-Sys/OFA
fairseq/tests/test_noising.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/tests/test_noising.py
Apache-2.0
def test_word_shuffle_without_eos_with_bpe_end_marker(self): """Same result as word shuffle without eos except using BPE end token""" vocab, x, x_len = self._get_test_data_with_bpe_end_marker(append_eos=False) # Assert word shuffle with max shuffle distance 0 causes input to be # unchan...
Same result as word shuffle without eos except using BPE end token
test_word_shuffle_without_eos_with_bpe_end_marker
python
OFA-Sys/OFA
fairseq/tests/test_noising.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/tests/test_noising.py
Apache-2.0
def assert_no_eos_at_end(self, x, x_len, eos): """Asserts that the last token of each sentence in x is not EOS """ for i in range(len(x_len)): self.assertNotEqual( x[x_len[i] - 1][i], eos, "Expected no eos (token id {eos}) at the end of sentenc...
Asserts that the last token of each sentence in x is not EOS
assert_no_eos_at_end
python
OFA-Sys/OFA
fairseq/tests/test_noising.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/tests/test_noising.py
Apache-2.0
def test_word_dropout_without_eos(self): """Same result as word dropout with eos except no EOS at end""" vocab, x, x_len = self._get_test_data_with_bpe_cont_marker(append_eos=False) with data_utils.numpy_seed(1234): noising_gen = noising.WordDropout(vocab) x_noised, l_no...
Same result as word dropout with eos except no EOS at end
test_word_dropout_without_eos
python
OFA-Sys/OFA
fairseq/tests/test_noising.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/tests/test_noising.py
Apache-2.0
def test_word_blank_without_eos(self): """Same result as word blank with eos except no EOS at end""" vocab, x, x_len = self._get_test_data_with_bpe_cont_marker(append_eos=False) with data_utils.numpy_seed(1234): noising_gen = noising.WordDropout(vocab) x_noised, l_noised...
Same result as word blank with eos except no EOS at end
test_word_blank_without_eos
python
OFA-Sys/OFA
fairseq/tests/test_noising.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/tests/test_noising.py
Apache-2.0
def _get_noising_dataset_batch( self, src_tokens_no_pad, src_dict, append_eos_to_tgt=False, ): """ Constructs a NoisingDataset and the corresponding ``LanguagePairDataset(NoisingDataset(src), src)``. If *append_eos_to_tgt* is True, wrap the source data...
Constructs a NoisingDataset and the corresponding ``LanguagePairDataset(NoisingDataset(src), src)``. If *append_eos_to_tgt* is True, wrap the source dataset in :class:`TransformEosDataset` to append EOS to the clean source when using it as the target.
_get_noising_dataset_batch
python
OFA-Sys/OFA
fairseq/tests/test_noising.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/tests/test_noising.py
Apache-2.0
def test_noising_dataset_without_eos(self): """ Similar to test noising dataset with eos except that we have to set *append_eos_to_tgt* to ``True``. """ src_dict, src_tokens, _ = self._get_test_data_with_bpe_cont_marker( append_eos=False ) # Format d...
Similar to test noising dataset with eos except that we have to set *append_eos_to_tgt* to ``True``.
test_noising_dataset_without_eos
python
OFA-Sys/OFA
fairseq/tests/test_noising.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/tests/test_noising.py
Apache-2.0
def test_roberta_batching(self, device: str): """ Checks that the batch of size 2 give twice the same results than the batch of size 1. """ _, model = get_toy_model(device) sample = mk_sample("en", device, batch_size=1) slen = sample["net_input"]["src_lengths"][0] ...
Checks that the batch of size 2 give twice the same results than the batch of size 1.
test_roberta_batching
python
OFA-Sys/OFA
fairseq/tests/test_roberta.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/tests/test_roberta.py
Apache-2.0
def test_roberta_incremental_decoder(self, device: str): """ Checks that incremental decoding yields the same result than non incremental one. """ task, model = get_toy_model(device) en_sample = mk_sample("en", device) en_tokens = en_sample["net_input"]["src_tokens"] ...
Checks that incremental decoding yields the same result than non incremental one.
test_roberta_incremental_decoder
python
OFA-Sys/OFA
fairseq/tests/test_roberta.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/tests/test_roberta.py
Apache-2.0
def test_ngram_blocking_same_as_default_implem(self): """Test that cuda extension returns same things as default impl in many settings.""" vocab_size = 4 step = 6 for _ in range(2): block_param = np.random.choice([1, 2, 3, 4]) batch_size = np.random.randint(1, 8) ...
Test that cuda extension returns same things as default impl in many settings.
test_ngram_blocking_same_as_default_implem
python
OFA-Sys/OFA
fairseq/tests/test_sequence_generator.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/tests/test_sequence_generator.py
Apache-2.0
def _compare_cuda_ext_to_default_implem( self, bsz, beam_size, generated_tok, lprobs, step, block_param ): """Assert that cuda extension and default implem return the same thing.""" blocker = NGramRepeatBlock(block_param) assert blocker.use_extension, "Extension not compiled" ...
Assert that cuda extension and default implem return the same thing.
_compare_cuda_ext_to_default_implem
python
OFA-Sys/OFA
fairseq/tests/test_sequence_generator.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/tests/test_sequence_generator.py
Apache-2.0
def test_4billion_tokens(self): """Regression test for numpy type promotion issue https://github.com/numpy/numpy/issues/5745""" data = [torch.tensor(list(range(10000)), dtype=torch.long)] * 430000 ds = self._build_dataset( data, block_size=6, pad=0, eos=1, break_mode="complete" ...
Regression test for numpy type promotion issue https://github.com/numpy/numpy/issues/5745
test_4billion_tokens
python
OFA-Sys/OFA
fairseq/tests/test_token_block_dataset.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/tests/test_token_block_dataset.py
Apache-2.0
def setup_model_loss_criterion(cfg, args, rank, is_cuda): """ setup model, criterion and optimizer based on input args """ args.distributed_rank = rank cfg.distributed_training.distributed_rank = args.distributed_rank if cfg.distributed_training.distributed_world_size > 1: distributed_ut...
setup model, criterion and optimizer based on input args
setup_model_loss_criterion
python
OFA-Sys/OFA
fairseq/tests/distributed/test_bmuf.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/tests/distributed/test_bmuf.py
Apache-2.0
def get_dummy_encoder_output(encoder_out_shape=(100, 80, 5)): """ This only provides an example to generate dummy encoder output """ (T, B, D) = encoder_out_shape encoder_out = {} encoder_out["encoder_out"] = torch.from_numpy( np.random.randn(*encoder_out_shape).astype(np.float32) )...
This only provides an example to generate dummy encoder output
get_dummy_encoder_output
python
OFA-Sys/OFA
fairseq/tests/speech_recognition/asr_test_base.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/tests/speech_recognition/asr_test_base.py
Apache-2.0
def check_encoder_output(encoder_output, batch_size=None): """we expect encoder_output to be a dict with the following key/value pairs: - encoder_out: a Torch.Tensor - encoder_padding_mask: a binary Torch.Tensor """ if not isinstance(encoder_output, dict): msg = ( "FairseqEnc...
we expect encoder_output to be a dict with the following key/value pairs: - encoder_out: a Torch.Tensor - encoder_padding_mask: a binary Torch.Tensor
check_encoder_output
python
OFA-Sys/OFA
fairseq/tests/speech_recognition/asr_test_base.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/tests/speech_recognition/asr_test_base.py
Apache-2.0
def check_decoder_output(decoder_output): """we expect output from a decoder is a tuple with the following constraint: - the first element is a torch.Tensor - the second element can be anything (reserved for future use) """ if not isinstance(decoder_output, tuple): msg = "FariseqDecoder outp...
we expect output from a decoder is a tuple with the following constraint: - the first element is a torch.Tensor - the second element can be anything (reserved for future use)
check_decoder_output
python
OFA-Sys/OFA
fairseq/tests/speech_recognition/asr_test_base.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/tests/speech_recognition/asr_test_base.py
Apache-2.0
def get_src_tokens(self, correct_prediction, aggregate): """ correct_prediction: True if the net_output (src_tokens) should predict the correct target aggregate: True if the criterion expects net_output (src_tokens) aggregated across time axis """ predicted_idx = ...
correct_prediction: True if the net_output (src_tokens) should predict the correct target aggregate: True if the criterion expects net_output (src_tokens) aggregated across time axis
get_src_tokens
python
OFA-Sys/OFA
fairseq/tests/speech_recognition/asr_test_base.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/tests/speech_recognition/asr_test_base.py
Apache-2.0
def override_config(args): """ vggtrasformer_1 use 14 layers of transformer, for testing purpose, it is too expensive. For fast turn-around test, reduce the number of layers to 3. """ args.transformer_enc_config = ( "((1024, 16, 409...
vggtrasformer_1 use 14 layers of transformer, for testing purpose, it is too expensive. For fast turn-around test, reduce the number of layers to 3.
override_config
python
OFA-Sys/OFA
fairseq/tests/speech_recognition/test_vggtransformer.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/tests/speech_recognition/test_vggtransformer.py
Apache-2.0
def override_config(args): """ vggtrasformer_2 use 16 layers of transformer, for testing purpose, it is too expensive. For fast turn-around test, reduce the number of layers to 3. """ args.transformer_enc_config = ( "((1024, 16, 409...
vggtrasformer_2 use 16 layers of transformer, for testing purpose, it is too expensive. For fast turn-around test, reduce the number of layers to 3.
override_config
python
OFA-Sys/OFA
fairseq/tests/speech_recognition/test_vggtransformer.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/tests/speech_recognition/test_vggtransformer.py
Apache-2.0
def override_config(args): """ vggtrasformer_base use 12 layers of transformer, for testing purpose, it is too expensive. For fast turn-around test, reduce the number of layers to 3. """ args.transformer_enc_config = ( "((512, 8, 20...
vggtrasformer_base use 12 layers of transformer, for testing purpose, it is too expensive. For fast turn-around test, reduce the number of layers to 3.
override_config
python
OFA-Sys/OFA
fairseq/tests/speech_recognition/test_vggtransformer.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/tests/speech_recognition/test_vggtransformer.py
Apache-2.0
def load(name: str, device: Union[str, torch.device] = "cuda" if torch.cuda.is_available() else "cpu", jit: bool = False, download_root: str = None): """Load a CLIP model Parameters ---------- name : str A model name listed by `clip.available_models()`, or the path to a model checkpoint contain...
Load a CLIP model Parameters ---------- name : str A model name listed by `clip.available_models()`, or the path to a model checkpoint containing the state_dict device : Union[str, torch.device] The device to put the loaded model jit : bool Whether to load the optimized JI...
load
python
OFA-Sys/OFA
models/clip/clip.py
https://github.com/OFA-Sys/OFA/blob/master/models/clip/clip.py
Apache-2.0
def tokenize(texts: Union[str, List[str]], context_length: int = 77, truncate: bool = False) -> torch.LongTensor: """ Returns the tokenized representation of given input string(s) Parameters ---------- texts : Union[str, List[str]] An input string or a list of input strings to tokenize ...
Returns the tokenized representation of given input string(s) Parameters ---------- texts : Union[str, List[str]] An input string or a list of input strings to tokenize context_length : int The context length to use; all CLIP models use 77 as the context length truncate: bool...
tokenize
python
OFA-Sys/OFA
models/clip/clip.py
https://github.com/OFA-Sys/OFA/blob/master/models/clip/clip.py
Apache-2.0
def forward( self, x: torch.Tensor, x_length: torch.Tensor ) -> Tuple[torch.Tensor, torch.Tensor]: """Subsample x. Args: x (torch.Tensor): Input tensor (#batch, time, idim). x_mask (torch.Tensor): Input mask (#batch, 1, time). Ret...
Subsample x. Args: x (torch.Tensor): Input tensor (#batch, time, idim). x_mask (torch.Tensor): Input mask (#batch, 1, time). Returns: torch.Tensor: Subsampled tensor (#batch, time', odim), where time' = time // 4. torch.Tensor: Subsampled...
forward
python
OFA-Sys/OFA
models/ofa/ofa_speech.py
https://github.com/OFA-Sys/OFA/blob/master/models/ofa/ofa_speech.py
Apache-2.0
def drop_path(x, drop_prob: float = 0., training: bool = False): """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). This is the same as the DropConnect impl I created for EfficientNet, etc networks, however, the original name is misleading as 'Drop Connect' is a.sh d...
Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). This is the same as the DropConnect impl I created for EfficientNet, etc networks, however, the original name is misleading as 'Drop Connect' is a.sh different form of dropout in a.sh separate paper... See discussion: h...
drop_path
python
OFA-Sys/OFA
models/ofa/resnet.py
https://github.com/OFA-Sys/OFA/blob/master/models/ofa/resnet.py
Apache-2.0
def drop_path(x, drop_prob: float = 0.0, training: bool = False): """ Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks, however, the original name is mislea...
Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks, however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
drop_path
python
OFA-Sys/OFA
models/ofa/unify_transformer_layer.py
https://github.com/OFA-Sys/OFA/blob/master/models/ofa/unify_transformer_layer.py
Apache-2.0
def forward(self, z): """ Inputs the output of the encoder network z and maps it to a discrete one-hot vector that is the index of the closest embedding vector e_j z (continuous) -> z_q (discrete) z.shape = (batch, channel, height, width) quantization pipeline: ...
Inputs the output of the encoder network z and maps it to a discrete one-hot vector that is the index of the closest embedding vector e_j z (continuous) -> z_q (discrete) z.shape = (batch, channel, height, width) quantization pipeline: 1. get encoder input (B,C,H,W) ...
forward
python
OFA-Sys/OFA
models/taming/modules/vqvae/quantize.py
https://github.com/OFA-Sys/OFA/blob/master/models/taming/modules/vqvae/quantize.py
Apache-2.0
def evaluate_on_coco_caption(res_file, label_file, outfile=None): """ res_file: txt file, each row is [image_key, json format list of captions]. Each caption is a dict, with fields "caption", "conf". label_file: JSON file of ground truth captions in COCO format. """ coco = COCO(label_fi...
res_file: txt file, each row is [image_key, json format list of captions]. Each caption is a dict, with fields "caption", "conf". label_file: JSON file of ground truth captions in COCO format.
evaluate_on_coco_caption
python
OFA-Sys/OFA
run_scripts/caption/coco_eval.py
https://github.com/OFA-Sys/OFA/blob/master/run_scripts/caption/coco_eval.py
Apache-2.0
def get_activations(images, model, batch_size=64, dims=2048, cuda=False, verbose=True): """Calculates the activations of the pool_3 layer for all images. Params: -- images : Numpy array of dimension (n_images, 3, hi, wi). The values must lie between 0 and 1. -- model : I...
Calculates the activations of the pool_3 layer for all images. Params: -- images : Numpy array of dimension (n_images, 3, hi, wi). The values must lie between 0 and 1. -- model : Instance of inception model -- batch_size : the images numpy array is split into batches wi...
get_activations
python
OFA-Sys/OFA
run_scripts/image_gen/fid_score.py
https://github.com/OFA-Sys/OFA/blob/master/run_scripts/image_gen/fid_score.py
Apache-2.0
def calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6): """Numpy implementation of the Frechet Distance. The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1) and X_2 ~ N(mu_2, C_2) is d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)). Stable version...
Numpy implementation of the Frechet Distance. The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1) and X_2 ~ N(mu_2, C_2) is d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)). Stable version by Dougal J. Sutherland. Params: -- mu1 : Numpy array containin...
calculate_frechet_distance
python
OFA-Sys/OFA
run_scripts/image_gen/fid_score.py
https://github.com/OFA-Sys/OFA/blob/master/run_scripts/image_gen/fid_score.py
Apache-2.0
def calculate_activation_statistics(images, model, batch_size=64, dims=2048, cuda=False, verbose=True): """Calculation of the statistics used by the FID. Params: -- images : Numpy array of dimension (n_images, 3, hi, wi). The values must lie betw...
Calculation of the statistics used by the FID. Params: -- images : Numpy array of dimension (n_images, 3, hi, wi). The values must lie between 0 and 1. -- model : Instance of inception model -- batch_size : The images numpy array is split into batches with ...
calculate_activation_statistics
python
OFA-Sys/OFA
run_scripts/image_gen/fid_score.py
https://github.com/OFA-Sys/OFA/blob/master/run_scripts/image_gen/fid_score.py
Apache-2.0