Skip to content
This repository has been archived by the owner on Dec 16, 2022. It is now read-only.

Data V2 #3700

Merged
merged 59 commits into from
Feb 26, 2020
Merged

Data V2 #3700

Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
59 commits
Select commit Hold shift + click to select a range
0c42cb9
example for feedback
DeNeutoy Jan 30, 2020
5ffedfc
Merge branch 'master' into data-v2
DeNeutoy Feb 19, 2020
80049f8
remove all existing multiprocessing
DeNeutoy Feb 19, 2020
6f58c2a
sneak torch datasets inside DatasetReader
DeNeutoy Feb 19, 2020
1b3ad9a
lint
DeNeutoy Feb 19, 2020
effc445
trainer_v2, We Love To See It
DeNeutoy Feb 19, 2020
9d44ad6
datasets have index_with now, not iterators
DeNeutoy Feb 19, 2020
7e89ea6
use iter, custom collate function in allennlp wrapper
DeNeutoy Feb 19, 2020
883b6d7
we don't even need the data in the trainer anymore
DeNeutoy Feb 19, 2020
56d022a
all trainer tests passing
DeNeutoy Feb 20, 2020
01e12f5
black
DeNeutoy Feb 20, 2020
5aea291
make find learning rate work
DeNeutoy Feb 20, 2020
f026946
update test fixtures to new config
DeNeutoy Feb 20, 2020
5973b50
get train command tests mostly working
DeNeutoy Feb 20, 2020
a23f47a
lazily construct samplers, index lazy datasets
DeNeutoy Feb 20, 2020
a76ea0a
Merge branch 'master' into data-v2
DeNeutoy Feb 20, 2020
ebf3854
update some fixtures
DeNeutoy Feb 20, 2020
57a67e5
evaluate tests passing
DeNeutoy Feb 20, 2020
7d21ed8
all command tests passing
DeNeutoy Feb 20, 2020
24a500c
lint
DeNeutoy Feb 20, 2020
fb13769
update model test case, common and module tests passing
DeNeutoy Feb 20, 2020
ef5187f
fix test interdependence introduced by #3762
DeNeutoy Feb 21, 2020
b1ea845
more test interdependence
DeNeutoy Feb 21, 2020
0231616
tests tests tests
DeNeutoy Feb 21, 2020
01d76bb
remove unnecessary brackets
DeNeutoy Feb 21, 2020
12b6efb
Merge branch 'master' into data-v2
DeNeutoy Feb 21, 2020
859d3ca
update a chunk of the configs
DeNeutoy Feb 21, 2020
c22dee3
fix archival test, couple more configs
DeNeutoy Feb 21, 2020
fe5b470
rm pointless gan test
DeNeutoy Feb 21, 2020
7533c91
more tests passing
DeNeutoy Feb 21, 2020
ad45659
add current state of from params changes
DeNeutoy Feb 21, 2020
f944840
Revert "add current state of from params changes"
DeNeutoy Feb 21, 2020
3b12a2f
Merge branch 'master' into data-v2
DeNeutoy Feb 21, 2020
be1f58c
updated understanding of Lazy
DeNeutoy Feb 21, 2020
ebdabe0
add discussion of None comparison to Lazy
DeNeutoy Feb 21, 2020
8693739
lint
DeNeutoy Feb 21, 2020
b9b0650
it's a hard doc life
DeNeutoy Feb 21, 2020
88314c7
pull samplers into separate file
DeNeutoy Feb 21, 2020
14296a1
more docs updates
DeNeutoy Feb 22, 2020
8a08899
fold in #3812
DeNeutoy Feb 22, 2020
3520280
remove torch dataset
DeNeutoy Feb 22, 2020
0f1d8a4
add example to lazy
DeNeutoy Feb 22, 2020
93e1e89
rename to collate
DeNeutoy Feb 22, 2020
40dd695
no kwargs
DeNeutoy Feb 23, 2020
da3b1b4
Revert "fold in #3812"
DeNeutoy Feb 23, 2020
801a8f5
don't break up dataset
DeNeutoy Feb 23, 2020
007fd0c
add comment to iterable dataset len
DeNeutoy Feb 23, 2020
d00e1a9
Merge branch 'master' into data-v2
DeNeutoy Feb 23, 2020
c066804
improve docstrings, build dataloader using partial_objects
DeNeutoy Feb 23, 2020
61c7b14
flake
DeNeutoy Feb 23, 2020
2b56b14
give dataloader a default implementation
DeNeutoy Feb 24, 2020
354010a
safer default for DataLoader init
DeNeutoy Feb 24, 2020
568291d
more coherent dir structure
DeNeutoy Feb 24, 2020
a016103
update imports
DeNeutoy Feb 24, 2020
47db16a
Merge branch 'master' into data-v2
DeNeutoy Feb 24, 2020
04fdb70
add a test for the BucketBatchSampler
DeNeutoy Feb 24, 2020
d1d5c4a
split bucket sampler into own file, tests
DeNeutoy Feb 24, 2020
5f0c8db
PR comments
DeNeutoy Feb 26, 2020
6f63a53
Merge branch 'master' into data-v2
DeNeutoy Feb 26, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
trainer_v2, We Love To See It
  • Loading branch information
DeNeutoy committed Feb 19, 2020
commit effc44518a3b60313c7ad37bcdeb10460a09463e
197 changes: 197 additions & 0 deletions allennlp/data/samplers/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@

from typing import List, Iterable, Tuple, Dict, cast
import logging
from torch.utils import data

from allennlp.common.registrable import Registrable

from allennlp.common.util import add_noise_to_dict_values, lazy_groups_of
from allennlp.data.batch import Batch as AllennlpBatch
from allennlp.data.instance import Instance
from allennlp.data.vocabulary import Vocabulary
from allennlp.data import Token
from allennlp.common.file_utils import cached_path
from allennlp.data.fields import Field, TextField, LabelField, MetadataField
from allennlp.data.token_indexers import SingleIdTokenIndexer, TokenIndexer

logger = logging.getLogger(__name__)


class Sampler(Registrable):

def __iter__(self) -> Iterable[int]:

raise NotImplementedError


class BatchSampler(Registrable):

def __iter__(self) -> Iterable[List[int]]:

raise NotImplementedError


@Sampler.register("sequential")
class SequentialSampler(Sampler, data.SequentialSampler):

def __init__(self, data_source: data.Dataset):
super().__init__(data_source)



@Sampler.register("random")
class RandomSampler(Sampler, data.RandomSampler):
r"""Samples elements randomly. If without replacement, then sample from a shuffled dataset.
If with replacement, then user can specify :attr:`num_samples` to draw.

Arguments:
data_source (Dataset): dataset to sample from
replacement (bool): samples are drawn with replacement if ``True``, default=``False``
num_samples (int): number of samples to draw, default=`len(dataset)`. This argument
is supposed to be specified only when `replacement` is ``True``.
"""
def __init__(self, data_source: data.Dataset, replacement: bool = False, num_samples: int = None):
super().__init__(data_source, replacement, num_samples)


@Sampler.register("subset_random")
class SubsetRandomSampler(Sampler, data.SubsetRandomSampler):
r"""Samples elements randomly from a given list of indices, without replacement.

Arguments:
indices (sequence): a sequence of indices
"""
def __init__(self, indices: List[int]):
super().__init__(indices)


@Sampler.register("weighted_random")
class WeightedRandomSampler(Sampler, data.WeightedRandomSampler):
r"""Samples elements from ``[0,..,len(weights)-1]`` with given probabilities (weights).

Args:
weights (sequence) : a sequence of weights, not necessary summing up to one
num_samples (int): number of samples to draw
replacement (bool): if ``True``, samples are drawn with replacement.
If not, they are drawn without replacement, which means that when a
sample index is drawn for a row, it cannot be drawn again for that row.

Example:
>>> list(WeightedRandomSampler([0.1, 0.9, 0.4, 0.7, 3.0, 0.6], 5, replacement=True))
[0, 0, 0, 1, 0]
>>> list(WeightedRandomSampler([0.9, 0.4, 0.05, 0.2, 0.3, 0.1], 5, replacement=False))
[0, 1, 4, 3, 2]
"""
def __init__(self, weights: List[float], num_samples: int, replacement: bool = True):
super().__init__(weights, num_samples, replacement)


@BatchSampler.register("basic")
class BasicBatchSampler(BatchSampler, data.BatchSampler):
r"""Wraps another sampler to yield a mini-batch of indices.

Args:
sampler (Sampler): Base sampler.
batch_size (int): Size of mini-batch.
drop_last (bool): If ``True``, the sampler will drop the last batch if
its size would be less than ``batch_size``

Example:
>>> list(BatchSampler(SequentialSampler(range(10)), batch_size=3, drop_last=False))
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
>>> list(BatchSampler(SequentialSampler(range(10)), batch_size=3, drop_last=True))
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]
"""

def __init__(self, sampler: Sampler, batch_size: int, drop_last: bool):
super().__init__(sampler, batch_size, drop_last)


@BatchSampler.register("bucket")
class BatchInstanceSampler(BatchSampler):
def __init__(
self,
data: data.Dataset,
batch_size: int,
sorting_keys: List[Tuple[str, str]] = None,
padding_noise: float = 0.1,
):

self.vocab = data.vocab
self._sorting_keys = sorting_keys
self._padding_noise = padding_noise
self._batch_size = batch_size
self.data = data

def _argsort_by_padding(self, instances: List[Instance]) -> List[int]:
"""
Sorts the instances by their padding lengths, using the keys in
`sorting_keys` (in the order in which they are provided). `sorting_keys` is a list of
`(field_name, padding_key)` tuples.
"""
if not self._sorting_keys:
logger.info("No sorting keys given; trying to guess a good one")
self._guess_sorting_keys(instances)
logger.info(f"Using {self._sorting_keys} as the sorting keys")
instances_with_lengths = []
for instance in instances:
# Make sure instance is indexed before calling .get_padding
instance.index_fields(self.vocab)
padding_lengths = cast(Dict[str, Dict[str, float]], instance.get_padding_lengths())
if self._padding_noise > 0.0:
noisy_lengths = {}
for field_name, field_lengths in padding_lengths.items():
noisy_lengths[field_name] = add_noise_to_dict_values(
field_lengths, self._padding_noise
)
padding_lengths = noisy_lengths
instance_with_lengths = (
[
padding_lengths[field_name][padding_key]
for (field_name, padding_key) in self._sorting_keys
],
instance,
)
instances_with_lengths.append(instance_with_lengths)
with_indices = [(x, i) for i, x in enumerate(instances_with_lengths)]
with_indices.sort(key=lambda x: x[0][0])
return [instance_with_index[-1] for instance_with_index in with_indices]

def __iter__(self) -> Iterable[List[int]]:

indices = self._argsort_by_padding(self.data)
for group in lazy_groups_of(indices, self._batch_size):
yield list(group)

def _guess_sorting_keys(self, instances: List[Instance]) -> None:
max_length = 0.0
longest_padding_key: Tuple[str, str] = None
for instance in instances:
instance.index_fields(self.vocab)
padding_lengths = cast(Dict[str, Dict[str, float]], instance.get_padding_lengths())
for field_name, field_padding in padding_lengths.items():
for padding_key, length in field_padding.items():
if length > max_length:
max_length = length
longest_padding_key = (field_name, padding_key)
if not longest_padding_key:
# This shouldn't ever happen (you basically have to have an empty instance list), but
# just in case...
raise AssertionError(
"Found no field that needed padding; we are surprised you got this error, please "
"open an issue on github"
)
self._sorting_keys = [longest_padding_key]


class DataLoader(Registrable, data.DataLoader):

def __init__(self, dataset: data.Dataset, batch_size: int = 1, shuffle: bool = False, sampler: Sampler = None,
batch_sampler: BatchSampler = None, num_workers: int = 0, collate_fn=None,
pin_memory: bool = False, drop_last: bool = False, timeout: bool = 0,
worker_init_fn=None, multiprocessing_context: str = None):

super().__init__(self, dataset=dataset, batch_size=batch_size, shuffle=shuffle, sampler=sampler,
batch_sampler=batch_sampler, num_workers=num_workers, collate_fn=collate_fn,
pin_memory=pin_memory, drop_last=drop_last, timeout=timeout,
worker_init_fn=worker_init_fn, multiprocessing_context=multiprocessing_context)
Loading