code stringlengths 17 6.64M |
|---|
def PrintUsage(message):
'Prints a brief usage string and exits, optionally with an error message.\n\n Args:\n message: The optional error message.\n '
sys.stderr.write(_USAGE)
if message:
sys.exit(('\nFATAL ERROR: ' + message))
else:
sys.exit(1)
|
def PrintCategories():
'Prints a list of all the error-categories used by error messages.\n\n These are the categories used to filter messages via --filter.\n '
sys.stderr.write(''.join(((' %s\n' % cat) for cat in _ERROR_CATEGORIES)))
sys.exit(0)
|
def ParseArguments(args):
'Parses the command line arguments.\n\n This may set the output format and verbosity level as side-effects.\n\n Args:\n args: The command line arguments:\n\n Returns:\n The list of filenames to lint.\n '
try:
(opts, filenames) = getopt.getopt(args, '', ['help', 'out... |
def main():
filenames = ParseArguments(sys.argv[1:])
sys.stderr = codecs.StreamReaderWriter(sys.stderr, codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace')
_cpplint_state.ResetErrorCounts()
for filename in filenames:
ProcessFile(filename, _cpplint_state.verbose_level)
_cpplint_s... |
def reporthook(count, block_size, total_size):
'\n From http://blog.moleculea.com/2012/10/04/urlretrieve-progres-indicator/\n '
global start_time
if (count == 0):
start_time = time.time()
return
duration = (time.time() - start_time)
progress_size = int((count * block_size))
... |
def parse_readme_frontmatter(dirname):
readme_filename = os.path.join(dirname, 'readme.md')
with open(readme_filename) as f:
lines = [line.strip() for line in f.readlines()]
top = lines.index('---')
bottom = lines.index('---', (top + 1))
frontmatter = yaml.load('\n'.join(lines[(top + 1):bo... |
def valid_dirname(dirname):
try:
return parse_readme_frontmatter(dirname)
except Exception as e:
print('ERROR: {}'.format(e))
raise argparse.ArgumentTypeError('Must be valid Caffe model directory with a correct readme.md')
|
def extract_datetime_from_line(line, year):
line = line.strip().split()
month = int(line[0][1:3])
day = int(line[0][3:])
timestamp = line[1]
pos = timestamp.rfind('.')
ts = [int(x) for x in timestamp[:pos].split(':')]
hour = ts[0]
minute = ts[1]
second = ts[2]
microsecond = int... |
def get_log_created_year(input_file):
'Get year from log file system timestamp\n '
log_created_time = os.path.getctime(input_file)
log_created_year = datetime.datetime.fromtimestamp(log_created_time).year
return log_created_year
|
def get_start_time(line_iterable, year):
'Find start time from group of lines\n '
start_datetime = None
for line in line_iterable:
line = line.strip()
if (line.find('Solving') != (- 1)):
start_datetime = extract_datetime_from_line(line, year)
break
return sta... |
def extract_seconds(input_file, output_file):
with open(input_file, 'r') as f:
lines = f.readlines()
log_created_year = get_log_created_year(input_file)
start_datetime = get_start_time(lines, log_created_year)
assert start_datetime, 'Start time not found'
out = open(output_file, 'w')
f... |
def main(args):
node_to_rank = json.load(open('node_to_rank.json', 'r'))
args.master_addr = {v: k for (k, v) in node_to_rank.items()}[0]
os.environ['MASTER_ADDR'] = args.master_addr
os.environ['MASTER_PORT'] = '10000'
host = socket.gethostbyname(socket.gethostname())
args.distributed_port = '1... |
class WordStat(object):
def __init__(self, word, is_bpe):
self.word = word
self.is_bpe = is_bpe
self.log_prob = 0
self.next_word_prob = 0
self.count = 0
self.missing_next_words = 0
def add(self, log_prob, next_word_prob):
' increments counters for the ... |
def main(parsed_args):
assert (parsed_args.path is not None), '--path required for evaluation!'
utils.import_user_module(parsed_args)
print(parsed_args)
use_cuda = (torch.cuda.is_available() and (not parsed_args.cpu))
task = tasks.setup_task(parsed_args)
print('| loading model(s) from {}'.form... |
def cli_main():
parser = options.get_eval_lm_parser()
args = options.parse_args_and_arch(parser)
main(args)
|
def safe_readline(f):
pos = f.tell()
while True:
try:
return f.readline()
except UnicodeDecodeError:
pos -= 1
f.seek(pos)
|
class Binarizer():
@staticmethod
def binarize(filename, dict, consumer, tokenize=tokenize_line, append_eos=True, reverse_order=False, offset=0, end=(- 1)):
(nseq, ntok) = (0, 0)
replaced = Counter()
def replaced_consumer(word, idx):
if ((idx == dict.unk_index) and (word !... |
class BleuStat(ctypes.Structure):
_fields_ = [('reflen', ctypes.c_size_t), ('predlen', ctypes.c_size_t), ('match1', ctypes.c_size_t), ('count1', ctypes.c_size_t), ('match2', ctypes.c_size_t), ('count2', ctypes.c_size_t), ('match3', ctypes.c_size_t), ('count3', ctypes.c_size_t), ('match4', ctypes.c_size_t), ('coun... |
class SacrebleuScorer(object):
def __init__(self):
import sacrebleu
self.sacrebleu = sacrebleu
self.reset()
def reset(self, one_init=False):
if one_init:
raise NotImplementedError
self.ref = []
self.sys = []
def add_string(self, ref, pred):
... |
class Scorer(object):
def __init__(self, pad, eos, unk):
self.stat = BleuStat()
self.pad = pad
self.eos = eos
self.unk = unk
self.reset()
def reset(self, one_init=False):
if one_init:
C.bleu_one_init(ctypes.byref(self.stat))
else:
... |
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, data_selector=None):
'Load a checkpoint and restore the training iterator.'
if (args.distributed_rank == 0):
os.makedirs(args.save_dir, exist_ok=True)
if (args.restore_file == 'checkpoint_last.pt'):
checkpoint_path = os.path.join(args.save_dir, 'checkpoin... |
def load_checkpoint_to_cpu(path, arg_overrides=None):
'Loads a checkpoint to CPU (with upgrading for backward compatibility).'
try:
with open(path, 'rb') as f:
state = torch.load(f, map_location=(lambda s, l: default_restore_location(s, 'cpu')))
except (ModuleNotFoundError, ImportError... |
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):
logging.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:
print('| Unable to access ... |
@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):
'Compute the loss for the given sample.\n\n Returns a tuple with three elements:... |
@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... |
@register_criterion('label_smoothed_cross_entropy_with_reg')
class LabelSmoothedCrossEntropyCriterionWithReg(LabelSmoothedCrossEntropyCriterion):
def __init__(self, args, task):
super().__init__(args, task)
self.reg_lambda_hidden = args.reg_lambda_hidden
self.reg_lambda_div = args.reg_lam... |
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 __init__(self, args, task):
super().__init__(args, task)
def forward(self, model, sample, reduce=True):
'Compute the loss for... |
@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('--save-predictions', metavar='FILE', help='file to save predictions to')
def forward(self, model, sample, reduce=True):
'Compute the lo... |
@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 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... |
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... |
class FairseqDataset(torch.utils.data.Dataset):
'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 a mini-batch.\n\... |
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):
raise NotImplementedError
def end_of_epoch(self) -> bool:
'Returns whether the most recent epoch iterator has been exhausted'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.