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 on_thread_stop(self) -> None: """Override this method instead of :meth:`stop()`. :meth:`stop()` calls this method. This method is called immediately after the thread is signaled to stop. """
Override this method instead of :meth:`stop()`. :meth:`stop()` calls this method. This method is called immediately after the thread is signaled to stop.
on_thread_stop
python
gorakhargosh/watchdog
src/watchdog/utils/__init__.py
https://github.com/gorakhargosh/watchdog/blob/master/src/watchdog/utils/__init__.py
Apache-2.0
def on_thread_start(self) -> None: """Override this method instead of :meth:`start()`. :meth:`start()` calls this method. This method is called right before this thread is started and this object's run() method is invoked. """
Override this method instead of :meth:`start()`. :meth:`start()` calls this method. This method is called right before this thread is started and this object's run() method is invoked.
on_thread_start
python
gorakhargosh/watchdog
src/watchdog/utils/__init__.py
https://github.com/gorakhargosh/watchdog/blob/master/src/watchdog/utils/__init__.py
Apache-2.0
def load_module(module_name: str) -> ModuleType: """Imports a module given its name and returns a handle to it.""" try: __import__(module_name) except ImportError as e: error = f"No module named {module_name}" raise ImportError(error) from e return sys.modules[module_name]
Imports a module given its name and returns a handle to it.
load_module
python
gorakhargosh/watchdog
src/watchdog/utils/__init__.py
https://github.com/gorakhargosh/watchdog/blob/master/src/watchdog/utils/__init__.py
Apache-2.0
def load_class(dotted_path: str) -> type[Trick]: """Loads and returns a class definition provided a dotted path specification the last part of the dotted path is the class name and there is at least one module name preceding the class name. Notes ----- You will need to ensure that the module yo...
Loads and returns a class definition provided a dotted path specification the last part of the dotted path is the class name and there is at least one module name preceding the class name. Notes ----- You will need to ensure that the module you are trying to load exists in the Python path. ...
load_class
python
gorakhargosh/watchdog
src/watchdog/utils/__init__.py
https://github.com/gorakhargosh/watchdog/blob/master/src/watchdog/utils/__init__.py
Apache-2.0
def _no_thread_leaks(): """ Fail on thread leak. We do not use pytest-threadleak because it is not reliable. """ old_thread_count = threading.active_count() yield gc.collect() # Clear the stuff from other function-level fixtures assert threading.active_count() == old_thread_count # Onl...
Fail on thread leak. We do not use pytest-threadleak because it is not reliable.
_no_thread_leaks
python
gorakhargosh/watchdog
tests/conftest.py
https://github.com/gorakhargosh/watchdog/blob/master/tests/conftest.py
Apache-2.0
def mkdir(path, *, parents=False): """Creates a directory (optionally also creates all the parent directories in the path).""" if parents: try: os.makedirs(path) except OSError as e: if e.errno != errno.EEXIST: raise else: os.mkdir(path)
Creates a directory (optionally also creates all the parent directories in the path).
mkdir
python
gorakhargosh/watchdog
tests/shell.py
https://github.com/gorakhargosh/watchdog/blob/master/tests/shell.py
Apache-2.0
def touch(path, times=None): """Updates the modified timestamp of a file or directory.""" if os.path.isdir(path): os.utime(path, times) else: with open(path, "ab"): os.utime(path, times)
Updates the modified timestamp of a file or directory.
touch
python
gorakhargosh/watchdog
tests/shell.py
https://github.com/gorakhargosh/watchdog/blob/master/tests/shell.py
Apache-2.0
def msize(path): """Modify the file size without updating the modified time.""" with open(path, "w") as w: w.write("") os.utime(path, (0, 0)) time.sleep(0.4) with open(path, "w") as w: w.write("0") os.utime(path, (0, 0))
Modify the file size without updating the modified time.
msize
python
gorakhargosh/watchdog
tests/shell.py
https://github.com/gorakhargosh/watchdog/blob/master/tests/shell.py
Apache-2.0
def test_load_config_valid(tmpdir): """Verifies the load of a valid yaml file""" yaml_file = os.path.join(tmpdir, "config_file.yaml") with open(yaml_file, "w") as f: f.write("one: value\ntwo:\n- value1\n- value2\n") config = watchmedo.load_config(yaml_file) assert isinstance(config, dict) ...
Verifies the load of a valid yaml file
test_load_config_valid
python
gorakhargosh/watchdog
tests/test_0_watchmedo.py
https://github.com/gorakhargosh/watchdog/blob/master/tests/test_0_watchmedo.py
Apache-2.0
def test_load_config_invalid(tmpdir): """Verifies if safe load avoid the execution of untrusted code inside yaml files""" critical_dir = os.path.join(tmpdir, "critical") yaml_file = os.path.join(tmpdir, "tricks_file.yaml") with open(yaml_file, "w") as f: content = f'one: value\nrun: !!pytho...
Verifies if safe load avoid the execution of untrusted code inside yaml files
test_load_config_invalid
python
gorakhargosh/watchdog
tests/test_0_watchmedo.py
https://github.com/gorakhargosh/watchdog/blob/master/tests/test_0_watchmedo.py
Apache-2.0
def test_auto_restart_on_file_change_debounce(tmpdir, capfd): """Simulate changing 3 files quickly and then another change later. Expect 2 restarts due to debouncing. """ script = make_dummy_script(tmpdir, n=2) trick = AutoRestartTrick([sys.executable, script], debounce_interval_seconds=0.5) tr...
Simulate changing 3 files quickly and then another change later. Expect 2 restarts due to debouncing.
test_auto_restart_on_file_change_debounce
python
gorakhargosh/watchdog
tests/test_0_watchmedo.py
https://github.com/gorakhargosh/watchdog/blob/master/tests/test_0_watchmedo.py
Apache-2.0
def test_auto_restart_subprocess_termination(tmpdir, capfd, restart_on_command_exit): """Run auto-restart with a script that terminates in about 2 seconds. After 5 seconds, expect it to have been restarted at least once. """ script = make_dummy_script(tmpdir, n=2) trick = AutoRestartTrick([sys.exec...
Run auto-restart with a script that terminates in about 2 seconds. After 5 seconds, expect it to have been restarted at least once.
test_auto_restart_subprocess_termination
python
gorakhargosh/watchdog
tests/test_0_watchmedo.py
https://github.com/gorakhargosh/watchdog/blob/master/tests/test_0_watchmedo.py
Apache-2.0
def test_add_watch_twice(observer: BaseObserver, p: P) -> None: """Adding the same watch twice used to result in a null pointer return without an exception. See https://github.com/gorakhargosh/watchdog/issues/765 """ a = p("a") mkdir(a) h = FileSystemEventHandler() w = ObservedWatch(a, rec...
Adding the same watch twice used to result in a null pointer return without an exception. See https://github.com/gorakhargosh/watchdog/issues/765
test_add_watch_twice
python
gorakhargosh/watchdog
tests/test_fsevents.py
https://github.com/gorakhargosh/watchdog/blob/master/tests/test_fsevents.py
Apache-2.0
def test_watcher_deletion_while_receiving_events_1( caplog: pytest.LogCaptureFixture, p: P, start_watching: StartWatching, ) -> None: """ When the watcher is stopped while there are events, such exception could happen: Traceback (most recent call last): File "observers/fsevents....
When the watcher is stopped while there are events, such exception could happen: Traceback (most recent call last): File "observers/fsevents.py", line 327, in events_callback self.queue_events(self.timeout, events) File "observers/fsevents.py", line 187, in queue_events...
test_watcher_deletion_while_receiving_events_1
python
gorakhargosh/watchdog
tests/test_fsevents.py
https://github.com/gorakhargosh/watchdog/blob/master/tests/test_fsevents.py
Apache-2.0
def test_watcher_deletion_while_receiving_events_2( caplog: pytest.LogCaptureFixture, p: P, start_watching: StartWatching, ) -> None: """Note: that test takes about 20 seconds to complete. Quite similar test to prevent another issue when the watcher is stopped while there are events, such excep...
Note: that test takes about 20 seconds to complete. Quite similar test to prevent another issue when the watcher is stopped while there are events, such exception could happen: Traceback (most recent call last): File "observers/fsevents.py", line 327, in events_callback self....
test_watcher_deletion_while_receiving_events_2
python
gorakhargosh/watchdog
tests/test_fsevents.py
https://github.com/gorakhargosh/watchdog/blob/master/tests/test_fsevents.py
Apache-2.0
def test_remove_watch_twice(start_watching: StartWatching) -> None: """ ValueError: PyCapsule_GetPointer called with invalid PyCapsule object The above exception was the direct cause of the following exception: src/watchdog/utils/__init__.py:92: in stop self.on_thread_stop() src/watchdog/o...
ValueError: PyCapsule_GetPointer called with invalid PyCapsule object The above exception was the direct cause of the following exception: src/watchdog/utils/__init__.py:92: in stop self.on_thread_stop() src/watchdog/observers/fsevents.py:73: SystemError def on_thread_stop(self): ...
test_remove_watch_twice
python
gorakhargosh/watchdog
tests/test_fsevents.py
https://github.com/gorakhargosh/watchdog/blob/master/tests/test_fsevents.py
Apache-2.0
def test_unschedule_removed_folder(observer: BaseObserver, p: P) -> None: """ TypeError: PyCObject_AsVoidPtr called with null pointer The above exception was the direct cause of the following exception: def on_thread_stop(self): if self.watch: _fsevents.remove_watch(self.watch) ...
TypeError: PyCObject_AsVoidPtr called with null pointer The above exception was the direct cause of the following exception: def on_thread_stop(self): if self.watch: _fsevents.remove_watch(self.watch) E SystemError: <built-in function stop> returned a result with an error set...
test_unschedule_removed_folder
python
gorakhargosh/watchdog
tests/test_fsevents.py
https://github.com/gorakhargosh/watchdog/blob/master/tests/test_fsevents.py
Apache-2.0
def test_recursive_check_accepts_relative_paths(p: P) -> None: """See https://github.com/gorakhargosh/watchdog/issues/797 The test code provided in the defect observes the current working directory using ".". Since the watch path wasn't normalized then that failed. This test emulates the scenario. ...
See https://github.com/gorakhargosh/watchdog/issues/797 The test code provided in the defect observes the current working directory using ".". Since the watch path wasn't normalized then that failed. This test emulates the scenario.
test_recursive_check_accepts_relative_paths
python
gorakhargosh/watchdog
tests/test_fsevents.py
https://github.com/gorakhargosh/watchdog/blob/master/tests/test_fsevents.py
Apache-2.0
def test_watchdog_recursive(p: P) -> None: """See https://github.com/gorakhargosh/watchdog/issues/706""" import os.path from watchdog.events import FileSystemEventHandler from watchdog.observers import Observer class Handler(FileSystemEventHandler): def __init__(self): super()....
See https://github.com/gorakhargosh/watchdog/issues/706
test_watchdog_recursive
python
gorakhargosh/watchdog
tests/test_fsevents.py
https://github.com/gorakhargosh/watchdog/blob/master/tests/test_fsevents.py
Apache-2.0
def test_non_ascii_path(p: P, event_queue: TestEventQueue, start_watching: StartWatching) -> None: """ Inotify can construct an event for a path containing non-ASCII. """ path = p("\N{SNOWMAN}") start_watching(path=p("")) os.mkdir(path) event, _ = event_queue.get(timeout=5) assert isinst...
Inotify can construct an event for a path containing non-ASCII.
test_non_ascii_path
python
gorakhargosh/watchdog
tests/test_inotify_c.py
https://github.com/gorakhargosh/watchdog/blob/master/tests/test_inotify_c.py
Apache-2.0
def test_root_deleted(event_queue, emitter): r"""Test the event got when removing the watched folder. The regression to prevent is: Exception in thread Thread-1: Traceback (most recent call last): File "watchdog\observers\winapi.py", line 333, in read_directory_changes ctype...
Test the event got when removing the watched folder. The regression to prevent is: Exception in thread Thread-1: Traceback (most recent call last): File "watchdog\observers\winapi.py", line 333, in read_directory_changes ctypes.byref(nbytes), None, None) File "watchdog\o...
test_root_deleted
python
gorakhargosh/watchdog
tests/test_observers_winapi.py
https://github.com/gorakhargosh/watchdog/blob/master/tests/test_observers_winapi.py
Apache-2.0
def wait(): """ Wait long enough for file/folder mtime to change. This is needed to be able to detected modifications. """ if platform.is_darwin() or platform.is_windows(): # on macOS resolution of stat.mtime is only 1 second time.sleep(1.5) else: time.sleep(0.5)
Wait long enough for file/folder mtime to change. This is needed to be able to detected modifications.
wait
python
gorakhargosh/watchdog
tests/test_snapshot_diff.py
https://github.com/gorakhargosh/watchdog/blob/master/tests/test_snapshot_diff.py
Apache-2.0
def test_pickle(p): """It should be possible to pickle a snapshot.""" mkdir(p("dir1")) snasphot = DirectorySnapshot(p("dir1")) pickle.dumps(snasphot)
It should be possible to pickle a snapshot.
test_pickle
python
gorakhargosh/watchdog
tests/test_snapshot_diff.py
https://github.com/gorakhargosh/watchdog/blob/master/tests/test_snapshot_diff.py
Apache-2.0
def train( cfg: DictConfig, trainer: Trainer, task: tasks.FairseqTask, epoch_itr ) -> Tuple[List[Optional[float]], bool]: """Train the model for one epoch and return validation losses.""" # Initialize data iterator itr = epoch_itr.next_epoch_itr( fix_batches_to_gpus=cfg.distributed_training.fix_...
Train the model for one epoch and return validation losses.
train
python
OFA-Sys/OFA
train.py
https://github.com/OFA-Sys/OFA/blob/master/train.py
Apache-2.0
def validate( cfg: DictConfig, trainer: Trainer, task: tasks.FairseqTask, epoch_itr, subsets: List[str], ) -> List[Optional[float]]: """Evaluate the model on the validation set(s) and return the losses.""" if cfg.dataset.fixed_validation_seed is not None: # set fixed seed for every ...
Evaluate the model on the validation set(s) and return the losses.
validate
python
OFA-Sys/OFA
train.py
https://github.com/OFA-Sys/OFA/blob/master/train.py
Apache-2.0
def reinitialize(self): """Reinitialize the Trainer, typically after model params change.""" self._lr_scheduler = None self._optimizer = None self._wrapped_criterion = None self._wrapped_model = None
Reinitialize the Trainer, typically after model params change.
reinitialize
python
OFA-Sys/OFA
trainer.py
https://github.com/OFA-Sys/OFA/blob/master/trainer.py
Apache-2.0
def should_save_checkpoint_on_current_rank(self) -> bool: """Indicates whether to save checkpoints on the current DDP rank.""" if ( self.is_fsdp and self.cfg.distributed_training.use_sharded_state ) or getattr(self.cfg.model, "base_layers", 0) > 0: return True els...
Indicates whether to save checkpoints on the current DDP rank.
should_save_checkpoint_on_current_rank
python
OFA-Sys/OFA
trainer.py
https://github.com/OFA-Sys/OFA/blob/master/trainer.py
Apache-2.0
def checkpoint_suffix(self) -> str: """Suffix to add to the checkpoint file name.""" if self.is_fsdp and self.cfg.distributed_training.use_sharded_state: return self.cfg.checkpoint.checkpoint_suffix + "-shard{0}".format( self.data_parallel_rank ) else: ...
Suffix to add to the checkpoint file name.
checkpoint_suffix
python
OFA-Sys/OFA
trainer.py
https://github.com/OFA-Sys/OFA/blob/master/trainer.py
Apache-2.0
def consolidate_optimizer(self): """For OSS, we need to consolidate the state dict.""" if self.cfg.checkpoint.no_save_optimizer_state: return self._gathered_optim_state = None if hasattr(self.optimizer.optimizer, "consolidate_state_dict"): self.optimizer.optimizer...
For OSS, we need to consolidate the state dict.
consolidate_optimizer
python
OFA-Sys/OFA
trainer.py
https://github.com/OFA-Sys/OFA/blob/master/trainer.py
Apache-2.0
def save_checkpoint(self, filename, extra_state): """Save all training state in a checkpoint file.""" logger.info(f"Saving checkpoint to {filename}") # call state_dict on all ranks in case it needs internal communication state_dict = utils.move_to_cpu(self.state_dict()) state_dic...
Save all training state in a checkpoint file.
save_checkpoint
python
OFA-Sys/OFA
trainer.py
https://github.com/OFA-Sys/OFA/blob/master/trainer.py
Apache-2.0
def load_checkpoint( self, filename, reset_optimizer=False, reset_lr_scheduler=False, optimizer_overrides=None, reset_meters=False, ): """ Load all training state from a checkpoint file. rank = 0 will load the checkpoint, and then broadcast it ...
Load all training state from a checkpoint file. rank = 0 will load the checkpoint, and then broadcast it to all other ranks.
load_checkpoint
python
OFA-Sys/OFA
trainer.py
https://github.com/OFA-Sys/OFA/blob/master/trainer.py
Apache-2.0
def get_train_iterator( self, epoch, combine=True, load_dataset=True, data_selector=None, shard_batch_itr=True, disable_iterator_cache=False, ): """Return an EpochBatchIterator over the training set for a given epoch.""" if load_dataset: ...
Return an EpochBatchIterator over the training set for a given epoch.
get_train_iterator
python
OFA-Sys/OFA
trainer.py
https://github.com/OFA-Sys/OFA/blob/master/trainer.py
Apache-2.0
def get_valid_iterator( self, subset, disable_iterator_cache=False, ): """Return an EpochBatchIterator over given validation subset for a given epoch.""" self.task.dataset(subset).dataset._seek() batch_iterator = self.task.get_batch_iterator( dataset=self....
Return an EpochBatchIterator over given validation subset for a given epoch.
get_valid_iterator
python
OFA-Sys/OFA
trainer.py
https://github.com/OFA-Sys/OFA/blob/master/trainer.py
Apache-2.0
def begin_epoch(self, epoch): """Called at the beginning of each epoch.""" logger.info("begin training epoch {}".format(epoch)) self.lr_step_begin_epoch(epoch) if self.quantizer is not None: self.quantizer.begin_epoch(epoch) # task specific setup per epoch ...
Called at the beginning of each epoch.
begin_epoch
python
OFA-Sys/OFA
trainer.py
https://github.com/OFA-Sys/OFA/blob/master/trainer.py
Apache-2.0
def train_step(self, samples, raise_oom=False): """Do forward, backward and parameter update.""" self._set_seed() self.model.train() self.criterion.train() self.zero_grad() metrics.log_start_time("train_wall", priority=800, round=0) # If EMA is enabled through s...
Do forward, backward and parameter update.
train_step
python
OFA-Sys/OFA
trainer.py
https://github.com/OFA-Sys/OFA/blob/master/trainer.py
Apache-2.0
def maybe_no_sync(): """ Whenever *samples* contains more than one mini-batch, we want to accumulate gradients locally and only call all-reduce in the last backwards pass. """ if ( self.data_parallel_worl...
Whenever *samples* contains more than one mini-batch, we want to accumulate gradients locally and only call all-reduce in the last backwards pass.
maybe_no_sync
python
OFA-Sys/OFA
trainer.py
https://github.com/OFA-Sys/OFA/blob/master/trainer.py
Apache-2.0
def valid_step(self, sample, raise_oom=False): """Do forward pass in evaluation mode.""" if self.tpu: import torch_xla.core.xla_model as xm xm.rendezvous("valid_step") # wait for all workers # If EMA is enabled through store_ema=True # and task.uses_ema is True...
Do forward pass in evaluation mode.
valid_step
python
OFA-Sys/OFA
trainer.py
https://github.com/OFA-Sys/OFA/blob/master/trainer.py
Apache-2.0
def lr_step_begin_epoch(self, epoch): """Adjust the learning rate at the beginning of the epoch.""" self.lr_scheduler.step_begin_epoch(epoch) # prefer updating the LR based on the number of steps return self.lr_step_update()
Adjust the learning rate at the beginning of the epoch.
lr_step_begin_epoch
python
OFA-Sys/OFA
trainer.py
https://github.com/OFA-Sys/OFA/blob/master/trainer.py
Apache-2.0
def lr_step(self, epoch, val_loss=None): """Adjust the learning rate at the end of the epoch.""" self.lr_scheduler.step(epoch, val_loss) # prefer updating the LR based on the number of steps return self.lr_step_update()
Adjust the learning rate at the end of the epoch.
lr_step
python
OFA-Sys/OFA
trainer.py
https://github.com/OFA-Sys/OFA/blob/master/trainer.py
Apache-2.0
def lr_step_update(self): """Update the learning rate after each update.""" new_lr = self.lr_scheduler.step_update(self.get_num_updates()) if isinstance(new_lr, dict): for k, v in new_lr.items(): metrics.log_scalar(f"lr_{k}", v, weight=0, priority=300) new...
Update the learning rate after each update.
lr_step_update
python
OFA-Sys/OFA
trainer.py
https://github.com/OFA-Sys/OFA/blob/master/trainer.py
Apache-2.0
def get_meter(self, name): """[deprecated] Get a specific meter by name.""" from fairseq import meters if "get_meter" not in self._warn_once: self._warn_once.add("get_meter") utils.deprecation_warning( "Trainer.get_meter is deprecated. Please use fairseq....
[deprecated] Get a specific meter by name.
get_meter
python
OFA-Sys/OFA
trainer.py
https://github.com/OFA-Sys/OFA/blob/master/trainer.py
Apache-2.0
def set_num_updates(self, num_updates): """Set the number of parameters updates.""" self._num_updates = num_updates self.lr_step_update() if self.quantizer: self.quantizer.step_update(self._num_updates) metrics.log_scalar("num_updates", self._num_updates, weight=0, pr...
Set the number of parameters updates.
set_num_updates
python
OFA-Sys/OFA
trainer.py
https://github.com/OFA-Sys/OFA/blob/master/trainer.py
Apache-2.0
def _all_gather_list_sync( self, logging_outputs: List[Dict[str, Any]], *extra_stats_to_sum, ignore=False, ): """ Sync logging outputs across workers. all_gather_list_sync is suitable when logging outputs are complex types. """ if self.tpu: ...
Sync logging outputs across workers. all_gather_list_sync is suitable when logging outputs are complex types.
_all_gather_list_sync
python
OFA-Sys/OFA
trainer.py
https://github.com/OFA-Sys/OFA/blob/master/trainer.py
Apache-2.0
def _fast_stat_sync_sum( self, logging_outputs: List[Dict[str, Any]], *extra_stats_to_sum, ignore=False, ): """ Sync logging outputs across workers. fast_stat_sync_sum is faster than all_gather_list_sync, but is only suitable when logging outputs are s...
Sync logging outputs across workers. fast_stat_sync_sum is faster than all_gather_list_sync, but is only suitable when logging outputs are scalars and can be summed. Note that *logging_outputs* cannot contain any nested dicts/lists.
_fast_stat_sync_sum
python
OFA-Sys/OFA
trainer.py
https://github.com/OFA-Sys/OFA/blob/master/trainer.py
Apache-2.0
def _check_grad_norms(self, grad_norm): """Check that grad norms are consistent across workers.""" if self._grad_norm_buf is not None: self._grad_norm_buf.zero_() self._grad_norm_buf[self.data_parallel_rank] = grad_norm distributed_utils.all_reduce( se...
Check that grad norms are consistent across workers.
_check_grad_norms
python
OFA-Sys/OFA
trainer.py
https://github.com/OFA-Sys/OFA/blob/master/trainer.py
Apache-2.0
def forward(self, model, sample, update_num=0, reduce=True): """Compute the loss for the given sample. Returns a tuple with three elements: 1) the loss 2) the sample size, which is used as the denominator for the gradient 3) logging outputs to display while training """ ...
Compute the loss for the given sample. Returns a tuple with three elements: 1) the loss 2) the sample size, which is used as the denominator for the gradient 3) logging outputs to display while training
forward
python
OFA-Sys/OFA
criterions/clip_scst_loss.py
https://github.com/OFA-Sys/OFA/blob/master/criterions/clip_scst_loss.py
Apache-2.0
def _calculate_clip_scores(self, gen_res, gt_text, device): ''' gen_res: generated images, list of Image gt_text: input captions. device: device for clip model ''' batch_size = len(gt_text) gen_res_size = len(gen_res) img_per_seq = gen_res_size // batch_si...
gen_res: generated images, list of Image gt_text: input captions. device: device for clip model
_calculate_clip_scores
python
OFA-Sys/OFA
criterions/clip_scst_loss.py
https://github.com/OFA-Sys/OFA/blob/master/criterions/clip_scst_loss.py
Apache-2.0
def reduce_metrics(cls, logging_outputs) -> None: """Aggregate logging outputs from data parallel training.""" loss_sum = sum(log.get("loss", 0) for log in logging_outputs) score_sum = sum(log.get("score", 0) for log in logging_outputs) ntokens = sum(log.get("ntokens", 0) for log in logg...
Aggregate logging outputs from data parallel training.
reduce_metrics
python
OFA-Sys/OFA
criterions/clip_scst_loss.py
https://github.com/OFA-Sys/OFA/blob/master/criterions/clip_scst_loss.py
Apache-2.0
def _calculate_eval_scores(self, gen_res, gt_idx, gt_res): ''' gen_res: generated captions, list of str gt_idx: list of int, of the same length as gen_res gt_res: ground truth captions, list of list of str. gen_res[i] corresponds to gt_res[gt_idx[i]] Each image ca...
gen_res: generated captions, list of str gt_idx: list of int, of the same length as gen_res gt_res: ground truth captions, list of list of str. gen_res[i] corresponds to gt_res[gt_idx[i]] Each image can have multiple ground truth captions
_calculate_eval_scores
python
OFA-Sys/OFA
criterions/scst_loss.py
https://github.com/OFA-Sys/OFA/blob/master/criterions/scst_loss.py
Apache-2.0
def infer_language_pair(path): """Infer language pair from filename: <split>.<lang1>-<lang2>.(...).idx""" src, dst = None, None for filename in PathManager.ls(path): parts = filename.split(".") if len(parts) >= 3 and len(parts[1].split("-")) == 2: return parts[1].split("-") r...
Infer language pair from filename: <split>.<lang1>-<lang2>.(...).idx
infer_language_pair
python
OFA-Sys/OFA
data/data_utils.py
https://github.com/OFA-Sys/OFA/blob/master/data/data_utils.py
Apache-2.0
def collate_tokens( values, pad_idx, eos_idx=None, left_pad=False, move_eos_to_beginning=False, pad_to_length=None, pad_to_multiple=1, pad_to_bsz=None, ): """Convert a list of 1d tensors into a padded 2d tensor.""" size = max(v.size(0) for v in values) size = size if pad_to_l...
Convert a list of 1d tensors into a padded 2d tensor.
collate_tokens
python
OFA-Sys/OFA
data/data_utils.py
https://github.com/OFA-Sys/OFA/blob/master/data/data_utils.py
Apache-2.0
def load_indexed_dataset( path, dictionary=None, dataset_impl=None, combine=False, default="cached" ): """A helper function for loading indexed datasets. Args: path (str): path to indexed dataset (e.g., 'data-bin/train') dictionary (~fairseq.data.Dictionary): data dictionary dataset...
A helper function for loading indexed datasets. Args: path (str): path to indexed dataset (e.g., 'data-bin/train') dictionary (~fairseq.data.Dictionary): data dictionary dataset_impl (str, optional): which dataset implementation to use. If not provided, it will be inferred autom...
load_indexed_dataset
python
OFA-Sys/OFA
data/data_utils.py
https://github.com/OFA-Sys/OFA/blob/master/data/data_utils.py
Apache-2.0
def numpy_seed(seed, *addl_seeds): """Context manager which seeds the NumPy PRNG with the specified seed and restores the state afterward""" if seed is None: yield return if len(addl_seeds) > 0: seed = int(hash((seed, *addl_seeds)) % 1e6) state = np.random.get_state() np....
Context manager which seeds the NumPy PRNG with the specified seed and restores the state afterward
numpy_seed
python
OFA-Sys/OFA
data/data_utils.py
https://github.com/OFA-Sys/OFA/blob/master/data/data_utils.py
Apache-2.0
def collect_filtered(function, iterable, filtered): """ Similar to :func:`filter` but collects filtered elements in ``filtered``. Args: function (callable): function that returns ``False`` for elements that should be filtered iterable (iterable): iterable to filter filte...
Similar to :func:`filter` but collects filtered elements in ``filtered``. Args: function (callable): function that returns ``False`` for elements that should be filtered iterable (iterable): iterable to filter filtered (list): list to store filtered elements
collect_filtered
python
OFA-Sys/OFA
data/data_utils.py
https://github.com/OFA-Sys/OFA/blob/master/data/data_utils.py
Apache-2.0
def filter_by_size(indices, dataset, max_positions, raise_exception=False): """ [deprecated] Filter indices based on their size. Use `FairseqDataset::filter_indices_by_size` instead. Args: indices (List[int]): ordered list of dataset indices dataset (FairseqDataset): fairseq dataset ins...
[deprecated] Filter indices based on their size. Use `FairseqDataset::filter_indices_by_size` instead. Args: indices (List[int]): ordered list of dataset indices dataset (FairseqDataset): fairseq dataset instance max_positions (tuple): filter elements larger than this size. ...
filter_by_size
python
OFA-Sys/OFA
data/data_utils.py
https://github.com/OFA-Sys/OFA/blob/master/data/data_utils.py
Apache-2.0
def filter_paired_dataset_indices_by_size(src_sizes, tgt_sizes, indices, max_sizes): """Filter a list of sample indices. Remove those that are longer than specified in max_sizes. Args: indices (np.array): original array of sample indices max_sizes (int or list[int] or tuple[int]): max s...
Filter a list of sample indices. Remove those that are longer than specified in max_sizes. Args: indices (np.array): original array of sample indices max_sizes (int or list[int] or tuple[int]): max sample size, can be defined separately for src and tgt (then list or tuple) ...
filter_paired_dataset_indices_by_size
python
OFA-Sys/OFA
data/data_utils.py
https://github.com/OFA-Sys/OFA/blob/master/data/data_utils.py
Apache-2.0
def batch_by_size( indices, num_tokens_fn, num_tokens_vec=None, max_tokens=None, max_sentences=None, required_batch_size_multiple=1, fixed_shapes=None, ): """ Yield mini-batches of indices bucketed by size. Batches may contain sequences of different lengths. Args: in...
Yield mini-batches of indices bucketed by size. Batches may contain sequences of different lengths. Args: indices (List[int]): ordered list of dataset indices num_tokens_fn (callable): function that returns the number of tokens at a given index num_tokens_vec (List[int]...
batch_by_size
python
OFA-Sys/OFA
data/data_utils.py
https://github.com/OFA-Sys/OFA/blob/master/data/data_utils.py
Apache-2.0
def compute_mask_indices( shape: Tuple[int, int], padding_mask: Optional[torch.Tensor], mask_prob: float, mask_length: int, mask_type: str = "static", mask_other: float = 0.0, min_masks: int = 0, no_overlap: bool = False, min_space: int = 0, ) -> np.ndarray: """ Computes rand...
Computes random mask spans for a given shape Args: shape: the the shape for which to compute masks. should be of size 2 where first element is batch size and 2nd is timesteps padding_mask: optional padding mask of the same size as shape, which will prevent masking padded elements ...
compute_mask_indices
python
OFA-Sys/OFA
data/data_utils.py
https://github.com/OFA-Sys/OFA/blob/master/data/data_utils.py
Apache-2.0
def raise_if_valid_subsets_unintentionally_ignored(train_cfg) -> None: """Raises if there are paths matching 'valid*[0-9].*' which are not combined or ignored.""" if ( train_cfg.dataset.ignore_unused_valid_subsets or train_cfg.dataset.combine_valid_subsets or train_cfg.dataset.disable_va...
Raises if there are paths matching 'valid*[0-9].*' which are not combined or ignored.
raise_if_valid_subsets_unintentionally_ignored
python
OFA-Sys/OFA
data/data_utils.py
https://github.com/OFA-Sys/OFA/blob/master/data/data_utils.py
Apache-2.0
def collater(self, samples, pad_to_length=None): """Merge samples of different tasks to form two mini-batches. Args: samples (List[Tuple]): samples to collate Returns: Tuple[dict]: two mini-batch containing the data of different tasks """ samples_v1 = [] ...
Merge samples of different tasks to form two mini-batches. Args: samples (List[Tuple]): samples to collate Returns: Tuple[dict]: two mini-batch containing the data of different tasks
collater
python
OFA-Sys/OFA
data/pretrain_data/unify_dataset.py
https://github.com/OFA-Sys/OFA/blob/master/data/pretrain_data/unify_dataset.py
Apache-2.0
def _collate_frames( frames: List[torch.Tensor] ): """ Convert a list of 2D frames into a padded 3D tensor Args: frames (list): list of 2D frames of size L[i]*f_dim. Where L[i] is length of i-th frame and f_dim is static dimension of features Retur...
Convert a list of 2D frames into a padded 3D tensor Args: frames (list): list of 2D frames of size L[i]*f_dim. Where L[i] is length of i-th frame and f_dim is static dimension of features Returns: 3D tensor of size len(frames)*len_max*f_dim where len_max ...
_collate_frames
python
OFA-Sys/OFA
data/s2t_data/unify_dataset.py
https://github.com/OFA-Sys/OFA/blob/master/data/s2t_data/unify_dataset.py
Apache-2.0
def add_args(parser): """Add optimizer-specific arguments to the parser.""" # fmt: off parser.add_argument('--weight-decay', '--wd', default=0.0, type=float, metavar='WD', help='weight decay') parser.add_argument('--adagrad-clip', default=0.0, type=float, meta...
Add optimizer-specific arguments to the parser.
add_args
python
OFA-Sys/OFA
fairseq/examples/adaptive_span/adagrad_with_grad_clip.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/adaptive_span/adagrad_with_grad_clip.py
Apache-2.0
def optimizer_config(self): """ Return a kwarg dictionary that will be used to override optimizer args stored in checkpoints. This allows us to load a checkpoint and resume training using a different set of optimizer args, e.g., with a different learning rate. """ ...
Return a kwarg dictionary that will be used to override optimizer args stored in checkpoints. This allows us to load a checkpoint and resume training using a different set of optimizer args, e.g., with a different learning rate.
optimizer_config
python
OFA-Sys/OFA
fairseq/examples/adaptive_span/adagrad_with_grad_clip.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/adaptive_span/adagrad_with_grad_clip.py
Apache-2.0
def forward(self, attn, normalize=True): """mask attention with the right span""" # batch and head dimensions are merged together, so separate them first self.clamp_param() if self._adapt_span_layer: attn = self._mask(attn) else: B = attn.size(0) # batch ...
mask attention with the right span
forward
python
OFA-Sys/OFA
fairseq/examples/adaptive_span/adaptive_span_attention.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/adaptive_span/adaptive_span_attention.py
Apache-2.0
def get_trim_len(self): """how much of memory can be trimmed to reduce computation""" L = self._max_span trim_len = min(L - 1, L - self._mask.get_current_max_size()) # too fine granularity might be bad for the memory management trim_len = math.floor(trim_len / 64) * 64 re...
how much of memory can be trimmed to reduce computation
get_trim_len
python
OFA-Sys/OFA
fairseq/examples/adaptive_span/adaptive_span_attention.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/adaptive_span/adaptive_span_attention.py
Apache-2.0
def trim_memory(self, query, key, value, key_pe): """trim out unnecessary memory beforehand to reduce computation""" trim_len = self.get_trim_len() cache_size = key.size(1) - query.size(1) trim_len_cache = trim_len - (self._max_span - cache_size) if trim_len_cache > 0: ...
trim out unnecessary memory beforehand to reduce computation
trim_memory
python
OFA-Sys/OFA
fairseq/examples/adaptive_span/adaptive_span_attention.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/adaptive_span/adaptive_span_attention.py
Apache-2.0
def get_cache_size(self): """determine how long the cache should be""" trim_len = self.get_trim_len() # give a buffer of 64 steps since a span might increase # in future updates return min(self._max_span, self._max_span - trim_len + 64)
determine how long the cache should be
get_cache_size
python
OFA-Sys/OFA
fairseq/examples/adaptive_span/adaptive_span_attention.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/adaptive_span/adaptive_span_attention.py
Apache-2.0
def forward(self, model, sample, reduce=True): """Compute the loss for the given sample. Returns a tuple with three elements: 1) the loss here is summed, different from the adaptive span code 2) the sample size, which is used as the denominator for the gradient 3) logging output...
Compute the loss for the given sample. Returns a tuple with three elements: 1) the loss here is summed, different from the adaptive span code 2) the sample size, which is used as the denominator for the gradient 3) logging outputs to display while training
forward
python
OFA-Sys/OFA
fairseq/examples/adaptive_span/adaptive_span_loss.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/adaptive_span/adaptive_span_loss.py
Apache-2.0
def _skew(X, pad_value): """shift every row 1 step to right""" # X = B x M x L B, M, L = X.size() X = F.pad(X, (0, M + 1), value=pad_value) # B x M x (L+M+1) X = X.view(B, -1) # B x ML+MM+M X = X[:, :-M] # B x ML+MM X = X.view(B, M, M + L) # B x M x L+M return X
shift every row 1 step to right
_skew
python
OFA-Sys/OFA
fairseq/examples/adaptive_span/adaptive_span_model.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/adaptive_span/adaptive_span_model.py
Apache-2.0
def reorder_incremental_state( self, incremental_state: Dict[str, Dict[str, Optional[torch.Tensor]]], new_order: torch.Tensor, ): """Reorder incremental state. This will be called when the order of the input has changed from the previous time step. A typical use case...
Reorder incremental state. This will be called when the order of the input has changed from the previous time step. A typical use case is beam search, where the input order changes between time steps based on the selection of beams.
reorder_incremental_state
python
OFA-Sys/OFA
fairseq/examples/adaptive_span/adaptive_span_model_wrapper.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/adaptive_span/adaptive_span_model_wrapper.py
Apache-2.0
def load_dataset(self, split, epoch=1, combine=False, **kwargs): """Load a given dataset split (e.g., train, valid, test)""" # support sharded datasets paths = utils.split_paths(self.cfg.data) assert len(paths) > 0 data_path = paths[(epoch - 1) % len(paths)] split_path =...
Load a given dataset split (e.g., train, valid, test)
load_dataset
python
OFA-Sys/OFA
fairseq/examples/adaptive_span/truncated_bptt_lm_task.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/adaptive_span/truncated_bptt_lm_task.py
Apache-2.0
def main(): """ Usage:: python examples/bart/summarize.py \ --model-dir $HOME/bart.large.cnn \ --model-file model.pt \ --src $HOME/data-bin/cnn_dm/test.source """ parser = argparse.ArgumentParser() parser.add_argument( "--model-dir", requ...
Usage:: python examples/bart/summarize.py --model-dir $HOME/bart.large.cnn --model-file model.pt --src $HOME/data-bin/cnn_dm/test.source
main
python
OFA-Sys/OFA
fairseq/examples/bart/summarize.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/bart/summarize.py
Apache-2.0
def update_init_roberta_model_state(state): """ update the state_dict of a Roberta model for initializing weights of the BertRanker """ for k in list(state.keys()): if ".lm_head." in k or "version" in k: del state[k] continue # remove 'encoder/decoder.sentence_en...
update the state_dict of a Roberta model for initializing weights of the BertRanker
update_init_roberta_model_state
python
OFA-Sys/OFA
fairseq/examples/discriminative_reranking_nmt/models/discriminative_reranking_model.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/discriminative_reranking_nmt/models/discriminative_reranking_model.py
Apache-2.0
def load_dictionary(cls, cfg, filename): """Load the dictionary from the filename""" dictionary = Dictionary.load(filename) dictionary.add_symbol("<mask>") # for loading pretrained XLMR model return dictionary
Load the dictionary from the filename
load_dictionary
python
OFA-Sys/OFA
fairseq/examples/discriminative_reranking_nmt/tasks/discriminative_reranking_task.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/discriminative_reranking_nmt/tasks/discriminative_reranking_task.py
Apache-2.0
def load_dataset(self, split, epoch=0, combine=False, **kwargs): """Load a given dataset split (e.g., train, valid, test).""" if self.cfg.data.endswith("1"): data_shard = (epoch - 1) % self.cfg.num_data_splits + 1 data_path = self.cfg.data[:-1] + str(data_shard) else: ...
Load a given dataset split (e.g., train, valid, test).
load_dataset
python
OFA-Sys/OFA
fairseq/examples/discriminative_reranking_nmt/tasks/discriminative_reranking_task.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/discriminative_reranking_nmt/tasks/discriminative_reranking_task.py
Apache-2.0
def __init__( self, combine_method, tgt_dict, src_dict=None, beam_size=1, max_len_a=0, max_len_b=200, min_len=1, len_penalty=1.0, unk_penalty=0.0, retain_dropout=False, temperature=1.0, match_source_len=False, ...
Generates translations of a given source sentence, using beam search with noisy channel decoding. Args: combine_method (string, optional): Method to combine direct, LM and channel model scores (default: None) tgt_dict (~fairseq.data.Dictionary): target diction...
__init__
python
OFA-Sys/OFA
fairseq/examples/fast_noisy_channel/noisy_channel_sequence_generator.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/fast_noisy_channel/noisy_channel_sequence_generator.py
Apache-2.0
def generate( self, models, sample, prefix_tokens=None, bos_token=None, **kwargs ): """Generate a batch of translations. Args: models (List[~fairseq.models.FairseqModel]): ensemble of models sample (dict): batch pref...
Generate a batch of translations. Args: models (List[~fairseq.models.FairseqModel]): ensemble of models sample (dict): batch prefix_tokens (torch.LongTensor, optional): force decoder to begin with these tokens
generate
python
OFA-Sys/OFA
fairseq/examples/fast_noisy_channel/noisy_channel_sequence_generator.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/fast_noisy_channel/noisy_channel_sequence_generator.py
Apache-2.0
def is_finished(sent, step, unfin_idx): """ Check whether we've finished generation for a given sentence, by comparing the worst score among finalized hypotheses to the best possible score among unfinalized hypotheses. """ assert len(finalized[sent...
Check whether we've finished generation for a given sentence, by comparing the worst score among finalized hypotheses to the best possible score among unfinalized hypotheses.
is_finished
python
OFA-Sys/OFA
fairseq/examples/fast_noisy_channel/noisy_channel_sequence_generator.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/fast_noisy_channel/noisy_channel_sequence_generator.py
Apache-2.0
def finalize_hypos(step, bbsz_idx, eos_scores, combined_noisy_channel_eos_scores): """ Finalize the given hypotheses at this step, while keeping the total number of finalized hypotheses per sentence <= beam_size. Note: the input must be in the desired finalization order,...
Finalize the given hypotheses at this step, while keeping the total number of finalized hypotheses per sentence <= beam_size. Note: the input must be in the desired finalization order, so that hypotheses that appear earlier in the input are preferred to those ...
finalize_hypos
python
OFA-Sys/OFA
fairseq/examples/fast_noisy_channel/noisy_channel_sequence_generator.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/fast_noisy_channel/noisy_channel_sequence_generator.py
Apache-2.0
def noisy_channel_rescoring(lprobs, beam_size, bsz, src_tokens, tokens, k): """Rescore the top k hypothesis from each beam using noisy channel modeling Returns: new_fw_lprobs: the direct model probabilities after pruning the top k new_ch_lm_lprobs: the combined c...
Rescore the top k hypothesis from each beam using noisy channel modeling Returns: new_fw_lprobs: the direct model probabilities after pruning the top k new_ch_lm_lprobs: the combined channel and language model probabilities new_lm_lprobs: the language model p...
noisy_channel_rescoring
python
OFA-Sys/OFA
fairseq/examples/fast_noisy_channel/noisy_channel_sequence_generator.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/fast_noisy_channel/noisy_channel_sequence_generator.py
Apache-2.0
def normalized_scores_with_batch_vocab( model_decoder, features, target_ids, k, bsz, beam_size, pad_idx, top_k=0, vocab_size_meter=None, start_idx=None, end_idx=None, **kwargs): """ Get normalized probabilities (or log probs) from a net's output w.r.t. vocab consisting of tar...
Get normalized probabilities (or log probs) from a net's output w.r.t. vocab consisting of target IDs in the batch
normalized_scores_with_batch_vocab
python
OFA-Sys/OFA
fairseq/examples/fast_noisy_channel/noisy_channel_sequence_generator.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/fast_noisy_channel/noisy_channel_sequence_generator.py
Apache-2.0
def add_args(parser): """Add task-specific arguments to the parser.""" TranslationTask.add_args(parser) # fmt: off parser.add_argument('--channel-model', metavar='FILE', help='path to P(S|T) model. P(S|T) and P(T|S) must share source and target dictionaries.')...
Add task-specific arguments to the parser.
add_args
python
OFA-Sys/OFA
fairseq/examples/fast_noisy_channel/noisy_channel_translation.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/fast_noisy_channel/noisy_channel_translation.py
Apache-2.0
def comp_joint_prob(uid2refs, uid2hyps): """ Args: pad: padding for spliced-feature derived labels """ cnts = Counter() skipped = [] abs_frmdiff = 0 for uid in uid2refs: if uid not in uid2hyps: skipped.append(uid) continue refs = uid2refs[uid] ...
Args: pad: padding for spliced-feature derived labels
comp_joint_prob
python
OFA-Sys/OFA
fairseq/examples/hubert/measure_teacher_quality.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/hubert/measure_teacher_quality.py
Apache-2.0
def read_lab(tsv_path, lab_path, pad_len=0, upsample=1): """ tsv is needed to retrieve the uids for the labels """ with open(tsv_path) as f: f.readline() uids = [op.splitext(op.basename(line.rstrip().split()[0]))[0] for line in f] with open(lab_path) as f: labs_list = [pad(li...
tsv is needed to retrieve the uids for the labels
read_lab
python
OFA-Sys/OFA
fairseq/examples/hubert/measure_teacher_quality.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/hubert/measure_teacher_quality.py
Apache-2.0
def add_args(parser): """Add model-specific arguments to the parser.""" parser.add_argument( "--dropout", default=0.1, type=float, metavar="D", help="dropout probability", ) parser.add_argument( "--encoder-embed-dim"...
Add model-specific arguments to the parser.
add_args
python
OFA-Sys/OFA
fairseq/examples/laser/laser_src/laser_lstm.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/laser/laser_src/laser_lstm.py
Apache-2.0
def reorder_encoder_out(self, encoder_out: Dict[str, List[Tensor]], new_order): """ Same as the one in transformer.py, with new_sentemb """ if len(encoder_out["sentemb"]) == 0: new_sentemb = [] else: new_sentemb = [encoder_out["sentemb"][0].index_select(0,...
Same as the one in transformer.py, with new_sentemb
reorder_encoder_out
python
OFA-Sys/OFA
fairseq/examples/laser/laser_src/laser_transformer.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/laser/laser_src/laser_transformer.py
Apache-2.0
def extract_features( self, prev_output_tokens, encoder_out: Optional[Dict[str, List[Tensor]]], incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None, full_context_alignment: bool = False, alignment_layer: Optional[int] = None, alignment_heads...
Similar to *forward* but only return features. Includes several features from "Jointly Learning to Align and Translate with Transformer Models" (Garg et al., EMNLP 2019). Args: full_context_alignment (bool, optional): don't apply auto-regressive mask to sel...
extract_features
python
OFA-Sys/OFA
fairseq/examples/laser/laser_src/laser_transformer.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/laser/laser_src/laser_transformer.py
Apache-2.0
def forward( self, prev_output_tokens, encoder_out: Optional[Dict[str, List[Tensor]]] = None, incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None, features_only: bool = False, alignment_layer: Optional[int] = None, alignment_heads: Optional[...
Args: prev_output_tokens (LongTensor): previous decoder outputs of shape `(batch, tgt_len)`, for teacher forcing encoder_out (optional): output from the encoder, used for encoder-side attention incremental_state (dict): dictionary used for sto...
forward
python
OFA-Sys/OFA
fairseq/examples/laser/laser_src/laser_transformer.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/laser/laser_src/laser_transformer.py
Apache-2.0
def next_epoch_idx(self): """Return the epoch index after *next_epoch_itr* is called.""" epochs = [itr.next_epoch_idx for itr in self.iterators] self.epoch = epochs[0] assert all(epoch == self.epoch for epoch in epochs) return self.epoch
Return the epoch index after *next_epoch_itr* is called.
next_epoch_idx
python
OFA-Sys/OFA
fairseq/examples/laser/laser_src/multitask_data_utils.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/laser/laser_src/multitask_data_utils.py
Apache-2.0
def sample(self, logit_idx): """To leverage the efficiency of distributed training, samples for all layers are computed at once for each logit_idx. Logits are parameters learnt independent of each other. Args: logit_idx: The index of logit parameters used for sampling. ...
To leverage the efficiency of distributed training, samples for all layers are computed at once for each logit_idx. Logits are parameters learnt independent of each other. Args: logit_idx: The index of logit parameters used for sampling.
sample
python
OFA-Sys/OFA
fairseq/examples/latent_depth/latent_depth_src/modules/latent_layers.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/latent_depth/latent_depth_src/modules/latent_layers.py
Apache-2.0
def forward( self, query, key: Optional[Tensor], value: Optional[Tensor], key_padding_mask: Optional[Tensor] = None, incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None, need_weights: bool = True, static_kv: bool = False, att...
Input shape: Time x Batch x Channel Args: key_padding_mask (ByteTensor, optional): mask to exclude keys that are pads, of shape `(batch, src_len)`, where padding elements are indicated by 1s. need_weights (bool, optional): return the attention weights, ...
forward
python
OFA-Sys/OFA
fairseq/examples/linformer/linformer_src/modules/multihead_linear_attention.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/linformer/linformer_src/modules/multihead_linear_attention.py
Apache-2.0
def reorder_incremental_state( self, incremental_state: Dict[str, Dict[str, Optional[Tensor]]], new_order: Tensor, ): """Reorder buffered internal state (for incremental generation).""" input_buffer = self._get_input_buffer(incremental_state) if input_buffer is not No...
Reorder buffered internal state (for incremental generation).
reorder_incremental_state
python
OFA-Sys/OFA
fairseq/examples/linformer/linformer_src/modules/multihead_linear_attention.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/linformer/linformer_src/modules/multihead_linear_attention.py
Apache-2.0
def match_target_hypo(args, target_outfile, hypo_outfile): """combine scores from the LM and bitext models, and write the top scoring hypothesis to a file""" if len(args.weight1) == 1: res = score_target_hypo( args, args.weight1[0], args.weight2[0], args.w...
combine scores from the LM and bitext models, and write the top scoring hypothesis to a file
match_target_hypo
python
OFA-Sys/OFA
fairseq/examples/noisychannel/rerank.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/noisychannel/rerank.py
Apache-2.0
def get_prefix(sentence, prefix_len): """assuming no bpe, gets the prefix of the sentence with prefix_len words""" tokens = sentence.strip("\n").split() if prefix_len >= len(tokens): return sentence.strip("\n") else: return " ".join(tokens[:prefix_len])
assuming no bpe, gets the prefix of the sentence with prefix_len words
get_prefix
python
OFA-Sys/OFA
fairseq/examples/noisychannel/rerank_utils.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/noisychannel/rerank_utils.py
Apache-2.0
def get_prefix_from_len(sentence, bpe_symbol, prefix_len): """get the prefix of sentence with bpe, with prefix len in terms of words, not bpe tokens""" bpe_count = sum([bpe_symbol.strip(" ") in t for t in sentence[:prefix_len]]) if bpe_count == 0: return sentence[:prefix_len] else: retur...
get the prefix of sentence with bpe, with prefix len in terms of words, not bpe tokens
get_prefix_from_len
python
OFA-Sys/OFA
fairseq/examples/noisychannel/rerank_utils.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/noisychannel/rerank_utils.py
Apache-2.0
def get_num_bpe_tokens_from_len(sentence, bpe_symbol, prefix_len): """given a prefix length in terms of words, return the number of bpe tokens""" prefix = get_prefix_no_bpe(sentence, bpe_symbol, prefix_len) assert len(remove_bpe(prefix, bpe_symbol).split()) <= prefix_len return len(prefix.split(" "))
given a prefix length in terms of words, return the number of bpe tokens
get_num_bpe_tokens_from_len
python
OFA-Sys/OFA
fairseq/examples/noisychannel/rerank_utils.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/noisychannel/rerank_utils.py
Apache-2.0
def get_full_from_prefix(hypo_prefix, hypos): """given a hypo prefix, recover the first hypo from the list of complete hypos beginning with that prefix""" for hypo in hypos: hypo_prefix = hypo_prefix.strip("\n") len_prefix = len(hypo_prefix) if hypo[:len_prefix] == hypo_prefix: ...
given a hypo prefix, recover the first hypo from the list of complete hypos beginning with that prefix
get_full_from_prefix
python
OFA-Sys/OFA
fairseq/examples/noisychannel/rerank_utils.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/noisychannel/rerank_utils.py
Apache-2.0
def replace_oovs(source_in, target_in, target_out): """Replaces <unk-N> tokens in the target text with the corresponding word in the source text. """ oov_re = re.compile("^<unk-([0-9]+)>$") for source_seq, target_seq in zip(source_in, target_in): target_seq_out = [] pos_to_word = ...
Replaces <unk-N> tokens in the target text with the corresponding word in the source text.
replace_oovs
python
OFA-Sys/OFA
fairseq/examples/pointer_generator/postprocess.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/pointer_generator/postprocess.py
Apache-2.0
def replace_oovs(source_in, target_in, vocabulary, source_out, target_out): """Replaces out-of-vocabulary words in source and target text with <unk-N>, where N in is the position of the word in the source sequence. """ def format_unk(pos): return "<unk-{}>".format(pos) if target_in is None...
Replaces out-of-vocabulary words in source and target text with <unk-N>, where N in is the position of the word in the source sequence.
replace_oovs
python
OFA-Sys/OFA
fairseq/examples/pointer_generator/preprocess.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/pointer_generator/preprocess.py
Apache-2.0
def forward( self, src_tokens, src_lengths: Optional[Tensor] = None, return_all_hiddens: bool = False, token_embeddings: Optional[Tensor] = None ): """ Runs the `forward()` method of the parent Transformer class. Then adds the source tokens into the en...
Runs the `forward()` method of the parent Transformer class. Then adds the source tokens into the encoder output tuple. While it might be more elegant that the model would pass the source tokens to the `forward()` method of the decoder too, this would require changes to `Sequen...
forward
python
OFA-Sys/OFA
fairseq/examples/pointer_generator/pointer_generator_src/transformer_pg.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/pointer_generator/pointer_generator_src/transformer_pg.py
Apache-2.0