code stringlengths 17 6.64M |
|---|
def save_checkpoint(args, trainer, epoch_itr, val_loss):
from fairseq import distributed_utils, meters
prev_best = getattr(save_checkpoint, 'best', val_loss)
if (val_loss is not None):
best_function = (max if args.maximize_best_checkpoint_metric else min)
save_checkpoint.best = best_functi... |
def load_checkpoint(args, trainer, **passthrough_args):
'\n Load a checkpoint and restore the training iterator.\n\n *passthrough_args* will be passed through to\n ``trainer.get_train_iterator``.\n '
if (args.distributed_rank == 0):
os.makedirs(args.save_dir, exist_ok=True)
if (args.re... |
def load_checkpoint_to_cpu(path, arg_overrides=None):
'Loads a checkpoint to CPU (with upgrading for backward compatibility).'
with PathManager.open(path, 'rb') as f:
state = torch.load(f, map_location=(lambda s, l: default_restore_location(s, 'cpu')))
args = state['args']
if (arg_overrides is... |
def load_model_ensemble(filenames, arg_overrides=None, task=None):
'Loads an ensemble of models.\n\n Args:\n filenames (List[str]): checkpoint files to load\n arg_overrides (Dict[str,Any], optional): override model args that\n were used during model training\n task (fairseq.task... |
def load_model_ensemble_and_task(filenames, arg_overrides=None, task=None):
from fairseq import tasks
ensemble = []
for filename in filenames:
if (not os.path.exists(filename)):
raise IOError('Model file not found: {}'.format(filename))
state = load_checkpoint_to_cpu(filename, ... |
def checkpoint_paths(path, pattern='checkpoint(\\d+)\\.pt'):
'Retrieves all checkpoints found in `path` directory.\n\n Checkpoints are identified by matching filename to the specified pattern. If\n the pattern contains groups, the result will be sorted by the first group in\n descending order.\n '
... |
def torch_persistent_save(*args, **kwargs):
for i in range(3):
try:
return torch.save(*args, **kwargs)
except Exception:
if (i == 2):
logger.error(traceback.format_exc())
|
def convert_state_dict_type(state_dict, ttype=torch.FloatTensor):
if isinstance(state_dict, dict):
cpu_dict = OrderedDict()
for (k, v) in state_dict.items():
cpu_dict[k] = convert_state_dict_type(v)
return cpu_dict
elif isinstance(state_dict, list):
return [convert_... |
def save_state(filename, args, model_state_dict, criterion, optimizer, lr_scheduler, num_updates, optim_history=None, extra_state=None):
from fairseq import utils
if (optim_history is None):
optim_history = []
if (extra_state is None):
extra_state = {}
state_dict = {'args': args, 'mode... |
def _upgrade_state_dict(state):
'Helper for upgrading old model checkpoints.'
from fairseq import models, registry, tasks
if ('optimizer_history' not in state):
state['optimizer_history'] = [{'criterion_name': 'CrossEntropyCriterion', 'best_loss': state['best_loss']}]
state['last_optimizer... |
def prune_state_dict(state_dict, args):
"Prune the given state_dict if desired for LayerDrop\n (https://arxiv.org/abs/1909.11556).\n\n Training with LayerDrop allows models to be robust to pruning at inference\n time. This function prunes state_dict to allow smaller models to be loaded\n from a larger... |
def load_pretrained_component_from_model(component: Union[(FairseqEncoder, FairseqDecoder)], checkpoint: str):
'\n Load a pretrained FairseqEncoder or FairseqDecoder from checkpoint into the\n provided `component` object. If state_dict fails to load, there may be a\n mismatch in the architecture of the c... |
def verify_checkpoint_directory(save_dir: str) -> None:
if (not os.path.exists(save_dir)):
os.makedirs(save_dir, exist_ok=True)
temp_file_path = os.path.join(save_dir, 'dummy')
try:
with open(temp_file_path, 'w'):
pass
except OSError as e:
logger.warning('Unable to ... |
@register_criterion('adaptive_cross_entropy')
class AdaptiveCrossEntropyCriterion(FairseqCriterion):
def __init__(self, args, task):
super().__init__(args, task)
self.eps = 1e-07
self.smooth = args.label_smoothing
@staticmethod
def add_args(parser):
'Add criterion-specifi... |
@register_criterion('adaptive_loss')
class AdaptiveLoss(FairseqCriterion):
'This is an implementation of the loss function accompanying the adaptive softmax approximation for\n graphical processing units (GPU), described in the paper "Efficient softmax approximation for GPUs"\n (http://arxiv.org/abs/1609.04... |
@register_criterion('binary_cross_entropy')
class BinaryCrossEntropyCriterion(FairseqCriterion):
def __init__(self, args, task):
super().__init__(args, task)
def forward(self, model, sample, reduce=True, log_pred=False):
'Compute the loss for the given sample.\n\n Returns a tuple with... |
@register_criterion('composite_loss')
class CompositeLoss(FairseqCriterion):
'This is a composite loss that, given a list of model outputs and a list of targets,\n computes an average of losses for each output-target pair'
@staticmethod
def add_args(parser):
'Add criterion-specific arguments t... |
@register_criterion('cross_entropy')
class CrossEntropyCriterion(FairseqCriterion):
def __init__(self, args, task):
super().__init__(args, task)
def forward(self, model, sample, reduce=True):
'Compute the loss for the given sample.\n\n Returns a tuple with three elements:\n 1) ... |
class FairseqCriterion(_Loss):
def __init__(self, args, task):
super().__init__()
self.args = args
self.task = task
self.padding_idx = (task.target_dictionary.pad() if (task.target_dictionary is not None) else (- 100))
@staticmethod
def add_args(parser):
'Add crit... |
def label_smoothed_nll_loss(lprobs, target, epsilon, ignore_index=None, reduce=True):
if (target.dim() == (lprobs.dim() - 1)):
target = target.unsqueeze((- 1))
nll_loss = (- lprobs.gather(dim=(- 1), index=target))
smooth_loss = (- lprobs.sum(dim=(- 1), keepdim=True))
if (ignore_index is not No... |
@register_criterion('label_smoothed_cross_entropy')
class LabelSmoothedCrossEntropyCriterion(FairseqCriterion):
def __init__(self, args, task):
super().__init__(args, task)
self.eps = args.label_smoothing
@staticmethod
def add_args(parser):
'Add criterion-specific arguments to th... |
def compute_cross_entropy_loss(logits, targets, ignore_index=(- 100)):
'\n Function to compute the cross entropy loss. The default value of\n ignore_index is the same as the default value for F.cross_entropy in\n pytorch.\n '
assert (logits.size(0) == targets.size((- 1))), "Logits and Targets tens... |
@register_criterion('legacy_masked_lm_loss')
class LegacyMaskedLmLoss(FairseqCriterion):
'\n Implementation for the loss used in masked language model (MLM) training.\n This optionally also computes the next sentence prediction (NSP) loss and\n adds it to the overall loss based on the specified args. The... |
@register_criterion('masked_lm')
class MaskedLmLoss(FairseqCriterion):
'\n Implementation for the loss used in masked language model (MLM) training.\n '
def forward(self, model, sample, reduce=True):
'Compute the loss for the given sample.\n\n Returns a tuple with three elements:\n ... |
@register_criterion('nat_loss')
class LabelSmoothedDualImitationCriterion(FairseqCriterion):
@staticmethod
def add_args(parser):
'Add criterion-specific arguments to the parser.'
parser.add_argument('--label-smoothing', default=0.0, type=float, metavar='D', help='epsilon for label smoothing, ... |
@register_criterion('sentence_prediction')
class SentencePredictionCriterion(FairseqCriterion):
@staticmethod
def add_args(parser):
parser.add_argument('--classification-head-name', default='sentence_classification_head', help='name of the classification head to use')
def forward(self, model, sa... |
@register_criterion('sentence_ranking')
class SentenceRankingCriterion(FairseqCriterion):
def __init__(self, args, task):
super().__init__(args, task)
if (self.args.save_predictions is not None):
self.prediction_h = open(self.args.save_predictions, 'w')
else:
self.... |
class AppendTokenDataset(BaseWrapperDataset):
def __init__(self, dataset, token=None):
super().__init__(dataset)
self.token = token
if (token is not None):
self._sizes = (np.array(dataset.sizes) + 1)
else:
self._sizes = dataset.sizes
def __getitem__(se... |
class RawAudioDataset(FairseqDataset):
def __init__(self, sample_rate, max_sample_size=None, min_sample_size=None, shuffle=True, min_length=0):
super().__init__()
self.sample_rate = sample_rate
self.sizes = []
self.max_sample_size = (max_sample_size if (max_sample_size is not None... |
class FileAudioDataset(RawAudioDataset):
def __init__(self, manifest_path, sample_rate, max_sample_size=None, min_sample_size=None, shuffle=True, min_length=0):
super().__init__(sample_rate=sample_rate, max_sample_size=max_sample_size, min_sample_size=min_sample_size, shuffle=shuffle, min_length=min_leng... |
def backtranslate_samples(samples, collate_fn, generate_fn, cuda=True):
"Backtranslate a list of samples.\n\n Given an input (*samples*) of the form:\n\n [{'id': 1, 'source': 'hallo welt'}]\n\n this will return:\n\n [{'id': 1, 'source': 'hello world', 'target': 'hallo welt'}]\n\n Args:\n ... |
class BacktranslationDataset(FairseqDataset):
'\n Sets up a backtranslation dataset which takes a tgt batch, generates\n a src using a tgt-src backtranslation function (*backtranslation_fn*),\n and returns the corresponding `{generated src, input tgt}` batch.\n\n Args:\n tgt_dataset (~fairseq.d... |
class BaseWrapperDataset(FairseqDataset):
def __init__(self, dataset):
super().__init__()
self.dataset = dataset
def __getitem__(self, index):
return self.dataset[index]
def __len__(self):
return len(self.dataset)
def collater(self, samples):
if hasattr(self... |
class ColorizeDataset(BaseWrapperDataset):
" Adds 'colors' property to net input that is obtained from the provided color getter for use by models "
def __init__(self, dataset, color_getter):
super().__init__(dataset)
self.color_getter = color_getter
def collater(self, samples):
... |
class ConcatDataset(FairseqDataset):
@staticmethod
def cumsum(sequence, sample_ratios):
(r, s) = ([], 0)
for (e, ratio) in zip(sequence, sample_ratios):
curr_len = int((ratio * len(e)))
r.append((curr_len + s))
s += curr_len
return r
def __init... |
class ConcatSentencesDataset(FairseqDataset):
def __init__(self, *datasets):
super().__init__()
self.datasets = datasets
assert all(((len(ds) == len(datasets[0])) for ds in datasets)), 'datasets must have the same length'
def __getitem__(self, index):
return torch.cat([ds[ind... |
def infer_language_pair(path):
'Infer language pair from filename: <split>.<lang1>-<lang2>.(...).idx'
(src, dst) = (None, None)
for filename in os.listdir(path):
parts = filename.split('.')
if ((len(parts) >= 3) and (len(parts[1].split('-')) == 2)):
return parts[1].split('-')
... |
def collate_tokens(values, pad_idx, eos_idx=None, left_pad=False, move_eos_to_beginning=False):
'Convert a list of 1d tensors into a padded 2d tensor.'
size = max((v.size(0) for v in values))
res = values[0].new(len(values), size).fill_(pad_idx)
def copy_tensor(src, dst):
assert (dst.numel() ... |
def load_indexed_dataset(path, dictionary, dataset_impl=None, combine=False, default='cached'):
"A helper function for loading indexed datasets.\n\n Args:\n path (str): path to indexed dataset (e.g., 'data-bin/train')\n dictionary (~fairseq.data.Dictionary): data dictionary\n dataset_impl ... |
@contextlib.contextmanager
def numpy_seed(seed, *addl_seeds):
'Context manager which seeds the NumPy PRNG with the specified seed and\n restores the state afterward'
if (seed is None):
(yield)
return
if (len(addl_seeds) > 0):
seed = int((hash((seed, *addl_seeds)) % 1000000.0))
... |
def collect_filtered(function, iterable, filtered):
'\n Similar to :func:`filter` but collects filtered elements in ``filtered``.\n\n Args:\n function (callable): function that returns ``False`` for elements that\n should be filtered\n iterable (iterable): iterable to filter\n ... |
def _filter_by_size_dynamic(indices, size_fn, max_positions, raise_exception=False):
def check_size(idx):
if (isinstance(max_positions, float) or isinstance(max_positions, int)):
return (size_fn(idx) <= max_positions)
elif isinstance(max_positions, dict):
idx_size = size_f... |
def filter_by_size(indices, dataset, max_positions, raise_exception=False):
'\n Filter indices based on their size.\n\n Args:\n indices (List[int]): ordered list of dataset indices\n dataset (FairseqDataset): fairseq dataset instance\n max_positions (tuple): filter elements larger than ... |
def batch_by_size(indices, num_tokens_fn, max_tokens=None, max_sentences=None, required_batch_size_multiple=1):
'\n Yield mini-batches of indices bucketed by size. Batches may contain\n sequences of different lengths.\n\n Args:\n indices (List[int]): ordered list of dataset indices\n num_to... |
def process_bpe_symbol(sentence: str, bpe_symbol: str):
if (bpe_symbol == 'sentencepiece'):
sentence = sentence.replace(' ', '').replace('▁', ' ').strip()
elif (bpe_symbol == '_EOW'):
sentence = sentence.replace(' ', '').replace('_EOW', ' ').strip()
elif (bpe_symbol is not None):
s... |
def collate(samples, pad_idx, eos_idx, vocab, left_pad_source=False, left_pad_target=False, input_feeding=True):
assert input_feeding
if (len(samples) == 0):
return {}
def merge(key, left_pad, move_eos_to_beginning=False):
return data_utils.collate_tokens([s[key] for s in samples], pad_id... |
class DenoisingDataset(FairseqDataset):
'\n A wrapper around TokenBlockDataset for BART dataset.\n\n Args:\n dataset (TokenBlockDataset): dataset to wrap\n sizes (List[int]): sentence lengths\n vocab (~fairseq.data.Dictionary): vocabulary\n mask_idx (int): dictionary index used f... |
class Dictionary(object):
'A mapping from symbols to consecutive integers'
def __init__(self, pad='<pad>', eos='</s>', unk='<unk>', bos='<s>', extra_special_symbols=None):
(self.unk_word, self.pad_word, self.eos_word) = (unk, pad, eos)
self.symbols = []
self.count = []
self.in... |
class TruncatedDictionary(object):
def __init__(self, wrapped_dict, length):
self.__class__ = type(wrapped_dict.__class__.__name__, (self.__class__, wrapped_dict.__class__), {})
self.__dict__ = wrapped_dict.__dict__
self.wrapped_dict = wrapped_dict
self.length = min(len(self.wrapp... |
@register_bpe('fastbpe')
class fastBPE(object):
@staticmethod
def add_args(parser):
parser.add_argument('--bpe-codes', type=str, help='path to fastBPE BPE')
def __init__(self, args):
if (args.bpe_codes is None):
raise ValueError('--bpe-codes is required for --bpe=subword_nmt'... |
@register_bpe('gpt2')
class GPT2BPE(object):
@staticmethod
def add_args(parser):
parser.add_argument('--gpt2-encoder-json', type=str, default=DEFAULT_ENCODER_JSON, help='path to encoder.json')
parser.add_argument('--gpt2-vocab-bpe', type=str, default=DEFAULT_VOCAB_BPE, help='path to vocab.bpe... |
@lru_cache()
def bytes_to_unicode():
"\n Returns list of utf-8 byte and a corresponding list of unicode strings.\n The reversible bpe codes work on unicode strings.\n This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.\n When you're at something like a 10B toke... |
def get_pairs(word):
'Return set of symbol pairs in a word.\n Word is represented as tuple of symbols (symbols being variable-length strings).\n '
pairs = set()
prev_char = word[0]
for char in word[1:]:
pairs.add((prev_char, char))
prev_char = char
return pairs
|
class Encoder():
def __init__(self, encoder, bpe_merges, errors='replace'):
self.encoder = encoder
self.decoder = {v: k for (k, v) in self.encoder.items()}
self.errors = errors
self.byte_encoder = bytes_to_unicode()
self.byte_decoder = {v: k for (k, v) in self.byte_encoder... |
def get_encoder(encoder_json_path, vocab_bpe_path):
with open(encoder_json_path, 'r') as f:
encoder = json.load(f)
with open(vocab_bpe_path, 'r', encoding='utf-8') as f:
bpe_data = f.read()
bpe_merges = [tuple(merge_str.split()) for merge_str in bpe_data.split('\n')[1:(- 1)]]
return En... |
@register_bpe('bert')
class BertBPE(object):
@staticmethod
def add_args(parser):
parser.add_argument('--bpe-cased', action='store_true', help='set for cased BPE', default=False)
parser.add_argument('--bpe-vocab-file', type=str, help='bpe vocab file.')
def __init__(self, args):
tr... |
@register_tokenizer('moses')
class MosesTokenizer(object):
@staticmethod
def add_args(parser):
parser.add_argument('--moses-source-lang', metavar='SRC', help='source language')
parser.add_argument('--moses-target-lang', metavar='TARGET', help='target language')
parser.add_argument('--... |
@register_tokenizer('nltk')
class NLTKTokenizer(object):
def __init__(self, source_lang=None, target_lang=None):
try:
from nltk.tokenize import word_tokenize
self.word_tokenize = word_tokenize
except ImportError:
raise ImportError('Please install nltk with: pip... |
@register_bpe('sentencepiece')
class SentencepieceBPE(object):
@staticmethod
def add_args(parser):
parser.add_argument('--sentencepiece-vocab', type=str, help='path to sentencepiece vocab')
def __init__(self, args):
vocab = file_utils.cached_path(args.sentencepiece_vocab)
try:
... |
@register_tokenizer('space')
class SpaceTokenizer(object):
def __init__(self, source_lang=None, target_lang=None):
self.space_tok = re.compile('\\s+')
def encode(self, x: str) -> str:
return self.space_tok.sub(' ', x)
def decode(self, x: str) -> str:
return x
|
@register_bpe('subword_nmt')
class SubwordNMTBPE(object):
@staticmethod
def add_args(parser):
parser.add_argument('--bpe-codes', type=str, help='path to subword NMT BPE')
parser.add_argument('--bpe-separator', default='@@', help='BPE separator')
def __init__(self, args):
if (args... |
def get_whole_word_mask(args, dictionary):
bpe = encoders.build_bpe(args)
if (bpe is not None):
def is_beginning_of_word(i):
if (i < dictionary.nspecial):
return True
tok = dictionary[i]
if tok.startswith('madeupword'):
return True
... |
class EpochListening():
'Mixin for receiving updates whenever the epoch increments.'
def set_epoch(self, epoch):
'Will receive the updated epoch number at the beginning of the epoch.\n '
pass
|
class FairseqDataset(torch.utils.data.Dataset, EpochListening):
'A dataset that provides helpers for batching.'
def __getitem__(self, index):
raise NotImplementedError
def __len__(self):
raise NotImplementedError
def collater(self, samples):
'Merge a list of samples to form ... |
class FairseqIterableDataset(torch.utils.data.IterableDataset, EpochListening):
"For datasets that need to be read sequentially, usually because the data\n is being streamed or otherwise can't be manipulated on a single machine.\n "
def __iter__(self):
raise NotImplementedError
|
class IdDataset(FairseqDataset):
def __getitem__(self, index):
return index
def __len__(self):
return 0
def collater(self, samples):
return torch.tensor(samples)
|
def __best_fitting_dtype(vocab_size=None):
if ((vocab_size is not None) and (vocab_size < 65500)):
return np.uint16
else:
return np.int32
|
def get_available_dataset_impl():
return ['raw', 'lazy', 'cached', 'mmap']
|
def infer_dataset_impl(path):
if IndexedRawTextDataset.exists(path):
return 'raw'
elif IndexedDataset.exists(path):
with open(index_file_path(path), 'rb') as f:
magic = f.read(8)
if (magic == IndexedDataset._HDR_MAGIC):
return 'cached'
elif (... |
def make_builder(out_file, impl, vocab_size=None):
if (impl == 'mmap'):
return MMapIndexedDatasetBuilder(out_file, dtype=__best_fitting_dtype(vocab_size))
else:
return IndexedDatasetBuilder(out_file)
|
def make_dataset(path, impl, fix_lua_indexing=False, dictionary=None):
if ((impl == 'raw') and IndexedRawTextDataset.exists(path)):
assert (dictionary is not None)
return IndexedRawTextDataset(path, dictionary)
elif ((impl == 'lazy') and IndexedDataset.exists(path)):
return IndexedData... |
def dataset_exists(path, impl):
if (impl == 'raw'):
return IndexedRawTextDataset.exists(path)
elif (impl == 'mmap'):
return MMapIndexedDataset.exists(path)
else:
return IndexedDataset.exists(path)
|
def read_longs(f, n):
a = np.empty(n, dtype=np.int64)
f.readinto(a)
return a
|
def write_longs(f, a):
f.write(np.array(a, dtype=np.int64))
|
def code(dtype):
for k in dtypes.keys():
if (dtypes[k] == dtype):
return k
raise ValueError(dtype)
|
def index_file_path(prefix_path):
return (prefix_path + '.idx')
|
def data_file_path(prefix_path):
return (prefix_path + '.bin')
|
class IndexedDataset(FairseqDataset):
'Loader for TorchNet IndexedDataset'
_HDR_MAGIC = b'TNTIDX\x00\x00'
def __init__(self, path, fix_lua_indexing=False):
super().__init__()
self.path = path
self.fix_lua_indexing = fix_lua_indexing
self.data_file = None
self.read_... |
class IndexedCachedDataset(IndexedDataset):
def __init__(self, path, fix_lua_indexing=False):
super().__init__(path, fix_lua_indexing=fix_lua_indexing)
self.cache = None
self.cache_index = {}
@property
def supports_prefetch(self):
return True
def prefetch(self, indic... |
class IndexedRawTextDataset(FairseqDataset):
'Takes a text file as input and binarizes it in memory at instantiation.\n Original lines are also kept in memory'
def __init__(self, path, dictionary, append_eos=True, reverse_order=False):
self.tokens_list = []
self.lines = []
self.siz... |
class IndexedDatasetBuilder(object):
element_sizes = {np.uint8: 1, np.int8: 1, np.int16: 2, np.int32: 4, np.int64: 8, np.float: 4, np.double: 8}
def __init__(self, out_file, dtype=np.int32):
self.out_file = open(out_file, 'wb')
self.dtype = dtype
self.data_offsets = [0]
self.d... |
def _warmup_mmap_file(path):
with open(path, 'rb') as stream:
while stream.read(((100 * 1024) * 1024)):
pass
|
class MMapIndexedDataset(torch.utils.data.Dataset):
class Index(object):
_HDR_MAGIC = b'MMIDIDX\x00\x00'
@classmethod
def writer(cls, path, dtype):
class _Writer(object):
def __enter__(self):
self._file = open(path, 'wb')
... |
class MMapIndexedDatasetBuilder(object):
def __init__(self, out_file, dtype=np.int64):
self._data_file = open(out_file, 'wb')
self._dtype = dtype
self._sizes = []
def add_item(self, tensor):
np_array = np.array(tensor.numpy(), dtype=self._dtype)
self._data_file.write(... |
class CountingIterator(object):
'Wrapper around an iterable that maintains the iteration count.\n\n Args:\n iterable (iterable): iterable to wrap\n\n Attributes:\n count (int): number of elements consumed from this iterator\n '
def __init__(self, iterable, start=0):
self.iterab... |
class EpochBatchIterating(object):
def __len__(self) -> int:
raise NotImplementedError
def next_epoch_itr(self, shuffle=True, fix_batches_to_gpus=False):
'Return a new iterator over the dataset.\n\n Args:\n shuffle (bool, optional): shuffle batches before returning the\n ... |
class StreamingEpochBatchIterator(EpochBatchIterating):
def __init__(self, dataset, epoch=0, num_shards=1, shard_id=0):
assert isinstance(dataset, torch.utils.data.IterableDataset)
self.dataset = dataset
self.epoch = epoch
self._current_epoch_iterator = None
self.num_shard... |
class EpochBatchIterator(EpochBatchIterating):
'A multi-epoch iterator over a :class:`torch.utils.data.Dataset`.\n\n Compared to :class:`torch.utils.data.DataLoader`, this iterator:\n\n - can be reused across multiple epochs with the :func:`next_epoch_itr`\n method (optionally shuffled between epochs)\... |
class GroupedIterator(object):
'Wrapper around an iterable that returns groups (chunks) of items.\n\n Args:\n iterable (iterable): iterable to wrap\n chunk_size (int): size of each chunk\n '
def __init__(self, iterable, chunk_size):
self._len = int(math.ceil((len(iterable) / float... |
class ShardedIterator(object):
"A sharded wrapper around an iterable, padded to length.\n\n Args:\n iterable (iterable): iterable to wrap\n num_shards (int): number of shards to split the iterable into\n shard_id (int): which shard to iterator over\n fill_value (Any, optional): padd... |
class BlockPairDataset(FairseqDataset):
"Break a Dataset of tokens into sentence pair blocks for next sentence\n prediction as well as masked language model.\n\n High-level logics are:\n 1. break input tensor to tensor blocks\n 2. pair the blocks with 50% next sentence and 50% random sente... |
class MaskedLMDataset(FairseqDataset):
'\n A wrapper Dataset for masked language modelling. The dataset\n wraps around TokenBlockDataset or BlockedPairDataset and creates a batch\n where the input blocks are masked according to the specified masking\n probability. Additionally the batch can also conta... |
class MaskedLMDictionary(Dictionary):
'\n Dictionary for Masked Language Modelling tasks. This extends Dictionary by\n adding the mask symbol.\n '
def __init__(self, pad='<pad>', eos='</s>', unk='<unk>', mask='<mask>'):
super().__init__(pad, eos, unk)
self.mask_word = mask
se... |
class BertDictionary(MaskedLMDictionary):
'\n Dictionary for BERT task. This extends MaskedLMDictionary by adding support\n for cls and sep symbols.\n '
def __init__(self, pad='<pad>', eos='</s>', unk='<unk>', mask='<mask>', cls='<cls>', sep='<sep>'):
super().__init__(pad, eos, unk, mask)
... |
class ListDataset(BaseWrapperDataset):
def __init__(self, dataset, sizes=None):
super().__init__(dataset)
self._sizes = sizes
def __iter__(self):
for x in self.dataset:
(yield x)
def collater(self, samples):
return samples
@property
def sizes(self):
... |
class LRUCacheDataset(BaseWrapperDataset):
def __init__(self, dataset, token=None):
super().__init__(dataset)
@lru_cache(maxsize=8)
def __getitem__(self, index):
return self.dataset[index]
@lru_cache(maxsize=8)
def collater(self, samples):
return self.dataset.collater(sa... |
class MaskTokensDataset(BaseWrapperDataset):
'\n A wrapper Dataset for masked language modeling.\n\n Input items are masked according to the specified masking probability.\n\n Args:\n dataset: Dataset to wrap.\n sizes: Sentence lengths\n vocab: Dictionary with the vocabulary and spec... |
def collate(samples, pad_idx, eos_idx):
if (len(samples) == 0):
return {}
def merge(key, is_list=False):
if is_list:
res = []
for i in range(len(samples[0][key])):
res.append(data_utils.collate_tokens([s[key][i] for s in samples], pad_idx, eos_idx, left... |
class MonolingualDataset(FairseqDataset):
'\n A wrapper around torch.utils.data.Dataset for monolingual data.\n\n Args:\n dataset (torch.utils.data.Dataset): dataset to wrap\n sizes (List[int]): sentence lengths\n vocab (~fairseq.data.Dictionary): vocabulary\n shuffle (bool, opti... |
def uniform_sampler(x):
return np.random.choice(x, 1).item()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.