repo
stringclasses
856 values
pull_number
int64
3
127k
instance_id
stringlengths
12
58
issue_numbers
sequencelengths
1
5
base_commit
stringlengths
40
40
patch
stringlengths
67
1.54M
test_patch
stringlengths
0
107M
problem_statement
stringlengths
3
307k
hints_text
stringlengths
0
908k
created_at
timestamp[s]
pytorch/text
145
pytorch__text-145
[ "143" ]
4ed903be7e59c0ea0ea901ea5261418991d9cd3d
diff --git a/torchtext/data/example.py b/torchtext/data/example.py --- a/torchtext/data/example.py +++ b/torchtext/data/example.py @@ -56,7 +56,9 @@ def fromlist(cls, data, fields): ex = cls() for (name, field), val in zip(fields, data): if field is not None: - setattr(ex, name, field.preprocess(val.rstrip('\n'))) + if isinstance(val, six.string_types): + val = val.rstrip('\n') + setattr(ex, name, field.preprocess(val)) return ex @classmethod
AttributeError: 'list' object has no attribute 'rstrip' Hi all, previously torchtext works for me when I'm running anaconda python. However, now, when i uninstalled my anaconda python. It stops working. It gives me the following error: ``` File "/Library/Python/2.7/site-packages/torchtext/data/example.py", line 59, in fromlist setattr(ex, name, field.preprocess(val.rstrip('\n'))) AttributeError: 'list' object has no attribute 'rstrip' ``` Thanks!
2017-10-16T00:01:46
pytorch/text
146
pytorch__text-146
[ "144" ]
db2e26c490d7d70db3edabf8ddc301275845d635
diff --git a/torchtext/data/dataset.py b/torchtext/data/dataset.py --- a/torchtext/data/dataset.py +++ b/torchtext/data/dataset.py @@ -124,14 +124,14 @@ def download(cls, root, check=None): class TabularDataset(Dataset): """Defines a Dataset of columns stored in CSV, TSV, or JSON format.""" - def __init__(self, path, format, fields, **kwargs): + def __init__(self, path, format, fields, skip_header=False, **kwargs): """Create a TabularDataset given a path, file format, and field list. Arguments: path (str): Path to the data file. format (str): The format of the data file. One of "CSV", "TSV", or "JSON" (case-insensitive). - fields (list(tuple(str, Field)) or dict[str, (name, Field)]: For CSV and + fields (list(tuple(str, Field)) or dict[str: tuple(str, Field)]: For CSV and TSV formats, list of tuples of (name, field). The list should be in the same order as the columns in the CSV or TSV file, while tuples of (name, None) represent columns that will be ignored. For JSON format, @@ -139,12 +139,15 @@ def __init__(self, path, format, fields, **kwargs): (name, field). This allows the user to rename columns from their JSON key names and also enables selecting a subset of columns to load (since JSON keys not present in the input dictionary are ignored). + skip_header (bool): Whether to skip the first line of the input file. """ make_example = { 'json': Example.fromJSON, 'dict': Example.fromdict, 'tsv': Example.fromTSV, 'csv': Example.fromCSV}[format.lower()] with io.open(os.path.expanduser(path), encoding="utf8") as f: + if skip_header: + next(f) examples = [make_example(line, fields) for line in f] if make_example in (Example.fromdict, Example.fromJSON):
Escape csv header lines I haven't been able to see how to skip first csv line in case of loading from a file with header. I could of course preprocess the file, but it'd be nice if there was an option to TabularDataset to tell it to skip the first line.
Oh, that's definitely worth including.
2017-10-16T00:14:47
pytorch/text
149
pytorch__text-149
[ "148" ]
b579fbe0e274457d142fab49a066c5457b1cde4c
diff --git a/torchtext/datasets/translation.py b/torchtext/datasets/translation.py --- a/torchtext/datasets/translation.py +++ b/torchtext/datasets/translation.py @@ -73,7 +73,8 @@ class Multi30k(TranslationDataset): urls = ['http://www.quest.dcs.shef.ac.uk/wmt16_files_mmt/training.tar.gz', 'http://www.quest.dcs.shef.ac.uk/wmt16_files_mmt/validation.tar.gz', - 'https://staff.fnwi.uva.nl/d.elliott/wmt16/mmt16_task1_test.tgz'] + 'http://www.quest.dcs.shef.ac.uk/' + 'wmt17_files_mmt/mmt_task1_test2016.tar.gz'] name = 'multi30k' dirname = ''
Multi30k Test Set URL Changed Looks like the organizers moved the test set to : http://www.quest.dcs.shef.ac.uk/wmt17_files_mmt/mmt_task1_test2016.tar.gz
2017-10-16T20:19:24
pytorch/text
151
pytorch__text-151
[ "137", "137" ]
1d5147ef3484b3217824aa4bd53c3f85fc1add16
diff --git a/torchtext/data/iterator.py b/torchtext/data/iterator.py --- a/torchtext/data/iterator.py +++ b/torchtext/data/iterator.py @@ -224,7 +224,7 @@ def __init__(self, dataset, batch_size, bptt_len, **kwargs): super(BPTTIterator, self).__init__(dataset, batch_size, **kwargs) def __len__(self): - return math.ceil(len(self.dataset[0].text) / + return math.ceil((len(self.dataset[0].text) - 1) / (self.batch_size * self.bptt_len)) def __iter__(self): @@ -240,7 +240,7 @@ def __iter__(self): ('text', TEXT), ('target', TEXT)]) while True: for i in range(0, len(self) * self.bptt_len, self.bptt_len): - seq_len = min(self.bptt_len, len(data) - 1 - i) + seq_len = min(self.bptt_len, len(data) - i - 1) yield Batch.fromvars( dataset, self.batch_size, train=self.train, text=data[i:i + seq_len],
BPTTIterator: Result of Slicing is an empty tensor I can't iterate through all the batches in the iterator returned by BPTTITerator. For example, this will give an error: batches = [batch for batch in train_iter] On the last batch, I'll get error: Result of Slicing is an empty tensor How should I fix it? Thanks! BPTTIterator: Result of Slicing is an empty tensor I can't iterate through all the batches in the iterator returned by BPTTITerator. For example, this will give an error: batches = [batch for batch in train_iter] On the last batch, I'll get error: Result of Slicing is an empty tensor How should I fix it? Thanks!
I can't reproduce with `datasets.WikiText2` (I had to fix some unrelated bugs in that first, though). This code works for me after said unrelated fixes (PR coming momentarily): ``` from torchtext import data, datasets TEXT = data.Field(sequential=True) train, dev, test = datasets.WikiText2.splits(TEXT) TEXT.build_vocab(train, dev, test) train_iter, dev_iter, test_iter = data.BPTTIterator.splits( (train, dev, test), batch_size=20, bptt_len=35, device=-1, repeat=False) for batch in train_iter: print(batch.text.size()) ``` and prints sizes of 35 x 20 until the last batch of size 26 x 20. Can you provide a snippet that's buggy? Hi Sure! So In utils.py, we have: ` def load_ptb(ptb_path='data.zip', ptb_dir='data', bptt_len=5, batch_size=1, gpu=False, reuse=False,repeat=False, shuffle=True): print ("Loading Data") if (not reuse) or (not os.path.exists(ptb_dir)): f = zipfile.ZipFile(ptb_path, 'r') f.extractall('.') f.close() DEV = 0 if gpu else -1 text_field = data.Field(lower=True, batch_first=True) train = datasets.LanguageModelingDataset(os.path.join(ptb_dir, 'train.txt'), text_field, newline_eos=False) val = datasets.LanguageModelingDataset(os.path.join(ptb_dir, 'valid.txt'), text_field, newline_eos=False) test = datasets.LanguageModelingDataset(os.path.join(ptb_dir, 'test.txt'), text_field, newline_eos=False) train_iter, val_iter, test_iter = data.BPTTIterator.splits((train, val, test), batch_size=batch_size, bptt_len=bptt_len, device=DEV, repeat=repeat, shuffle=shuffle) text_field.build_vocab(train, vectors=torchtext.vocab.GloVe(name='6B', dim=50)) return train_iter, val_iter, test_iter, text_field ` And then in main.py function Even `batches = [batch for batch in train_iter]` doesn't work Thanks so much! I can't reproduce with `datasets.WikiText2` (I had to fix some unrelated bugs in that first, though). This code works for me after said unrelated fixes (PR coming momentarily): ``` from torchtext import data, datasets TEXT = data.Field(sequential=True) train, dev, test = datasets.WikiText2.splits(TEXT) TEXT.build_vocab(train, dev, test) train_iter, dev_iter, test_iter = data.BPTTIterator.splits( (train, dev, test), batch_size=20, bptt_len=35, device=-1, repeat=False) for batch in train_iter: print(batch.text.size()) ``` and prints sizes of 35 x 20 until the last batch of size 26 x 20. Can you provide a snippet that's buggy? Hi Sure! So In utils.py, we have: ` def load_ptb(ptb_path='data.zip', ptb_dir='data', bptt_len=5, batch_size=1, gpu=False, reuse=False,repeat=False, shuffle=True): print ("Loading Data") if (not reuse) or (not os.path.exists(ptb_dir)): f = zipfile.ZipFile(ptb_path, 'r') f.extractall('.') f.close() DEV = 0 if gpu else -1 text_field = data.Field(lower=True, batch_first=True) train = datasets.LanguageModelingDataset(os.path.join(ptb_dir, 'train.txt'), text_field, newline_eos=False) val = datasets.LanguageModelingDataset(os.path.join(ptb_dir, 'valid.txt'), text_field, newline_eos=False) test = datasets.LanguageModelingDataset(os.path.join(ptb_dir, 'test.txt'), text_field, newline_eos=False) train_iter, val_iter, test_iter = data.BPTTIterator.splits((train, val, test), batch_size=batch_size, bptt_len=bptt_len, device=DEV, repeat=repeat, shuffle=shuffle) text_field.build_vocab(train, vectors=torchtext.vocab.GloVe(name='6B', dim=50)) return train_iter, val_iter, test_iter, text_field ` And then in main.py function Even `batches = [batch for batch in train_iter]` doesn't work Thanks so much!
2017-10-18T01:37:40
pytorch/text
153
pytorch__text-153
[ "152" ]
51bba2fdef201106ee9600a19348a58fe9a5db46
diff --git a/torchtext/vocab.py b/torchtext/vocab.py --- a/torchtext/vocab.py +++ b/torchtext/vocab.py @@ -114,7 +114,9 @@ def load_vectors(self, vectors): if not isinstance(vectors, list): vectors = [vectors] for idx, vector in enumerate(vectors): - if isinstance(vector, six.text_type): + if six.PY2 and isinstance(vector, str): + vector = six.text_type(vector) + if isinstance(vector, six.string_types): # Convert the string pretrained vector identifier # to a Vectors object if vector not in pretrained_aliases:
diff --git a/test/test_vocab.py b/test/test_vocab.py --- a/test/test_vocab.py +++ b/test/test_vocab.py @@ -51,7 +51,7 @@ def test_vocab_download_fasttext_vectors(self): # to test string aliases. for i in range(3): if i == 2: - vectors = "fasttext.simple.300d" + vectors = str("fasttext.simple.300d") # must handle str on Py2 else: vectors = FastText(language='simple')
ValueError: Got input vectors of type <type 'str'>, expected str or Vectors object when I run the code, it has the error, **Traceback (most recent call last): File "test/example.py", line 16, in <module> inputs.vocab.load_vectors('glove.840B.300d') File "/Users/wangyuan/anaconda2/lib/python2.7/site-packages/torchtext/vocab.py", line 129, in load_vectors "Vectors object".format(type(vector))) ValueError: Got input vectors of type <type 'str'>, expected str or Vectors object**
2017-10-19T03:12:53
pytorch/text
155
pytorch__text-155
[ "154" ]
51bba2fdef201106ee9600a19348a58fe9a5db46
diff --git a/torchtext/data/field.py b/torchtext/data/field.py --- a/torchtext/data/field.py +++ b/torchtext/data/field.py @@ -331,7 +331,7 @@ def reverse(self, batch): print("Please install revtok.") raise if not self.batch_first: - batch.t_() + batch = batch.t() with torch.cuda.device_of(batch): batch = batch.tolist() batch = [[self.vocab.itos[ind] for ind in ex] for ex in batch] # denumericalize
ReversibleField performs in-place transpose operation I am using the recently added `ReversibleField` field. Converting padded indices into original words was always a cumbersome chore, and the newly added class greatly reduces this burden. However, I found a strange behavior of the class; when `batch_first` is `True`, it performs in-place transpose operation, which I think not intuitive. Is it an intended side effect? The following is the code for reproducing this behavior. ``` TEXT = data.ReversibleField() LABEL = data.Field(sequential=False) train, dev, test = datasets.SNLI.splits(TEXT, LABEL) TEXT.build_vocab(train, max_size=1000) LABEL.build_vocab(train) train_iter, dev_iter, test_iter = data.BucketIterator.splits((train, dev, test), batch_size=4) b = next(iter(train_iter)) b.premise.size() # torch.Size([7, 4]) TEXT.reverse(b.premise.data) b.premise.size() # torch.Size([4, 7]) ``` And it is also problematic in that calling `TEXT.reverse(b.premise.data)` repeatedly does not give consistent results. For example, when I call it for the first time, it works nicely: ``` ['A girl jumps off of a diving board into a pool.', 'The mountain biker is UNK the hill on a UNK trail.', 'A man is standing next to a large black UNK statue.', 'A young gentleman is pointing to a sign on a building.'] ``` However if I call it again, since `b.premise.data` is transposed, it emits wrong results. ``` ['A The A A', 'girl mountain man young', 'jumps biker is gentleman', 'off is standing is', 'of UNK next pointing', 'a the to to', 'diving hill a a', 'board on large sign', 'into a black on', 'a UNK UNK a', 'pool trail statue building', '....'] ```
Good catch! You're right, that should definitely be out-of-place.
2017-10-20T02:42:06
pytorch/text
182
pytorch__text-182
[ "137", "137" ]
23ced46fcb310a2dd1a0cc065c326141f65e0b5c
diff --git a/torchtext/data/iterator.py b/torchtext/data/iterator.py --- a/torchtext/data/iterator.py +++ b/torchtext/data/iterator.py @@ -224,8 +224,8 @@ def __init__(self, dataset, batch_size, bptt_len, **kwargs): super(BPTTIterator, self).__init__(dataset, batch_size, **kwargs) def __len__(self): - return math.ceil((len(self.dataset[0].text) - 1) / - (self.batch_size * self.bptt_len)) + return math.ceil((len(self.dataset[0].text) / self.batch_size - 1) / + self.bptt_len) def __iter__(self): text = self.dataset[0].text
BPTTIterator: Result of Slicing is an empty tensor I can't iterate through all the batches in the iterator returned by BPTTITerator. For example, this will give an error: batches = [batch for batch in train_iter] On the last batch, I'll get error: Result of Slicing is an empty tensor How should I fix it? Thanks! BPTTIterator: Result of Slicing is an empty tensor I can't iterate through all the batches in the iterator returned by BPTTITerator. For example, this will give an error: batches = [batch for batch in train_iter] On the last batch, I'll get error: Result of Slicing is an empty tensor How should I fix it? Thanks!
I can't reproduce with `datasets.WikiText2` (I had to fix some unrelated bugs in that first, though). This code works for me after said unrelated fixes (PR coming momentarily): ``` from torchtext import data, datasets TEXT = data.Field(sequential=True) train, dev, test = datasets.WikiText2.splits(TEXT) TEXT.build_vocab(train, dev, test) train_iter, dev_iter, test_iter = data.BPTTIterator.splits( (train, dev, test), batch_size=20, bptt_len=35, device=-1, repeat=False) for batch in train_iter: print(batch.text.size()) ``` and prints sizes of 35 x 20 until the last batch of size 26 x 20. Can you provide a snippet that's buggy? Hi Sure! So In utils.py, we have: ` def load_ptb(ptb_path='data.zip', ptb_dir='data', bptt_len=5, batch_size=1, gpu=False, reuse=False,repeat=False, shuffle=True): print ("Loading Data") if (not reuse) or (not os.path.exists(ptb_dir)): f = zipfile.ZipFile(ptb_path, 'r') f.extractall('.') f.close() DEV = 0 if gpu else -1 text_field = data.Field(lower=True, batch_first=True) train = datasets.LanguageModelingDataset(os.path.join(ptb_dir, 'train.txt'), text_field, newline_eos=False) val = datasets.LanguageModelingDataset(os.path.join(ptb_dir, 'valid.txt'), text_field, newline_eos=False) test = datasets.LanguageModelingDataset(os.path.join(ptb_dir, 'test.txt'), text_field, newline_eos=False) train_iter, val_iter, test_iter = data.BPTTIterator.splits((train, val, test), batch_size=batch_size, bptt_len=bptt_len, device=DEV, repeat=repeat, shuffle=shuffle) text_field.build_vocab(train, vectors=torchtext.vocab.GloVe(name='6B', dim=50)) return train_iter, val_iter, test_iter, text_field ` And then in main.py function Even `batches = [batch for batch in train_iter]` doesn't work Thanks so much! I think I had an off-by-one error. I can't reproduce with `datasets.WikiText2` (I had to fix some unrelated bugs in that first, though). This code works for me after said unrelated fixes (PR coming momentarily): ``` from torchtext import data, datasets TEXT = data.Field(sequential=True) train, dev, test = datasets.WikiText2.splits(TEXT) TEXT.build_vocab(train, dev, test) train_iter, dev_iter, test_iter = data.BPTTIterator.splits( (train, dev, test), batch_size=20, bptt_len=35, device=-1, repeat=False) for batch in train_iter: print(batch.text.size()) ``` and prints sizes of 35 x 20 until the last batch of size 26 x 20. Can you provide a snippet that's buggy? Hi Sure! So In utils.py, we have: ` def load_ptb(ptb_path='data.zip', ptb_dir='data', bptt_len=5, batch_size=1, gpu=False, reuse=False,repeat=False, shuffle=True): print ("Loading Data") if (not reuse) or (not os.path.exists(ptb_dir)): f = zipfile.ZipFile(ptb_path, 'r') f.extractall('.') f.close() DEV = 0 if gpu else -1 text_field = data.Field(lower=True, batch_first=True) train = datasets.LanguageModelingDataset(os.path.join(ptb_dir, 'train.txt'), text_field, newline_eos=False) val = datasets.LanguageModelingDataset(os.path.join(ptb_dir, 'valid.txt'), text_field, newline_eos=False) test = datasets.LanguageModelingDataset(os.path.join(ptb_dir, 'test.txt'), text_field, newline_eos=False) train_iter, val_iter, test_iter = data.BPTTIterator.splits((train, val, test), batch_size=batch_size, bptt_len=bptt_len, device=DEV, repeat=repeat, shuffle=shuffle) text_field.build_vocab(train, vectors=torchtext.vocab.GloVe(name='6B', dim=50)) return train_iter, val_iter, test_iter, text_field ` And then in main.py function Even `batches = [batch for batch in train_iter]` doesn't work Thanks so much! I think I had an off-by-one error.
2017-11-20T12:36:49
pytorch/text
192
pytorch__text-192
[ "171" ]
4980e44224c96a0d2de73e5d706989dd8d25ba15
diff --git a/torchtext/data/iterator.py b/torchtext/data/iterator.py --- a/torchtext/data/iterator.py +++ b/torchtext/data/iterator.py @@ -72,7 +72,7 @@ class Iterator(object): """ def __init__(self, dataset, batch_size, sort_key=None, device=None, - batch_size_fn=lambda new, count, sofar: count, train=True, + batch_size_fn=None, train=True, repeat=None, shuffle=None, sort=None, sort_within_batch=None): self.batch_size, self.train, self.dataset = batch_size, train, dataset @@ -155,6 +155,8 @@ def epoch(self): return self.iterations / len(self) def __len__(self): + if self.batch_size_fn is not None: + raise NotImplementedError return math.ceil(len(self.dataset) / self.batch_size) def __iter__(self): @@ -266,8 +268,11 @@ def create_batches(self): random_shuffler=self.random_shuffler) -def batch(data, batch_size, batch_size_fn=lambda new, count, sofar: count): +def batch(data, batch_size, batch_size_fn=None): """Yield elements from data in chunks of batch_size.""" + if batch_size_fn is None: + def batch_size_fn(new, count, sofar): + return count minibatch, size_so_far = [], 0 for ex in data: minibatch.append(ex)
len of iterator incorrect for dynamic batching The `__len__` method of `Iterator` (defined [here](https://github.com/pytorch/text/blob/master/torchtext/data/iterator.py#L157)) returns a wrong result for dynamic batching (i.e. if [batch_size_fn](https://github.com/pytorch/text/blob/master/torchtext/data/iterator.py#L50) is not None). For example if we set `batch_size_fn` to ``` lambda x, n, b: b + len(x.text) ``` there might be more or fewer batches in the dataset than the `__len__` outputs.
2017-12-22T07:17:42
pytorch/text
193
pytorch__text-193
[ "184" ]
2180312e9e2d73f20dfc1d9e39f90d336eb38045
diff --git a/torchtext/vocab.py b/torchtext/vocab.py --- a/torchtext/vocab.py +++ b/torchtext/vocab.py @@ -45,7 +45,8 @@ def __init__(self, counter, max_size=None, min_freq=1, specials=['<pad>'], or custom pretrained vectors (see Vocab.load_vectors); or a list of aforementioned vectors """ - self.freqs = counter.copy() + self.freqs = counter + counter = counter.copy() min_freq = max(min_freq, 1) counter.update(specials)
Side effect in Vocab __init__ The constructor of Vocab accumulates input data in its `specials` argument/variable and pollute the input argument `counter`. The constructed object is also wrong because of this side effect. Please find reproducible example below: ``` >>> c1 = Counter([1]) >>> v1 = Vocab(c1) >>> print(c1) Counter({1: 1, u'<pad>': 0}) >>> print(v1.stoi) defaultdict(<function _default_unk_index at 0x10b4aa758>, {1: 1, u'<pad>': 0}) >>> c2 = Counter([2]) >>> print(c2) Counter({2: 1}) >>> v2 = Vocab(c2) >>> print(c2) Counter({2: 1, 1: 0, u'<pad>': 0}) # c2 is changed after passing as argument >>> print(v2.stoi) defaultdict(<function _default_unk_index at 0x10b4aa758>, {1: 1, u'<pad>': 0, 2: 2}) # resulting vocabulary is wrong ```
2017-12-22T07:50:50
pytorch/text
208
pytorch__text-208
[ "206" ]
c8419a5f0516496eb308ee75c740357bf021d916
diff --git a/torchtext/datasets/translation.py b/torchtext/datasets/translation.py --- a/torchtext/datasets/translation.py +++ b/torchtext/datasets/translation.py @@ -40,12 +40,13 @@ def __init__(self, path, exts, fields, **kwargs): super(TranslationDataset, self).__init__(examples, fields, **kwargs) @classmethod - def splits(cls, exts, fields, root='.data', + def splits(cls, exts, fields, path=None, root='.data', train='train', validation='val', test='test', **kwargs): """Create dataset objects for splits of a TranslationDataset. Arguments: - + path (str): Common prefix of the splits' file paths, or None to use + the result of cls.download(root). root: Root dataset storage directory. Default is '.data'. exts: A tuple containing the extension to path for each language. fields: A tuple containing the fields that will be used for data @@ -56,7 +57,8 @@ def splits(cls, exts, fields, root='.data', Remaining keyword arguments: Passed to the splits method of Dataset. """ - path = cls.download(root) + if path is None: + path = cls.download(root) train_data = None if train is None else cls( os.path.join(path, train), exts, fields, **kwargs)
text/test/translation.py fails for custom paths `text/test/translation.py` currently fails on the last section: ```python train, val = datasets.TranslationDataset.splits( path='.data/multi30k/', train='train', validation='val', exts=('.de', '.en'), fields=(DE, EN)) ``` because `splits` expects TranslationDataset.name to be defined, but it isn't. Possible fix: add `name = ''` to `TranslationDataset`
2018-01-21T06:50:24
pytorch/text
217
pytorch__text-217
[ "215" ]
690d3d0cdef20b96bdc67193911eb48eec5064c7
diff --git a/torchtext/data/dataset.py b/torchtext/data/dataset.py --- a/torchtext/data/dataset.py +++ b/torchtext/data/dataset.py @@ -2,6 +2,7 @@ import os import zipfile import tarfile +from functools import partial import torch.utils.data @@ -141,19 +142,22 @@ def __init__(self, path, format, fields, skip_header=False, **kwargs): path (str): Path to the data file. format (str): The format of the data file. One of "CSV", "TSV", or "JSON" (case-insensitive). - fields (list(tuple(str, Field)) or dict[str: tuple(str, Field)]: For CSV and - TSV formats, list of tuples of (name, field). The list should be in - the same order as the columns in the CSV or TSV file, while tuples of - (name, None) represent columns that will be ignored. For JSON format, - dictionary whose keys are the JSON keys and whose values are tuples of - (name, field). This allows the user to rename columns from their JSON key - names and also enables selecting a subset of columns to load - (since JSON keys not present in the input dictionary are ignored). + fields (list(tuple(str, Field)) or dict[str: tuple(str, Field)]: + If using a list, the format must be CSV or TSV, and the values of the list + should be tuples of (name, field). + The fields should be in the same order as the columns in the CSV or TSV + file, while tuples of (name, None) represent columns that will be ignored. + + If using a dict, the keys should be a subset of the JSON keys or CSV/TSV + columns, and the values should be tuples of (name, field). + Keys not present in the input dictionary are ignored. + This allows the user to rename columns from their JSON/CSV/TSV key names + and also enables selecting a subset of columns to load. skip_header (bool): Whether to skip the first line of the input file. """ make_example = { 'json': Example.fromJSON, 'dict': Example.fromdict, - 'tsv': Example.fromTSV, 'csv': Example.fromCSV}[format.lower()] + 'tsv': Example.fromCSV, 'csv': Example.fromCSV}[format.lower()] with io.open(os.path.expanduser(path), encoding="utf8") as f: if format == 'csv': @@ -163,8 +167,18 @@ def __init__(self, path, format, fields, skip_header=False, **kwargs): else: reader = f + if format in ['csv', 'tsv'] and isinstance(fields, dict): + if skip_header: + raise ValueError('When using a dict to specify fields with a {} file,' + 'skip_header must be False and' + 'the file must have a header.'.format(format)) + header = next(reader) + field_to_index = {f: header.index(f) for f in fields.keys()} + make_example = partial(make_example, field_to_index=field_to_index) + if skip_header: next(reader) + examples = [make_example(line, fields) for line in reader] if make_example in (Example.fromdict, Example.fromJSON): diff --git a/torchtext/data/example.py b/torchtext/data/example.py --- a/torchtext/data/example.py +++ b/torchtext/data/example.py @@ -29,12 +29,13 @@ def fromdict(cls, data, fields): return ex @classmethod - def fromTSV(cls, data, fields): - return cls.fromlist(data, fields) - - @classmethod - def fromCSV(cls, data, fields): - return cls.fromlist(data, fields) + def fromCSV(cls, data, fields, field_to_index=None): + if field_to_index is None: + return cls.fromlist(data, fields) + else: + assert(isinstance(fields, dict)) + data_dict = {f: data[idx] for f, idx in field_to_index.items()} + return cls.fromdict(data_dict, fields) @classmethod def fromlist(cls, data, fields):
diff --git a/test/common/torchtext_test_case.py b/test/common/torchtext_test_case.py --- a/test/common/torchtext_test_case.py +++ b/test/common/torchtext_test_case.py @@ -24,6 +24,8 @@ def setUp(self): self.test_dir, "test_numerical_features_dataset") self.test_newline_dataset_path = os.path.join(self.test_dir, "test_newline_dataset") + self.test_has_header_dataset_path = os.path.join(self.test_dir, + "test_has_header_dataset") def tearDown(self): try: diff --git a/test/data/test_dataset.py b/test/data/test_dataset.py --- a/test/data/test_dataset.py +++ b/test/data/test_dataset.py @@ -122,3 +122,32 @@ def test_input_with_newlines_in_text(self): for example in dataset: self.assert_(hasattr(example, "text")) self.assert_(hasattr(example, "label")) + + def test_csv_file_with_header(self): + example_with_header = [("text", "label"), + ("HELLO WORLD", "0"), + ("goodbye world", "1")] + + fields = { + "label": ("label", data.Field(sequential=False)), + "text": ("text", data.Field(lower=True, tokenize=lambda x: x)) + } + + for format_, delim in zip(["csv", "tsv"], [",", "\t"]): + with open(self.test_has_header_dataset_path, "wt") as f: + for line in example_with_header: + f.write("{}\n".format(delim.join(line))) + + # check that an error is raised here if a non-existent field is specified + with self.assertRaises(ValueError): + data.TabularDataset( + path=self.test_has_header_dataset_path, format=format_, + fields={"non_existent": ("label", data.Field())}) + + dataset = data.TabularDataset( + path=self.test_has_header_dataset_path, format=format_, + skip_header=False, fields=fields) + + for i, example in enumerate(dataset): + self.assertEqual(example.text, example_with_header[i + 1][0].lower()) + self.assertEqual(example.label, example_with_header[i + 1][1])
TabularDataset class with header does not match fields by name Currently, the TabularDataset class matches each feature in a csv/tsv file to its field by requiring the (name, Field) tuples passed to the fields kwarg to be in the same order as the columns csv/tsv file. I think this is counterintuitive, especially if the csv/tsv file has a header. If there is a header, I think that the user should be allowed to specify the fields similar to the json format, where they pass in a dict mapping the column name to the (name, Field) tuple. Here’s an example of what I’m thinking. ``` $ head -n 2 train.csv "text","label" "hello",0 ``` ```python >>> pos = data.TabularDataset( ... path='train.tsv', format='csv', ... fields={'labels': ('labels', data.Field()), ... 'text': ('text', data.Field())} ... ``` I think they should also be allowed to select a subset of the rows using this method, similar to the API for the json format (columns not in the keys will be ignored). This should provide a more consistent and intuitive API. If the maintainers are willing to accept this API, I would be happy to implement it and send a PR.
2018-02-04T02:18:03
pytorch/text
248
pytorch__text-248
[ "247" ]
421018d569c9b2a97f0188c074dd174249360e39
diff --git a/torchtext/data/batch.py b/torchtext/data/batch.py --- a/torchtext/data/batch.py +++ b/torchtext/data/batch.py @@ -34,6 +34,7 @@ def fromvars(cls, dataset, batch_size, train=True, **kwargs): batch.batch_size = batch_size batch.dataset = dataset batch.train = train + batch.fields = dataset.fields.keys() for k, v in kwargs.items(): setattr(batch, k, v) return batch
A batch object created by fromvars does not have "fields" attribute When making a batch object, the value of the `fields` attribute is set in its `__init__` method. However, when created with `fromvars` class method, `fields` attribute is not set since the method first creates an empty object and then add information. It should be modified to be analogous with the one created by `__init__` method. It can be simply done by adding the following after https://github.com/pytorch/text/blob/master/torchtext/data/batch.py#L36: ``` batch.fields = dataset.fields.keys() ``` This kind of object creation is found when using BPTT iterator. Without `fields` attribute, printing a batch object is not possible due to https://github.com/pytorch/text/blob/master/torchtext/data/batch.py#L49.
2018-03-16T10:12:49
pytorch/text
254
pytorch__text-254
[ "240" ]
421018d569c9b2a97f0188c074dd174249360e39
diff --git a/torchtext/data/batch.py b/torchtext/data/batch.py --- a/torchtext/data/batch.py +++ b/torchtext/data/batch.py @@ -24,7 +24,7 @@ def __init__(self, data=None, dataset=None, device=None, train=True): for (name, field) in dataset.fields.items(): if field is not None: - batch = [x.__dict__[name] for x in data] + batch = [getattr(x, name) for x in data] setattr(self, name, field.process(batch, device=device, train=train)) @classmethod
Use getattr rather than __dict__ in Batch (adds support for __slots__ in Example subclasses) This is a proposal to change [one line of code](https://github.com/pytorch/text/blob/c839a7934930819be7e240ea972e4d600966afdc/torchtext/data/batch.py#L27) in Batch.py I suggest `[x.__dict__[name] for x in data]` should become `[getattr(x, name) for x in data]` A major advantage to doing this is compatibility with `__slots__`. A class that is going to be instantiated for every data point is an ideal use-case for `__slots__`, which reduces per-instance memory overhead. It makes sense for specific projects to subclass Example using `__slots__` with the known fields of the project. If you do, the instances will have empty `__dicts__` but the slots can be accessed via `getattr`. I don't _think_ this change would break anything...
2018-03-17T18:14:22
pytorch/text
279
pytorch__text-279
[ "278" ]
a2795e5731d1b7c0298a1b5087bb8142e1c39d0b
diff --git a/torchtext/data/dataset.py b/torchtext/data/dataset.py --- a/torchtext/data/dataset.py +++ b/torchtext/data/dataset.py @@ -108,8 +108,6 @@ def split(self, split_ratio=0.7, stratified=False, strata_field='label', if not stratified: train_data, test_data, val_data = rationed_split(self.examples, train_ratio, test_ratio, val_ratio, rnd) - return tuple(Dataset(d, self.fields) - for d in (train_data, val_data, test_data) if d) else: if strata_field not in self.fields: raise ValueError("Invalid field name for strata_field {}" @@ -125,8 +123,14 @@ def split(self, split_ratio=0.7, stratified=False, strata_field='label', test_data += group_test val_data += group_val - return tuple(Dataset(d, self.fields) - for d in (train_data, val_data, test_data) if d) + splits = tuple(Dataset(d, self.fields) + for d in (train_data, val_data, test_data) if d) + + # In case the parent sort key isn't none + if self.sort_key: + for subset in splits: + subset.sort_key = self.sort_key + return splits def __getitem__(self, i): return self.examples[i]
dataset.sort_key not retained after dataset.split() Hi I was trying out the new `split()` functionality to split a test set into test and validation set. When the `BucketIterator` is being set up from a newly split dataset the sorting fails because `dataset.sort_key` is None. Looking at the `split()` function I see that a new instance of type `Dataset` is created in which `sort_key` is None by default: ``` def split(): ... if not stratified: train_data, test_data, val_data = rationed_split(self.examples, train_ratio, test_ratio, val_ratio, rnd) return tuple(Dataset(d, self.fields) for d in (train_data, val_data, test_data) if d) ``` I guess one way would be to explicitly copy the `sort_key` into the new instance. A more generic way could be to make a copy of the current instance and replace only the `examples` attribute but I'm not sure if that is really needed. Thanks!
Correct, thanks for spotting this. I'll issue a fix soon.
2018-04-11T16:54:14
pytorch/text
280
pytorch__text-280
[ "277" ]
a2795e5731d1b7c0298a1b5087bb8142e1c39d0b
diff --git a/torchtext/datasets/imdb.py b/torchtext/datasets/imdb.py --- a/torchtext/datasets/imdb.py +++ b/torchtext/datasets/imdb.py @@ -1,5 +1,6 @@ import os import glob +import io from .. import data @@ -29,7 +30,7 @@ def __init__(self, path, text_field, label_field, **kwargs): for label in ['pos', 'neg']: for fname in glob.iglob(os.path.join(path, label, '*.txt')): - with open(fname, 'r', encoding="utf-8") as f: + with io.open(fname, 'r', encoding="utf-8") as f: text = f.readline() examples.append(data.Example.fromlist([text, label], fields))
TypeError in Python 2.7 https://github.com/pytorch/text/blob/a2795e5731d1b7c0298a1b5087bb8142e1c39d0b/torchtext/datasets/imdb.py#L32 In python 2.7, it will report that `TypeError: 'encoding' is an invalid keyword argument for this function`. I replace `open` with `io.open` to fix it.
2018-04-11T16:59:57
pytorch/text
301
pytorch__text-301
[ "300" ]
4ecb8d8b04b2f9ac3295e96f53409b98cd706c0a
diff --git a/torchtext/vocab.py b/torchtext/vocab.py --- a/torchtext/vocab.py +++ b/torchtext/vocab.py @@ -327,6 +327,8 @@ def cache(self, name, cache, url=None): self.vectors = torch.Tensor(vectors).view(-1, dim) self.dim = dim logger.info('Saving vectors to {}'.format(path_pt)) + if not os.path.exists(cache): + os.makedirs(cache) torch.save((self.itos, self.stoi, self.vectors, self.dim), path_pt) else: logger.info('Loading vectors from {}'.format(path_pt))
Automatically create cache directories for pretrained embeddings When you try to load your own pretrained embeddings - using eg. ```torchtext.vocab.Vectors``` - if the ```.vector_cache``` directory/the directory in the args doesn't exist, torch's save routine throws an exception. Whilst in theory it is possible to just create the directory yourself, this is annoying on servers with issues with cuda and relative paths. It seems to be pretty simple to just check whether the cache directory exists or not, though, and create it if it doesn't.
2018-04-26T23:51:44
pytorch/text
308
pytorch__text-308
[ "275" ]
2635361dc786274f2d5c69724368b5a48c746b1e
diff --git a/torchtext/vocab.py b/torchtext/vocab.py --- a/torchtext/vocab.py +++ b/torchtext/vocab.py @@ -239,7 +239,7 @@ def __getitem__(self, token): if token in self.stoi: return self.vectors[self.stoi[token]] else: - return self.unk_init(torch.Tensor(1, self.dim)) + return self.unk_init(torch.Tensor(self.dim)) def cache(self, name, cache, url=None): if os.path.isfile(name):
diff --git a/test/data/test_field.py b/test/data/test_field.py --- a/test/data/test_field.py +++ b/test/data/test_field.py @@ -762,7 +762,7 @@ def test_build_vocab(self): [['o', 'n', 'e'], ['l', 'a', 's', 't'], ['s', 'e', 'n', 't']]] field.build_vocab(sources, vectors='glove.6B.50d', - unk_init=init.xavier_normal, + unk_init=init.normal_, vectors_cache=".vector_cache")
wordvec of unk token https://github.com/pytorch/text/blob/master/torchtext/vocab.py#L242 When the word is in the dictionary, the returned is a one-dim vector, while unk vector is a two-dim vector. I assume this is not expected, right?
@jekbradbury What would be preferred out of those two? I could make a PR for this. Probably the one-dim vector. Does nothing else in the codebase currently rely on this `__getitem__` method? @jekbradbury I've been searching through the codebase, but I wasn't able to find anything. It seems that after the vectors are finally loaded, it's up to user's model to deal with it. I'll see whether something breaks when I change this.
2018-05-04T11:29:53
pytorch/text
361
pytorch__text-361
[ "306" ]
dc97900ebb40ccbbc1b828043255c2e8d016e9b7
diff --git a/torchtext/data/utils.py b/torchtext/data/utils.py --- a/torchtext/data/utils.py +++ b/torchtext/data/utils.py @@ -21,16 +21,22 @@ def get_tokenizer(tokenizer): raise elif tokenizer == "moses": try: - from nltk.tokenize.moses import MosesTokenizer + from sacremoses import MosesTokenizer moses_tokenizer = MosesTokenizer() return moses_tokenizer.tokenize except ImportError: - print("Please install NLTK. " - "See the docs at http://nltk.org for more information.") + print("Please install SacreMoses. " + "See the docs at https://github.com/alvations/sacremoses " + "for more information.") raise - except LookupError: - print("Please install the necessary NLTK corpora. " - "See the docs at http://nltk.org for more information.") + elif tokenizer == "toktok": + try: + from nltk.tokenize.toktok import ToktokTokenizer + toktok = ToktokTokenizer() + return toktok.tokenize + except ImportError: + print("Please install NLTK. " + "See the docs at https://nltk.org for more information.") raise elif tokenizer == 'revtok': try:
diff --git a/test/data/test_utils.py b/test/data/test_utils.py --- a/test/data/test_utils.py +++ b/test/data/test_utils.py @@ -16,7 +16,7 @@ def test_get_tokenizer(self): "A", "string", ",", "particularly", "one", "with", "slightly", "complex", "punctuation", "."] - # Test Moses option. Test strings taken from NLTK doctests. + # Test Moses option. # Note that internally, MosesTokenizer converts to unicode if applicable moses_tokenizer = data.get_tokenizer("moses") assert moses_tokenizer(test_str) == [ @@ -26,6 +26,13 @@ def test_get_tokenizer(self): # Nonbreaking prefixes should tokenize the final period. assert moses_tokenizer(six.text_type("abc def.")) == ["abc", "def", "."] + # Test Toktok option. Test strings taken from NLTK doctests. + # Note that internally, MosesTokenizer converts to unicode if applicable + toktok_tokenizer = data.get_tokenizer("toktok") + assert toktok_tokenizer(test_str) == [ + "A", "string", ",", "particularly", "one", "with", "slightly", + "complex", "punctuation", "."] + # Test that errors are raised for invalid input arguments. with self.assertRaises(ValueError): data.get_tokenizer(1)
MosesTokenizer has been moved out of NLTK due to licensing issues @jekbradbury great work here! Due to https://github.com/nltk/nltk/issues/2000, we had to remove MosesTokenizer out of NLTK but now it's hosted on https://github.com/alvations/sacremoses ``` pip install sacremoses ``` The silver lining is that the package comes with the data needed for tokenization so there's no need to keep the `nltk_data` directory =) ---- I would propose adding `sacremoses` on top of `nltk` because NLTK has another port of a nice tokenizer (by @jonsafari) that people overlook, https://github.com/nltk/nltk/blob/develop/nltk/tokenize/toktok.py (I think it's fast too)
I'm not sure which branch is the dev branch to add tokenizers, so I'll rely on the github search: `text/torchtext/data/utils.py` ```python elif tokenizer == "moses": try: from sacremoses import MosesTokenizer moses_tokenizer = MosesTokenizer() return moses_tokenizer.tokenize except ImportError: print("Please install SacreMoses. " "See the docs at https://github.com/alvations/sacremoses for more information.") raise elif tokenizer == "toktok": try: from nltk.tokenize.toktok import ToktokTokenizer toktok = ToktokTokenizer() return toktok.tokenize except ImportError: print("Please install NLTK. " "See the docs at https://nltk.org for more information.") raise ``` Hope it helps! @alvations Thanks for the repo! We're coming up on the same problem: https://github.com/PetrochukM/PyTorch-NLP I'll update it to SacreMoses.
2018-08-07T06:11:03
pytorch/text
377
pytorch__text-377
[ "312" ]
3bbe8b07f6ff3705bde9f9564214d5b206f042b9
diff --git a/torchtext/datasets/translation.py b/torchtext/datasets/translation.py --- a/torchtext/datasets/translation.py +++ b/torchtext/datasets/translation.py @@ -97,8 +97,9 @@ def splits(cls, exts, fields, root='.data', Remaining keyword arguments: Passed to the splits method of Dataset. """ + path = os.path.join('data', cls.name) return super(Multi30k, cls).splits( - exts, fields, root, train, validation, test, **kwargs) + exts, fields, path, root, train, validation, test, **kwargs) class IWSLT(TranslationDataset): @@ -205,5 +206,6 @@ def splits(cls, exts, fields, root='.data', Remaining keyword arguments: Passed to the splits method of Dataset. """ + path = os.path.join('data', cls.name) return super(WMT14, cls).splits( - exts, fields, root, train, validation, test, **kwargs) + exts, fields, path, root, train, validation, test, **kwargs)
Translation datasets not automatically downloading Code: ``` python from torchtext.data import Field from torchtext.datasets import Multi30k DE = Field(init_token='<sos>', eos_token='<eos>') EN = Field(init_token='<sos>', eos_token='<eos>') train, val, test = Multi30k.splits(exts=('.de', '.en'), fields=(DE, EN)) ``` Error: ``` --------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) <ipython-input-3-637d49b65435> in <module>() ----> 1 train, val, test = Multi30k.splits(exts=('.de', '.en'), fields=(DE, EN)) ~/miniconda3/envs/pytorch/lib/python3.6/site-packages/torchtext/datasets/translation.py in splits(cls, exts, fields, root, train, validation, test, **kwargs) 99 """ 100 return super(Multi30k, cls).splits( --> 101 exts, fields, root, train, validation, test, **kwargs) 102 103 ~/miniconda3/envs/pytorch/lib/python3.6/site-packages/torchtext/datasets/translation.py in splits(cls, exts, fields, path, root, train, validation, test, **kwargs) 62 63 train_data = None if train is None else cls( ---> 64 os.path.join(path, train), exts, fields, **kwargs) 65 val_data = None if validation is None else cls( 66 os.path.join(path, validation), exts, fields, **kwargs) ~/miniconda3/envs/pytorch/lib/python3.6/site-packages/torchtext/datasets/translation.py in __init__(self, path, exts, fields, **kwargs) 31 32 examples = [] ---> 33 with open(src_path) as src_file, open(trg_path) as trg_file: 34 for src_line, trg_line in zip(src_file, trg_file): 35 src_line, trg_line = src_line.strip(), trg_line.strip() FileNotFoundError: [Errno 2] No such file or directory: '.data/val.de' ``` It just doesn't seem to automatically download the data for both the Multi30k and WMT14 datasets. PyTorch version: 0.3.1 TorchText version 0.2.3 **EDIT** I have downgraded my TorchText to version 0.2.1 and I do not get the error, had a quick look at the commits between 0.2.1 and 0.2.3 and couldn't figure out which commit introduced the break.
I think that this got broken in #208, where the additional argument `path` was added to the `splits` method of `TranslationDataset`, but `Multi30k` and `WMT14` super calls to that method have not been updated to accommodate for the change. @jekbradbury Want to take a look? I got around this quite easily by downloading with Multi30k.download(DATAROOT) and then just using TranslationDataset.splits instead of Multi30k.splits. Pass the rootpath to the path argument instead of the root argument ``` from torchtext.datasets import TranslationDataset, Multi30k ROOT = '~/Python/DATASETS/Multi30k/' Multi30k.download(ROOT) (trnset, valset, testset) = TranslationDataset.splits( path = ROOT, exts = ['.en', '.de'], fields = [('src', srcfield), ('trg',tgtfield)], test = 'test2016' ) I use this function (after downloading) to preprocess the data and get the iterators import spacy from torchtext.data import BucketIterator, interleave_keys, Field from onmt.inputters import OrderedIterator def prep_torchtext_multi30k( dataroot = '~/Python/DATASETS/Multi30k/', maxwords = 12000, bsize =32, langs = ['de','en'], exts = ['.en','.de'], ): # modifies dataset loader from https://github.com/A-Jacobson/minimal-nmt try: de, en = [ load_multi30k_torchtext.nlp.get(lang) for lang in langs] except: de, en = [ spacy.load(lang, disable=['tagger', 'parser', 'ner']) for lang in langs] prep_torchtext_multi30k.nlp = {'en':en, 'de':de} # repeatedly loading spacy models can use lots of mem def tok_src(text): return [tok.text for tok in de.tokenizer(text) if not tok.is_space] def tok_tgt(text): return [tok.text for tok in en.tokenizer(text) if not tok.is_space] SRC = Field( tokenize = tok_src, init_token='<s>', eos_token='</s>' ) TGT = Field( tokenize = tok_tgt, init_token='<s>', eos_token='</s>' ) trnset, valset, testset = TranslationDataset.splits( path = dataroot, exts = exts, fields = [('src', SRC), ('trg',TGT)], train = 'train', validation = 'val', test = 'test2016') for (nm, field) in [('src', SRC), ('trg',TGT)]: trnsubset = getattr(trnset, nm) field.build_vocab( trnsubset, max_size = maxwords) # ONMT's OrderedIterator --> subclasses BucketIterator but better at packing batches together. # also want to use torchtext's interleave_keys -> minimizes padding on both src and tgt sides trniter, valiter, tstiter = OrderedIterator.splits( datasets = [trnset, valset, testset], batch_size = bsize, sort_key = lambda ex: interleave_keys(len(ex.src), len(ex.trg)), device='cuda' ) return (trnset, valset, testset), (trniter, valiter, tstiter), (SRC.vocab, TGT.vocab) ``` This problem breaks a functionality of part of library, it's about 3 months old and (correct me if I am wrong) all it takes to fix this is to add `path` argument to both `splits()` and `super(Multi30k, cls).splits()`. How is this issue not fixed yet (or why there isn't even a PR)? If no one else wants to, I can submit a PR.
2018-09-05T18:42:55
pytorch/text
385
pytorch__text-385
[ "384" ]
d2eccb76953c649fd535fb758e38dd23184d58e3
diff --git a/torchtext/datasets/translation.py b/torchtext/datasets/translation.py --- a/torchtext/datasets/translation.py +++ b/torchtext/datasets/translation.py @@ -97,7 +97,9 @@ def splits(cls, exts, fields, root='.data', Remaining keyword arguments: Passed to the splits method of Dataset. """ - path = os.path.join('data', cls.name) + expected_folder = os.path.join(root, cls.name) + path = expected_folder if os.path.exists(expected_folder) else None + return super(Multi30k, cls).splits( exts, fields, path, root, train, validation, test, **kwargs) @@ -206,6 +208,8 @@ def splits(cls, exts, fields, root='.data', Remaining keyword arguments: Passed to the splits method of Dataset. """ - path = os.path.join('data', cls.name) + expected_folder = os.path.join(root, cls.name) + path = expected_folder if os.path.exists(expected_folder) else None + return super(WMT14, cls).splits( exts, fields, path, root, train, validation, test, **kwargs)
diff --git a/test/translation.py b/test/translation.py --- a/test/translation.py +++ b/test/translation.py @@ -78,7 +78,7 @@ def tokenize_en(text): train, val = datasets.TranslationDataset.splits( path='.data/multi30k/', train='train', - validation='val', exts=('.de', '.en'), + validation='val', test=None, exts=('.de', '.en'), fields=(DE, EN)) print(train.fields)
Translation splits error when not downloading dataset first Thanks @AngusMonroe for finding this! The problem is that the absence of dataset is not addressed when creating splits. Minimal example: ``` from torchtext.datasets import Multi30k from torchtext.data import Field EN = Field() DE = Field() ds = Multi30k.splits(('.de','.en'),[('de',DE),('en',EN)],'data/multi30k') ```
I am currently busy and can't work on it (possibly for a few days) so if anyone wants to submit PR, go for it. Otherwise, I will take a look at it as soon as possible.
2018-09-17T10:08:06
pytorch/text
399
pytorch__text-399
[ "398" ]
8a2fb6d19c7ffa59f84bde098729b48610ce32e6
diff --git a/torchtext/vocab.py b/torchtext/vocab.py --- a/torchtext/vocab.py +++ b/torchtext/vocab.py @@ -199,7 +199,7 @@ def __init__(self, counter, max_size=None, specials=['<pad>'], self.stoi = defaultdict(_default_unk_index) self.stoi.update({tok: i for i, tok in enumerate(specials)}) - self.itos = specials + self.itos = specials.copy() self.segment = revtok.SubwordSegmenter(counter, max_size) @@ -210,6 +210,8 @@ def __init__(self, counter, max_size=None, specials=['<pad>'], key=lambda tup: (len(tup[0]) != 1, -tup[1], tup[0])) for tok, _ in toks: + if len(self.itos) == max_size: + break self.itos.append(tok) self.stoi[tok] = len(self.itos) - 1
SubwordVocab's stoi and itos change if it is called more than once If `SubwordVocab` is called more than once , `SubwordVocab.stoi` and `SubwordVocab.itos` will be strange except for the first one. Example code: ```pythonn from torchtext.vocab import SubwordVocab from collections import Counter counter = Counter("torch torch test".split()) v1 = SubwordVocab(counter, max_size=10) print(v1.itos, v1.stoi) v2 = SubwordVocab(counter, max_size=10) print(v2.itos, v2.stoi) ``` Output: ```python # v1 # stoi and itos are correct enumerating ngrams: 100%|██████████| 2/2 [00:00<00:00, 4064.25it/s] building subword vocab: 100%|██████████| 3/3 [00:00<00:00, 12409.18it/s]For faster subwords, please install Julia 0.6, pyjulia, and Revtok.jl. Falling back to Python implementation... ['<pad>', 't', 'c', 'e', 'h', 'o', 'r', 's', 'torch', 'test', 'est'] defaultdict(<function _default_unk_index at 0x1203dd158>, {'<pad>': 0, 't': 1, 'c': 2, 'e': 3, 'h': 4, 'o': 5, 'r': 6, 's': 7, 'torch': 8, 'test': 9, 'est': 10}) # v2 # stoi and itos are incorrect. several indeces are skipped. enumerating ngrams: 100%|██████████| 2/2 [00:00<00:00, 4064.25it/s] building subword vocab: 100%|██████████| 3/3 [00:00<00:00, 12409.18it/s]For faster subwords, please install Julia 0.6, pyjulia, and Revtok.jl. Falling back to Python implementation... ['<pad>', 't', 'c', 'e', 'h', 'o', 'r', 's', 'torch', 'test', 'est', 't', 'c', 'e', 'h', 'o', 'r', 's', 'torch', 'test', 'est'] defaultdict(<function _default_unk_index at 0x1203dd158>, {'<pad>': 0, 't': 11, 'c': 12, 'e': 13, 'h': 14, 'o': 15, 'r': 16, 's': 17, 'torch': 18, 'test': 19, 'est': 20}) ``` This is because `specials` is updated inside `SubwordVocab__init__` due to call by reference.
2018-09-21T12:50:59
pytorch/text
403
pytorch__text-403
[ "372" ]
b18248ef4244846f3d9c6b02ac65afe463eff8f3
diff --git a/torchtext/data/field.py b/torchtext/data/field.py --- a/torchtext/data/field.py +++ b/torchtext/data/field.py @@ -644,6 +644,7 @@ def build_vocab(self, *args, **kwargs): self.nesting_field.build_vocab(*flattened, **kwargs) super(NestedField, self).build_vocab() self.vocab.extend(self.nesting_field.vocab) + self.vocab.freqs = self.nesting_field.vocab.freqs.copy() if old_vectors is not None: self.vocab.load_vectors(old_vectors, unk_init=old_unk_init, cache=old_vectors_cache)
diff --git a/test/data/test_field.py b/test/data/test_field.py --- a/test/data/test_field.py +++ b/test/data/test_field.py @@ -514,6 +514,9 @@ def test_build_vocab_from_dataset(self): for c in expected: assert c in CHARS.vocab.stoi + expected_freqs = Counter({"a": 6, "b": 6, "c": 1}) + assert CHARS.vocab.freqs == CHARS.nesting_field.vocab.freqs == expected_freqs + def test_build_vocab_from_iterable(self): nesting_field = data.Field(unk_token="<cunk>", pad_token="<cpad>") CHARS = data.NestedField(nesting_field) @@ -527,6 +530,9 @@ def test_build_vocab_from_iterable(self): for c in expected: assert c in CHARS.vocab.stoi + expected_freqs = Counter({"a": 6, "b": 12, "c": 4}) + assert CHARS.vocab.freqs == CHARS.nesting_field.vocab.freqs == expected_freqs + def test_pad(self): nesting_field = data.Field(tokenize=list, unk_token="<cunk>", pad_token="<cpad>", init_token="<w>", eos_token="</w>")
Try to get the vocab of NestedField but only get '[]' # Here is the dataset train1.csv: "3","EBay gets into rentals","EBay plans to buy the apartment and home rental service Rent.com for \$415 million, adding to its already exhaustive breadth of offerings." test1.csv: "3","EBay gets into rentals","EBay plans to buy the apartment and home rental service Rent.com for \$415 million, adding to its already exhaustive breadth of offerings." # Here is my code** import os import torch import torchtext from torchtext import data import spacy spacy_en = spacy.load('en') def tokenizer(text):# create a tokenizer function return [tok.text for tok in spacy_en.tokenizer(text)] def sentenizer(text): return [sent.text for sent in spacy_en(text).sents] LABEL = data.Field(sequential=False, use_vocab=False) SENTENCE = data.Field(sequential=True, tokenize=sentenizer, lower=True) TEXT_NESTING = data.Field(sequential=True, tokenize=tokenizer, lower=True) TEXT_2d = data.NestedField(TEXT_NESTING) zhang2015_datafields_2d = [('Label', LABEL), (('Sentence', 'Text'), (SENTENCE, TEXT_2d))] train, test = data.TabularDataset.splits(path='data/ag_news_csv/', \ train='train1.csv', \ test='test1.csv', \ format='csv', \ fields=zhang2015_datafields_2d) print(train.fields) print(len(train)) print(vars(train[0])) TEXT_2d.build_vocab(train) print (TEXT_2d.vocab.freqs.most_common(10)) # Here is my output {'Text': <torchtext.data.field.NestedField object at 0x118871208>, 'Sentence': <torchtext.data.field.Field object at 0x1188714e0>, 'Label': <torchtext.data.field.Field object at 0x118871518>} 1 {'Sentence': ['ebay gets into rentals'], 'Text': [['ebay'], ['gets'], ['into'], ['rentals']], 'Label': '3'} []
I have the same issue for using `NestedField` to do character-level embedding. I followed the [test script](https://github.com/pytorch/text/blob/master/test/sequence_tagging.py#L69) but `CHAR.vocab.freqs` is empty.
2018-09-21T20:26:55
pytorch/text
408
pytorch__text-408
[ "289" ]
1b8ce749b746ca008114a9c87c5e53ba076e6e3f
diff --git a/torchtext/datasets/translation.py b/torchtext/datasets/translation.py --- a/torchtext/datasets/translation.py +++ b/torchtext/datasets/translation.py @@ -2,6 +2,7 @@ import xml.etree.ElementTree as ET import glob import io +import codecs from .. import data @@ -163,7 +164,7 @@ def clean(path): for f_xml in glob.iglob(os.path.join(path, '*.xml')): print(f_xml) f_txt = os.path.splitext(f_xml)[0] - with io.open(f_txt, mode='w', encoding='utf-8') as fd_txt: + with codecs.open(f_txt, mode='w', encoding='utf-8') as fd_txt: root = ET.parse(f_xml).getroot()[0] for doc in root.findall('doc'): for e in doc.findall('seg'): @@ -174,7 +175,7 @@ def clean(path): for f_orig in glob.iglob(os.path.join(path, 'train.tags*')): print(f_orig) f_txt = f_orig.replace('.tags', '') - with io.open(f_txt, mode='w', encoding='utf-8') as fd_txt, \ + with codecs.open(f_txt, mode='w', encoding='utf-8') as fd_txt, \ io.open(f_orig, mode='r', encoding='utf-8') as fd_orig: for l in fd_orig: if not any(tag in l for tag in xml_tags):
Unicode Error in Using IWSLT dataset: TypeError: write() argument 1 must be unicode, not str Hi, I'm using the IWSLT translation dataset in torchtext. However I found the following encoding errors. The code snippet is: MAX_LEN = 100 train, val, test = datasets.IWSLT.splits( exts=('.de', '.en'), fields=(SRC, TGT), filter_pred=lambda x: len(vars(x)['src']) <= MAX_LEN and len(vars(x)['trg']) <= MAX_LEN) Indeed in an third-party implementation of Transformer using pytorch: https://github.com/harvardnlp/annotated-transformer/blob/master/The%20Annotated%20Transformer.ipynb The error is: .data/iwslt/de-en/IWSLT16.TED.tst2011.de-en.en.xml Traceback (most recent call last): File "The+Annotated+Transformer.py", line 773, in <module> filter_pred=lambda x: len(vars(x)['src']) <= MAX_LEN and File "/usr/anaconda2/lib/python2.7/site-packages/torchtext/datasets/translation.py", line 140, in splits cls.clean(path) File "/usr/anaconda2/lib/python2.7/site-packages/torchtext/datasets/translation.py", line 160, in clean fd_txt.write(e.text.strip() + '\n') TypeError: write() argument 1 must be unicode, not str Would you help to check the issue? Thanks! Systems config: Ubuntu 14.04, python 2.7. Best, Fei
Can you provide the full code? Some variables are not yet defined in your snippet. Also, use code formatting ("<>" ) for better readability. I have exactly the same issue. The full code is from a tutorial, as follows: ``` # For data loading. from torchtext import data, datasets if True: import spacy spacy_de = spacy.load('de') spacy_en = spacy.load('en') def tokenize_de(text): return [tok.text for tok in spacy_de.tokenizer(text)] def tokenize_en(text): return [tok.text for tok in spacy_en.tokenizer(text)] BOS_WORD = u'<s>' EOS_WORD = u'</s>' BLANK_WORD = u"<blank>" SRC = data.Field(tokenize=tokenize_de, pad_token=BLANK_WORD) TGT = data.Field(tokenize=tokenize_en, init_token = BOS_WORD, eos_token = EOS_WORD, pad_token=BLANK_WORD) MAX_LEN = 100 train, val, test = datasets.IWSLT.splits( exts=('.de', '.en'), fields=(SRC, TGT), filter_pred=lambda x: len(vars(x)['src']) <= MAX_LEN and len(vars(x)['trg']) <= MAX_LEN) MIN_FREQ = 2 SRC.build_vocab(train.src, min_freq=MIN_FREQ) TGT.build_vocab(train.trg, min_freq=MIN_FREQ) ``` The error that results is ``` .data/iwslt/de-en/IWSLT16.TED.tst2013.de-en.en.xml --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-51-d787c2f8b289> in <module>() 24 train, val, test = datasets.IWSLT.splits( 25 exts=('.de', '.en'), fields=(SRC, TGT), ---> 26 filter_pred=lambda x: len(vars(x)['src']) <= MAX_LEN and 27 len(vars(x)['trg']) <= MAX_LEN) 28 MIN_FREQ = 2 /usr/local/lib/python2.7/dist-packages/torchtext/datasets/translation.pyc in splits(cls, exts, fields, root, train, validation, test, **kwargs) 138 139 if not os.path.exists(os.path.join(path, train) + exts[0]): --> 140 cls.clean(path) 141 142 train_data = None if train is None else cls( /usr/local/lib/python2.7/dist-packages/torchtext/datasets/translation.pyc in clean(path) 158 for doc in root.findall('doc'): 159 for e in doc.findall('seg'): --> 160 fd_txt.write(e.text.strip() + '\n') 161 162 xml_tags = ['<url', '<keywords', '<talkid', '<description', TypeError: write() argument 1 must be unicode, not str ``` same error, very simple code to trigger it: ``` from torchtext import data from torchtext import datasets inputs = data.Field(lower=True, include_lengths=True, batch_first=True) train, dev, test = datasets.IWSLT.splits(root='.data', exts=['.en', '.de'], fields=[inputs, inputs]) ``` @tkondrashov python 2.7, right?
2018-09-24T14:35:02
pytorch/text
426
pytorch__text-426
[ "131" ]
a176a42a46b852d380027c1ee5bf7b1eee5acda9
diff --git a/torchtext/datasets/translation.py b/torchtext/datasets/translation.py --- a/torchtext/datasets/translation.py +++ b/torchtext/datasets/translation.py @@ -31,7 +31,8 @@ def __init__(self, path, exts, fields, **kwargs): src_path, trg_path = tuple(os.path.expanduser(path + x) for x in exts) examples = [] - with open(src_path) as src_file, open(trg_path) as trg_file: + with io.open(src_path, mode='r', encoding='utf-8') as src_file, \ + io.open(trg_path, mode='w', encoding='utf-8') as trg_file: for src_line, trg_line in zip(src_file, trg_file): src_line, trg_line = src_line.strip(), trg_line.strip() if src_line != '' and trg_line != '':
ascii vs. utf-8 in torchtext/datasets/translation.py @nelson-liu: I incorrectly brought this up in pull #52, new issue here When trying to load splits for IWSLT (in french, german, etc...), the loading process would fail with an ascii encoding/decoding error: ``` .data/iwslt/de-en/IWSLT16.TED.dev2010.de-en.en.xml .data/iwslt/de-en/IWSLT16.TED.tst2013.de-en.de.xml Traceback (most recent call last): File "test.py", line 25, in <module> train, val, test = datasets.IWSLT.splits(exts=('.de', '.en'), fields=(DE, EN)) File "build/bdist.linux-x86_64/egg/torchtext/datasets/translation.py", line 116, in splits File "build/bdist.linux-x86_64/egg/torchtext/datasets/translation.py", line 136, in clean UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 60: ordinal not in range(128) ``` These are my library versions: ``` numpy==1.13.3 regex==2017.9.23 spacy==1.9.0 torch==0.2.0.post4 torchtext==0.2.0b0 (just cloned a few minutes before error) torchvision==0.1.9 ``` Here is the code that I was using, from test/translation.py: ``` from torchtext import data from torchtext import datasets import re import spacy import sys spacy_de = spacy.load('de') spacy_en = spacy.load('en') url = re.compile('(<url>.*</url>)') def tokenize_de(text): return [tok.text for tok in spacy_de.tokenizer(url.sub('@URL@', text))] def tokenize_en(text): return [tok.text for tok in spacy_en.tokenizer(url.sub('@URL@', text))] # Testing IWSLT DE = data.Field(tokenize=tokenize_de) EN = data.Field(tokenize=tokenize_en) train, val, test = datasets.IWSLT.splits(exts=('.de', '.en'), fields=(DE, EN)) ``` The following fixed it for me, in torchtext/datasets/translation.py. Replace opens with io.opens specifying utf-8 for python2. It's worth noting that a friend with python3 did not have this problem. ``` 127 @staticmethod 128 def clean(path): 129 for f_xml in glob.iglob(os.path.join(path, '*.xml')): 130 print(f_xml) 131 f_txt = os.path.splitext(f_xml)[0] 132 import io 133 with io.open(f_txt, mode="w", encoding="utf-8") as fd_txt: <--- INSERT 134 #with open(f_txt, 'w') as fd_txt: <--- COMMENT 135 root = ET.parse(f_xml).getroot()[0] 136 for doc in root.findall('doc'): 137 for e in doc.findall('seg'): 138 fd_txt.write(e.text.strip() + '\n') 139 xml_tags = ['<url', '<keywords', '<talkid', '<description', 140 '<reviewer', '<translator', '<title', '<speaker'] 141 for f_orig in glob.iglob(os.path.join(path, 'train.tags*')): 142 print(f_orig) 143 f_txt = f_orig.replace('.tags', '') 144 with io.open(f_txt,mode='w',encoding='utf-8') as fd_txt, io.open(f_orig,mode='r',encoding='utf=8') as fd_orig: <--- INSERT 145 #with open(f_txt, 'w') as fd_txt, open(f_orig) as fd_orig: <--- COMMENT 146 for l in fd_orig: 147 if not any(tag in l for tag in xml_tags): 148 fd_txt.write(l.strip() + '\n') ``` @jekbradbury, you were correct in pull #52 that I didn't need the middle block explicitly encoding/decoding (not seen here) since the file is already open as utf-8.
The fix commit changes several calls to open() to io.open() in torchtext/datasets/translation.py. This allows to explicitly specify utf-8 encoding when reading, which does not happen by default in python2. Same thing happened to me. ` def __init__(self, path, exts, fields, **kwargs): """Create a TranslationDataset given paths and fields. Arguments: path: Common prefix of paths to the data files for both languages. exts: A tuple containing the extension to path for each language. fields: A tuple containing the fields that will be used for data in each language. Remaining keyword arguments: Passed to the constructor of data.Dataset. """ if not isinstance(fields[0], (tuple, list)): fields = [('src', fields[0]), ('trg', fields[1])] src_path, trg_path = tuple(os.path.expanduser(path + x) for x in exts) examples = [] with open(src_path, encoding='utf-8') as src_file, open(trg_path, encoding='utf-8') as trg_file: for src_line, trg_line in zip(src_file, trg_file): src_line, trg_line = src_line.strip(), trg_line.strip() if src_line != '' and trg_line != '': examples.append(data.Example.fromlist( [src_line, trg_line], fields)) super(TranslationDataset, self).__init__(examples, fields, **kwargs) ` I changed the code in translation.py with open(src_path) as src_file, open(trg_path) as trg_file: --> with open(src_path, encoding='utf-8') as src_file, open(trg_path, encoding='utf-8') as trg_file:
2018-09-27T17:50:45
pytorch/text
450
pytorch__text-450
[ "449" ]
e3304eaedf8f7583cc27e260a8ded78ef2213b64
diff --git a/torchtext/data/field.py b/torchtext/data/field.py --- a/torchtext/data/field.py +++ b/torchtext/data/field.py @@ -692,8 +692,10 @@ class LabelField(Field): """ def __init__(self, **kwargs): - # whichever value is set for sequential and unk_token will be overwritten + # whichever value is set for sequential, unk_token, and is_target + # will be overwritten kwargs['sequential'] = False kwargs['unk_token'] = None + kwargs['is_target'] = True super(LabelField, self).__init__(**kwargs) diff --git a/torchtext/data/iterator.py b/torchtext/data/iterator.py --- a/torchtext/data/iterator.py +++ b/torchtext/data/iterator.py @@ -32,8 +32,7 @@ class Iterator(object): repeat: Whether to repeat the iterator for multiple epochs. Default: False. shuffle: Whether to shuffle examples between epochs. sort: Whether to sort examples according to self.sort_key. - Note that repeat, shuffle, and sort default to train, train, and - (not train). + Note that shuffle and sort default to train and (not train). sort_within_batch: Whether to sort (in descending order according to self.sort_key) within each batch. If None, defaults to self.sort. If self.sort is True and this is False, the batch is left in the @@ -192,8 +191,7 @@ class BPTTIterator(Iterator): repeat: Whether to repeat the iterator for multiple epochs. Default: False. shuffle: Whether to shuffle examples between epochs. sort: Whether to sort examples according to self.sort_key. - Note that repeat, shuffle, and sort default to train, train, and - (not train). + Note that shuffle and sort default to train and (not train). device (str or torch.device): A string or instance of `torch.device` specifying which device the Variables are going to be created on. If left as default, the tensors will be created on cpu. Default: None.
Setting `is_target` to True by default in `LabelField` Hi, With the addition of `is_target` in #288, it might be a good idea for `LabelField` to come with `is_target` as True by default.
Yeah, this makes sense. Will be added (if you wish to setup a PR, it would be appreciated).
2018-10-14T14:01:47
pytorch/text
458
pytorch__text-458
[ "457" ]
758d356fd76ee6102de06a4cb5e414a3164c9e42
diff --git a/torchtext/data/field.py b/torchtext/data/field.py --- a/torchtext/data/field.py +++ b/torchtext/data/field.py @@ -163,14 +163,10 @@ def __init__(self, sequential=True, use_vocab=True, init_token=None, self.pad_token = pad_token if self.sequential else None self.pad_first = pad_first self.truncate_first = truncate_first - if stop_words is not None: - try: - self.stop_words = set(stop_words) - except TypeError: - raise ValueError("Stop words must be convertible to a set") - else: - self.stop_words = stop_words - self.stop_words = stop_words + try: + self.stop_words = set(stop_words) if stop_words is not None else None + except TypeError: + raise ValueError("Stop words must be convertible to a set") self.is_target = is_target def __getstate__(self):
Field.stop_words is overwritten and is no longer a set https://github.com/pytorch/text/blob/758d356fd76ee6102de06a4cb5e414a3164c9e42/torchtext/data/field.py#L166-L173 I think this is an error and self.stop_words should not be overwritten after the condition.
2018-10-22T15:49:26
pytorch/text
663
pytorch__text-663
[ "657" ]
c04636cb8f9d5cbd15ec123e3db0a0e7e9940382
diff --git a/torchtext/datasets/text_classification.py b/torchtext/datasets/text_classification.py --- a/torchtext/datasets/text_classification.py +++ b/torchtext/datasets/text_classification.py @@ -113,7 +113,7 @@ def get_vocab(self): return self._vocab -def _setup_datasets(dataset_name, root='.data', ngrams=2, vocab=None, include_unk=False): +def _setup_datasets(dataset_name, root='.data', ngrams=1, vocab=None, include_unk=False): dataset_tar = download_from_url(URLS[dataset_name], root=root) extracted_files = extract_archive(dataset_tar)
text_classification dataset default ngrams argument does not match comments ## 🐛 Bug `_setup_datasets` for the `text_classification` datasets has the `ngrams` argument default to 2, [see](https://github.com/pytorch/text/blob/master/torchtext/datasets/text_classification.py#L116) However the comments for each of the `text_classification` datasets says that the default `ngrams` argument is 1, [see](https://github.com/pytorch/text/blob/master/torchtext/datasets/text_classification.py#L159). So the default in `_setup_datasets` should be changed. I would submit a pull request but it looks like this can be incorporated as part of adding the IMDB dataset: https://github.com/pytorch/text/pull/651
@bentrevett Please let us know if you have any feedbacks for the new datasets in `text_classification` and `language_modeling`. I will do a cherry-up for the bug in doc. @cpuhrsch @zhangguanheng66 I think they look good so far - but do they not lose functionality offered by `data.Field` and `build_vocab`? A lot of the functionality offered by the `Field` can be incorporated into the `tokenizer` argument, e.g. `init_token`, `eos_token`, `fix_length`, `lower`, but some cannot. How can I get the same functionality as `include_lengths` (necessary for packed padded sequences) for these? How can I change the default pad or unk tokens? Is this all supposed to be done in the `collate_fn` of the `DataLoader` now? It also creates a vocabulary but does not have a way to pass arguments such as `max_size` and `min_freq` to it - both of which I think are important. I don't think this can be done in the `collate_fn`. > @zhangguanheng66 I think they look good so far - but do they not lose functionality offered by `data.Field` and `build_vocab`? > > A lot of the functionality offered by the `Field` can be incorporated into the `tokenizer` argument, e.g. `init_token`, `eos_token`, `fix_length`, `lower`, but some cannot. How can I get the same functionality as `include_lengths` (necessary for packed padded sequences) for these? How can I change the default pad or unk tokens? > > Is this all supposed to be done in the `collate_fn` of the `DataLoader` now? > > It also creates a vocabulary but does not have a way to pass arguments such as `max_size` and `min_freq` to it - both of which I think are important. I don't think this can be done in the `collate_fn`. Hi @bentrevett You are right and we are still at the early stage to incorporate those functions and we need to figure out a better way to have these functionals. For example, you could write a padding function in `collate_fn`.
2019-12-05T19:16:27
pytorch/text
745
pytorch__text-745
[ "376" ]
8b58a222b54288e46566148b3c70caf14aaceb16
diff --git a/torchtext/data/iterator.py b/torchtext/data/iterator.py --- a/torchtext/data/iterator.py +++ b/torchtext/data/iterator.py @@ -3,6 +3,7 @@ import logging +import torch from .utils import RandomShuffler from .batch import Batch from .dataset import Dataset @@ -65,6 +66,12 @@ def __init__(self, dataset, batch_size, sort_key=None, device=None, + " or passing a string as an argument. This behavior will be" + " deprecated soon and currently defaults to cpu.") device = None + + if device is None: + device = torch.device('cpu') + elif isinstance(device, str): + device = torch.device(device) + self.device = device self.random_shuffler = RandomShuffler()
Use "cpu" instead of None for representing device I think using device value as `cpu` instead of `None` will make `Iterator` class compatible with PyTorch device types [1] i.e., "cpu" and "gpu". [1] https://pytorch.org/docs/stable/tensor_attributes.html
Sure, could you submit a PR for this?
2020-04-29T20:41:58
pytorch/text
1,067
pytorch__text-1067
[ "1063" ]
97e6d1d64b82ff91899b9083350951d8619e5914
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -49,6 +49,12 @@ def _export_version(version, sha): print('-- Building version ' + VERSION) +pytorch_package_version = os.getenv('PYTORCH_VERSION') + +pytorch_package_dep = 'torch' +if pytorch_package_version is not None: + pytorch_package_dep += "==" + pytorch_package_version + class clean(distutils.command.clean.clean): def run(self): @@ -82,7 +88,7 @@ def run(self): license='BSD', install_requires=[ - 'tqdm', 'requests', 'torch', 'numpy' + 'tqdm', 'requests', pytorch_package_dep, 'numpy' ], python_requires='>=3.5', classifiers=[
pip install torchtext==0.7.0 installs incompatible PyTorch 1.7.0 ## 🐛 Bug **Describe the bug** Recently, after I do `pip install torchtext==0.7.0`, import torchtext would cause segmentation fault. I found that degrading pytorch to 1.6.0 fixes this issue. **To Reproduce** Steps to reproduce the behavior: 1. `pip install torchtext==0.7.0` (assuming that pytorch is not installed yet, and this command will install the latest pytorch) 2. python -c "import torchtext" **Expected behavior** Segmentation Fault **Environment** - PyTorch Version (e.g., 1.0): 1.7.0 - OS (e.g., Linux): Linux/MacOS - Python: 3.8.3
Yup. That's expected. Since we add cpp extension in torchtext, we have to publish torchtext and pytorch together for compatibility. You should use torchtext=0.8.0 with torch=1.7.0. Any version before 0.7.0 has python only so the compatibility is not an issue. Feel free to re-open the issue if you still have questions. But, shouldn't `pip install torchtext==0.7.0` install `pytorch==1.6` then? > But, shouldn't `pip install torchtext==0.7.0` install `pytorch==1.6` then? It should but obviously it didn't. If users would like the access to the previous version, please follow the version compatibility on README file of the repo. > > But, shouldn't `pip install torchtext==0.7.0` install `pytorch==1.6` then? > > It should but obviously it didn't. If users would like the access to the previous version, please follow the version compatibility on README file of the repo. Is it possible for you to fix this such that `pip install torchtext==0.7.0` automatically installs `pytorch==1.6` ? torchtext 0.7.0 was released only **a few months ago** and lots of users are still using that due to the overhaul of code in later versions (such as the retiring of `Field` and `Batch`). Let me follow-up with @seemethere Yup looks like this is a real bug, we don't actually set a specific torch version in the setup.py https://github.com/pytorch/text/blob/v0.8.0-rc2/setup.py#L85 This will be addressed in the next release to fix the torch/torchtext version.
2020-11-03T17:49:54
pytorch/text
1,467
pytorch__text-1467
[ "1464" ]
493e37c464cf61b72ac90b35b7b5bc81e5557539
diff --git a/build_tools/setup_helpers/extension.py b/build_tools/setup_helpers/extension.py --- a/build_tools/setup_helpers/extension.py +++ b/build_tools/setup_helpers/extension.py @@ -29,7 +29,7 @@ def _get_eca(debug): if platform.system() == "Windows": eca += ['-O2'] else: - eca += ["-O3"] + eca += ["-O3", "-fvisibility=hidden"] return eca @@ -114,6 +114,8 @@ def _build_third_party(debug): '-DCMAKE_EXPORT_COMPILE_COMMANDS=ON', f'-DCMAKE_INSTALL_PREFIX={_TP_INSTALL_DIR}', f'-DCMAKE_BUILD_TYPE={config}', + '-DCMAKE_CXX_VISIBILITY_PRESET=hidden', + '-DCMAKE_POLICY_DEFAULT_CMP0063=NEW', ] + extra_args + ['..'], cwd=str(build_dir), check=True, @@ -144,8 +146,11 @@ def _build_sentence_piece(debug): extra_args = [] subprocess.run( args=['cmake', '-DSPM_ENABLE_SHARED=OFF', f'-DCMAKE_INSTALL_PREFIX={_TP_INSTALL_DIR}', + '-DCMAKE_CXX_VISIBILITY_PRESET=hidden', '-DCMAKE_CXX_FLAGS=' + _get_cxx11_abi(), + '-DCMAKE_POLICY_DEFAULT_CMP0063=NEW', f'-DCMAKE_BUILD_TYPE={config}'] + extra_args + ['..'], + cwd=str(build_dir), check=True, env=build_env,
Should hide the symbols from the third party I am integrating KenLM in torchaudio and realized that KenLM uses double-conversion like torchtext does. In torchaudio we are hiding the symbols of third party with `-fhidden` flag with compiling, but it turns out that torchtext does not do this. (and according to the conversation I had with @malfet about a year ago, PyTorch also hides the symbol of their own code, in addition to third party.) Torchtext may want to do this in case client code imports the same package compiled differently. ## References: - https://stackoverflow.com/a/22254251 - https://labjack.com/news/simple-cpp-symbol-visibility-demo ## Double conversion ``` nm torchtext/_torchtext.so| grep double_c | grep 'T __' | head -10 0000000000175a48 T __ZN17double_conversion13StrtodTrimmedENS_6VectorIKcEEi 000000000017175c T __ZN17double_conversion16PowersOfTenCache32GetCachedPowerForDecimalExponentEiPNS_5DiyFpEPi 00000000001716fc T __ZN17double_conversion16PowersOfTenCache36GetCachedPowerForBinaryExponentRangeEiiPNS_5DiyFpEPi 00000000001715bc T __ZN17double_conversion6Bignum11PlusCompareERKS0_S2_S2_ 000000000016f7cc T __ZN17double_conversion6Bignum12AssignBignumERKS0_ 000000000016f788 T __ZN17double_conversion6Bignum12AssignUInt16Et 000000000016f7a0 T __ZN17double_conversion6Bignum12AssignUInt64Ey 0000000000171188 T __ZN17double_conversion6Bignum13SubtractTimesERKS0_i 00000000001702e8 T __ZN17double_conversion6Bignum14SubtractBignumERKS0_ 000000000016ff70 T __ZN17double_conversion6Bignum15AssignHexStringENS_6VectorIKcEE ``` ## Sentencepiece ``` $ nm torchtext/_torchtext.so| grep sentencep | grep 'T __' | head -10 0000000000128718 T __ZN13sentencepiece10ModelProto12InternalSwapEPS0_ 00000000001277fc T __ZN13sentencepiece10ModelProto14_InternalParseEPKcPN6google8protobuf8internal12ParseContextE 000000000012765c T __ZN13sentencepiece10ModelProto16default_instanceEv 0000000000128334 T __ZN13sentencepiece10ModelProto21CheckTypeAndMergeFromERKN6google8protobuf11MessageLiteE 00000000001276a0 T __ZN13sentencepiece10ModelProto5ClearEv 0000000000128620 T __ZN13sentencepiece10ModelProto8CopyFromERKS0_ 0000000000127650 T __ZN13sentencepiece10ModelProto9ArenaDtorEPv 0000000000128338 T __ZN13sentencepiece10ModelProto9MergeFromERKS0_ 0000000000127168 T __ZN13sentencepiece10ModelProto9_Internal12trainer_specEPKS0_ 0000000000127178 T __ZN13sentencepiece10ModelProto9_Internal14self_test_dataEPKS0_ ```
2021-12-20T16:16:49
pytorch/text
1,525
pytorch__text-1525
[ "1523" ]
0f7f859e412fba4a31852c1a84801a182e636fde
diff --git a/torchtext/vocab/vocab_factory.py b/torchtext/vocab/vocab_factory.py --- a/torchtext/vocab/vocab_factory.py +++ b/torchtext/vocab/vocab_factory.py @@ -49,6 +49,7 @@ def vocab(ordered_dict: Dict, min_freq: int = 1, ordered_dict.pop(token, None) tokens = [] + # Save room for special tokens for token, freq in ordered_dict.items(): if freq >= min_freq: tokens.append(token) @@ -61,7 +62,7 @@ def vocab(ordered_dict: Dict, min_freq: int = 1, return Vocab(VocabPybind(tokens, None)) -def build_vocab_from_iterator(iterator: Iterable, min_freq: int = 1, specials: Optional[List[str]] = None, special_first: bool = True) -> Vocab: +def build_vocab_from_iterator(iterator: Iterable, min_freq: int = 1, specials: Optional[List[str]] = None, special_first: bool = True, max_tokens: Optional[int] = None) -> Vocab: """ Build a Vocab from an iterator. @@ -70,6 +71,7 @@ def build_vocab_from_iterator(iterator: Iterable, min_freq: int = 1, specials: O min_freq: The minimum frequency needed to include a token in the vocabulary. specials: Special symbols to add. The order of supplied tokens will be preserved. special_first: Indicates whether to insert symbols at the beginning or at the end. + max_tokens: If provided, creates the vocab from the `max_tokens - len(specials)` most frequent tokens. Returns: @@ -90,10 +92,16 @@ def build_vocab_from_iterator(iterator: Iterable, min_freq: int = 1, specials: O for tokens in iterator: counter.update(tokens) - sorted_by_freq_tuples = sorted(counter.items(), key=lambda x: x[0]) - sorted_by_freq_tuples.sort(key=lambda x: x[1], reverse=True) - ordered_dict = OrderedDict(sorted_by_freq_tuples) + specials = specials or [] + + # First sort by descending frequency, then lexicographically + sorted_by_freq_tuples = sorted(counter.items(), key=lambda x: (-x[1], x[0])) + + if max_tokens is None: + ordered_dict = OrderedDict(sorted_by_freq_tuples) + else: + assert len(specials) < max_tokens, "len(specials) >= max_tokens, so the vocab will be entirely special tokens." + ordered_dict = OrderedDict(sorted_by_freq_tuples[:max_tokens - len(specials)]) - word_vocab = vocab(ordered_dict, min_freq=min_freq, specials=specials or [], - special_first=special_first) + word_vocab = vocab(ordered_dict, min_freq=min_freq, specials=specials, special_first=special_first) return word_vocab
diff --git a/test/test_vocab.py b/test/test_vocab.py --- a/test/test_vocab.py +++ b/test/test_vocab.py @@ -1,6 +1,8 @@ # -*- coding: utf-8 -*- from collections import OrderedDict import os + +import pytest import torch from test.common.torchtext_test_case import TorchtextTestCase from torchtext.vocab import ( @@ -258,3 +260,34 @@ def test_vocab_specials(self): expected_stoi = {x: index for index, x in enumerate(expected_itos)} self.assertEqual(v2.get_itos(), expected_itos) self.assertEqual(dict(v2.get_stoi()), expected_stoi) + + def test_build_vocab_sorts_descending_frequency_then_lexigraphically(self): + it = [["a", "b"], ["a", "b"]] + vocab = build_vocab_from_iterator(it) + self.assertEqual(vocab["a"], 0) + self.assertEqual(vocab["b"], 1) + + it = [["a", "b"], ["b"]] + vocab = build_vocab_from_iterator(it) + self.assertEqual(vocab["b"], 0) + self.assertEqual(vocab["a"], 1) + + def test_build_vocab_from_iterator_max_tokens(self): + it = [["hello", "world"], ["hello"]] + max_tokens = 1 + specials = ["<unk>", "<pad>"] + self.assertLess(max_tokens, len(specials)) + with pytest.raises(AssertionError): + build_vocab_from_iterator(it, specials=specials, max_tokens=max_tokens) + + max_tokens = 3 + vocab = build_vocab_from_iterator(it, specials=specials, special_first=True, max_tokens=max_tokens) + self.assertEqual(vocab["<unk>"], 0) + self.assertEqual(vocab["<pad>"], 1) + self.assertEqual(vocab["hello"], 2) + + max_tokens = 3 + vocab = build_vocab_from_iterator(it, specials=specials, special_first=False, max_tokens=max_tokens) + self.assertEqual(vocab["hello"], 0) + self.assertEqual(vocab["<unk>"], 1) + self.assertEqual(vocab["<pad>"], 2)
Add a `max_words` argument to `build_vocab_from_iterator` ## 🚀 Feature <!-- A clear and concise description of the feature proposal --> [Link to the docs](https://pytorch.org/text/stable/vocab.html?highlight=build%20vocab#torchtext.vocab.build_vocab_from_iterator) I believe it would be beneficial to limit the number of words you want in your vocabulary with an argument like `max_words`, e.g.: ``` vocab = build_vocab_from_iterator(yield_tokens_batch(file_path), specials=["<unk>"], max_words=50000) ``` **Motivation** <!-- Please outline the motivation for the proposal. Is your feature request related to a problem? e.g., I'm always frustrated when [...]. If this is related to another GitHub issue, please link here too --> This allows a controllable-sized `nn.Embedding`, with rare words being mapped to `<unk>`. Otherwise, it would not be practical to use `build_vocab_from_iterator` for larger datasets. **Alternatives** <!-- A clear and concise description of any alternative solutions or features you've considered, if any. --> Keras and Huggingface's tokenizers would be viable alternatives, but do not nicely integrate with the torchtext ecosystem.
Thank you @xhlulu for interesting proposal. I don't see any downsides for adding this argument. Internally, we are sorting tokens by frequency and I think it would be trivial to add the support for max_words by discarding the lowest frequency tokens. I wonder if there are any other criteria that users might want to follow instead of frequency? I'll add that normally your "upstream" tokenization strategy will handle this for you. For instance, you can specify subword vocab size when training unigram LM as in sentencepiece or BPE-based models. Building your torchtext vocabulary from subword tokenized segments means you already get this "max_tokens" implicitly. In python-y pseudocode, you could do something like... ```python # subword_model is a pretrained subword model w/ pre-specified vocab size max_tokens def yield_tokens(file_path, subword_model): for line in get_lines_from_file(file_path): yield from subword_model.tokenize(line) vocab = build_vocab_from_iterator(yield_tokens(file_path, subword_model), specials=[...]) assert len(vocab) <= max_tokens embedding = nn.Embedding(len(vocab), embedding_dim, padding_index=vocab["<pad>"]) ``` > I'll add that normally your "upstream" tokenization strategy will handle this for you. I wonder if this is valid for all types of tokenizers? For instance white-space or other rule/regex based tokenizers may not provide such constraints out-of-the-box, right? It's certainly not valid in all cases and your point is well taken. I'd at the very least recommend sticking with "max tokens" or "max vocab size" since words are a bit sticky. :-)
2022-01-16T14:17:20
pytorch/text
1,562
pytorch__text-1562
[ "1494" ]
7f3ed4b183eb451b439740a59bb849771c707f0c
diff --git a/torchtext/datasets/__init__.py b/torchtext/datasets/__init__.py --- a/torchtext/datasets/__init__.py +++ b/torchtext/datasets/__init__.py @@ -3,6 +3,7 @@ from .ag_news import AG_NEWS from .amazonreviewfull import AmazonReviewFull from .amazonreviewpolarity import AmazonReviewPolarity +from .cc100 import CC100 from .conll2000chunking import CoNLL2000Chunking from .dbpedia import DBpedia from .enwik9 import EnWik9 @@ -26,6 +27,7 @@ "AG_NEWS": AG_NEWS, "AmazonReviewFull": AmazonReviewFull, "AmazonReviewPolarity": AmazonReviewPolarity, + "CC100": CC100, "CoNLL2000Chunking": CoNLL2000Chunking, "DBpedia": DBpedia, "EnWik9": EnWik9, diff --git a/torchtext/datasets/cc100.py b/torchtext/datasets/cc100.py new file mode 100644 --- /dev/null +++ b/torchtext/datasets/cc100.py @@ -0,0 +1,56 @@ +import os.path + +from typing import Union, Tuple + +from torchtext._internal.module_utils import is_module_available + +if is_module_available("torchdata"): + from torchdata.datapipes.iter import FileOpener, HttpReader, IterableWrapper + +from torchtext.data.datasets_utils import ( + _create_dataset_directory, + _wrap_split_argument +) + +URL = "http://data.statmt.org/cc-100/%s.txt.xz" + +VALID_CODES = { + "am", "ar", "as", "az", "be", "bg", "bn", "bn_rom", "br", "bs", "ca", "cs", "cy", "da", "de", + "el", "en", "eo", "es", "et", "eu", "fa", "ff", "fi", "fr", "fy", "ga", "gd", "gl", "gn", "gu", + "ha", "he", "hi", "hi_rom", "hr", "ht", "hu", "hy", "id", "ig", "is", "it", "ja", "jv", "ka", + "kk", "km", "kn", "ko", "ku", "ky", "la", "lg", "li", "ln", "lo", "lt", "lv", "mg", "mk", "ml", + "mn", "mr", "ms", "my", "my_zaw", "ne", "nl", "no", "ns", "om", "or", "pa", "pl", "ps", "pt", + "qu", "rm", "ro", "ru", "sa", "si", "sc", "sd", "sk", "sl", "so", "sq", "sr", "ss", "su", "sv", + "sw", "ta", "ta_rom", "te", "te_rom", "th", "tl", "tn", "tr", "ug", "uk", "ur", "ur_rom", "uz", + "vi", "wo", "xh", "yi", "yo", "zh-Hans", "zh-Hant", "zu", +} + +NUM_LINES = None +MD5 = None + +DATASET_NAME = "CC100" + + +@_create_dataset_directory(dataset_name=DATASET_NAME) +@_wrap_split_argument(("train",)) +def CC100(root: str, split: Union[Tuple[str], str], language_code: str = "en"): + if language_code not in VALID_CODES: + raise ValueError(f"Invalid language code {language_code}") + + url = URL % language_code + url_dp = IterableWrapper([url]) + cache_compressed_dp = url_dp.on_disk_cache( + filepath_fn=lambda x: os.path.join(root, os.path.basename(url)) + ) + + cache_compressed_dp = HttpReader(cache_compressed_dp) + cache_compressed_dp = cache_compressed_dp.end_caching(mode="wb", same_filepath_fn=True) + + cache_decompressed_dp = cache_compressed_dp.on_disk_cache( + filepath_fn=lambda x: os.path.join(root, os.path.basename(x).rstrip(".xz")) + ) + cache_decompressed_dp = FileOpener(cache_decompressed_dp, mode="b").read_from_xz() + cache_decompressed_dp = cache_decompressed_dp.end_caching(mode="wb") + + data_dp = FileOpener(cache_decompressed_dp, mode="r").readlines(return_path=False) + return data_dp.map(lambda x: (language_code, x))
Migrate datasets to build on top of torchdata datapipes ## 🚀 Feature <!-- A clear and concise description of the feature proposal --> **Motivation** https://github.com/pytorch/data#why-composable-data-loading **_user-experience:_** TorchData datasets enable new functional API, auto-sharding, and snapshotting support out-of-the-box. They also enable standard flow-control like batching, collation, shuffling, bucketing, and mapping/transformation using user-defined functions and transforms (UDFs). **_Maintenance:_** By relying on TorchData, we no longer have to maintain low level functionality like downloading, extracting, caching, file/steam parsing, etc. **Reference** Examples: https://github.com/facebookexternal/torchdata/tree/main/examples/text TorchData: https://github.com/facebookexternal/torchdata ## Backlog of datasets - [x] AG_NEWS https://github.com/pytorch/text/pull/1498 - [x] AmazonReviewFull https://github.com/pytorch/text/pull/1499 - [x] AmazonReviewPolarity https://github.com/pytorch/text/pull/1490 - [x] DBpedia https://github.com/pytorch/text/pull/1500 - [x] SogouNews https://github.com/pytorch/text/pull/1503 - [x] YelpReviewFull https://github.com/pytorch/text/pull/1507 - [x] YelpReviewPolarity https://github.com/pytorch/text/pull/1509 - [x] YahooAnswers https://github.com/pytorch/text/pull/1508 - [x] CoNLL2000Chunking https://github.com/pytorch/text/pull/1515 - [x] UDPOS https://github.com/pytorch/text/pull/1535 - [x] IWSLT2016 https://github.com/pytorch/text/pull/1545 - [x] IWSLT2017 https://github.com/pytorch/text/pull/1547 - [x] Multi30K https://github.com/pytorch/text/pull/1536 - [x] SQuAD1 https://github.com/pytorch/text/pull/1513 - [x] SQuAD2 https://github.com/pytorch/text/pull/1514 - [x] PennTreebank https://github.com/pytorch/text/pull/1511 - [x] WikiText103 https://github.com/pytorch/text/pull/1518 - [x] WikiText2 https://github.com/pytorch/text/pull/1519 - [x] EnWik9 https://github.com/pytorch/text/pull/1512 - [x] IMDB https://github.com/pytorch/text/pull/1531 - [x] SST2 https://github.com/pytorch/text/pull/1538 - [x] CC-100 https://github.com/pytorch/text/pull/1562 ## Contributing Please leave a message below if you plan to work on particular dataset(s) to avoid duplication of efforts. Also please link to the corresponding PRs. cc: @Nayef211 , @abhinavarora , @erip , @ejguan , @VitalyFedyunin
This sounds great! Logistically, how do we want to organize the PRs? Should we have a branch which adds torchdata as a dependency, we branch from that branch and target that branch for our PRs? @erip That's a good point. Right now we have torchdata as an optional dependency since it is not yet available on pypi (torchdata is in prototype phase until the next Pytorch release). I think going forward we still want to keep it as an optional dependency until torchdata is released as beta. What do you think @parmeet @abhinavarora? Right, agreed with @Nayef211 . Let's continue keeping optional dependency. I am working on PR to migrate AmazonReviewPolarity (https://github.com/pytorch/text/pull/1490) to ensure nothing breaks in the CI when doing the migration. Once this lands, we can follow the same to migrate other datasets. Great, so individual PRs instead of one big one -- got it! I'll pick a couple soon and start digging. I guess it will become necessary to use some `skip if` logic when dealing with optional dependency. In CI, I recommend to make them fail unless explicitly allowed to skip. We had an issue where CUDA tests were unintentionally skipped because of wrong CI configuration and permissive `skipIf`. Here is the update I applied recently to avoid that https://github.com/pytorch/audio/pull/2127 I'll keep a moving list here. To start, I'll take... - AG_NEWS - Amazon review full - DBPedia - Sogou News - YelpReviewFull - YelpReviewPolarity - YahooAnswers - CoNLL2000Chunking - SQUAD1 - SQUAD2 - UDPOS (blocked by CoNLL2000Chunking) - IWSLT2016 - IWSLT2017 - Multi30K Hey @erip, thank you for picking the datasets :). > I'll keep a moving list here. To start, I'll take... Since we already have a backlog checklist in the the issue, you may constraint this list to the datasets you pick-up and checkmark it directly in the backlog items once the PR lands. > * ~AmazonReviewPolarity~ Parmeet has finished this you may skip the mention for this dataset. I will check mark it once I land the PR :) AmazonRiviewPolarity [WIP] https://github.com/pytorch/text/pull/1490. Note that this PR shall also resolve issues with existing CI dataset tests. > I guess it will become necessary to use some `skip if` logic when dealing with optional dependency. In CI, I recommend to make them fail unless explicitly allowed to skip. We had an issue where CUDA tests were unintentionally skipped because of wrong CI configuration and permissive `skipIf`. > > Here is the update I applied recently to avoid that [pytorch/audio#2127](https://github.com/pytorch/audio/pull/2127) Actually in this case, the problem is beyond just unit-testing. The package builds (conda, wheels, docs) also rely on availability of torchdata, because it is imported inside the modules. As of now, the import is [conditioned](https://github.com/pytorch/text/blob/1a052693509ce32b6fb91302f6ca62546b0afe0d/torchtext/experimental/datasets/sst2.py#L12) on availability. For unit-testing, we are [installing torchdata](https://github.com/pytorch/text/blob/1a052693509ce32b6fb91302f6ca62546b0afe0d/.circleci/unittest/linux/scripts/install.sh#L17) from source. Perhaps we could do the same for package builds? > Actually in this case, the problem is beyond just unit-testing. The package builds (conda, wheels, docs) also rely on availability of torchdata, because it is imported inside the modules. As of now, the import is [conditioned](https://github.com/pytorch/text/blob/1a052693509ce32b6fb91302f6ca62546b0afe0d/torchtext/experimental/datasets/sst2.py#L12) on availability. For unit-testing, we are [installing torchdata](https://github.com/pytorch/text/blob/1a052693509ce32b6fb91302f6ca62546b0afe0d/.circleci/unittest/linux/scripts/install.sh#L17) from source. Perhaps we could do the same for package builds? Isn't torchdata optional runtime dependency? I looked into the build process, and CI configuration but I do not see any mention to torchdata or the build/packaging logic changed by the presence of torchdata. I plan to pick-up CC-100 next.. > Isn't torchdata optional runtime dependency? Yes, it is if users does not use migrated datasets. But they would need installation if they need to use them since the underlying implementation of migrated datasets does not fall back to previous (non-datapipes based) implementation if torchdata package is not found. Edit: We are going to make torchdata hard-dependency with the next release. I think the question is rather what should we be doing during this migration phase. As a safe side, I think keeping it optional make sense, so that users working directly from source/nightly do not break their workflow unless they depend on the migrated datasets (in which case they would need installation anyway). > I looked into the build process, and CI configuration but I do not see any mention to torchdata or the build/packaging logic changed by the presence of torchdata. If we remove the [conditional import](https://github.com/pytorch/text/blob/1a052693509ce32b6fb91302f6ca62546b0afe0d/torchtext/experimental/datasets/sst2.py#L12), it breaks the CI build/packaging related tests. I guess we would need to install torchdata in appropriate locations for them to pass like we are doing for unit-testing [here](https://github.com/pytorch/text/blob/1a052693509ce32b6fb91302f6ca62546b0afe0d/.circleci/unittest/linux/scripts/install.sh#L17) > Edit: We are going to make torchdata hard-dependency with the next release. I think the question is rather what should we be doing during this migration phase. As a safe side, I think keeping it optional make sense, so that users working directly from source/nightly do not break their workflow unless they depend on the migrated datasets (in which case they would need installation anyway). I second on this. Before our release, TorchData theoretically is unstable library, which means our API would change a lot. Nightly users of TorchText can encounter error during installation phase. This should not be expected as some users won't use anything from TorchData. > Edit: We are going to make torchdata hard-dependency with the next release. Okay, this is what I wanted to verify. As long as it is the intended move (and is going to be mentioned in README) then it sounds good to me. > If we remove the conditional import, it breaks the CI build/packaging related tests. I guess we would need to install torchdata in appropriate locations for them to pass like we are doing for unit-testing here nit: IMU, packaging job should not be importing torchtext, so, I am not entirely convinced that it's required at build time. (especially since torchdata is pure-python package) Maybe it failed at smoke test step that happens right after the packaging step in the same CI job. > nit: IMU, packaging job should not be importing torchtext, so, I am not entirely convinced that it's required at build time. (especially since torchdata is pure-python package) Maybe it failed at smoke test step that happens right after the packaging step in the same CI job. sorry for the confusion, yes you are right it is not needed for packaging, but rather in testing in the same CI job (basically importing torchtext would fail as it would implicitly import datasets that would fail due to missing torchdata package) I plan to pick up - WikiText103 - WikiText2 Continuing on the discussion (https://github.com/pytorch/text/pull/1513#issuecomment-1013319134) by @ejguan, I think it's worth considering this point. The point of discussion is whether we should keep both the implementations (current one and the one with datapipes) in upcoming release (0.12) and provide user-warning to switch to the new implementation? **Some thoughts** Pros: * Better handling of BC related issues, risk minimization of breaking user workflows in unexpected ways * Give enough time to users to switch to new implementation, meanwhile making some educational blogs, tutorial for transition * Minimize any risk related to torchdata being still in process of making first beta-release or API changes/adaptions Cons: * Cannot think of any, except a bit of extra maintenance @mthrok, @Nayef211 , @abhinavarora, @erip: would appreciate your thoughts here to help us reach a consensus. > Pros: > > * Better handling of BC related issues, risk minimization of breaking user workflows in unexpected ways > * Give enough time to users to switch to new implementation, meanwhile making some educational blogs, tutorial for transition > * Minimize any risk related to torchdata being still in process of making first beta-release or API changes/adaptions > Cons: > > * Cannot think of any, except a bit of extra maintenance In terms of pros I agree with the 2nd and 3rd points. My question about the first point would be whether there would be any BC related issues? As we discussed before starting this revamp effort, the purpose of this migration is to change the underlying implementation of the datasets without modifying the user facing API. If this is indeed the case, the end-user shouldn't notice any changes in how they are using the dataset. The main issues I could foresee coming up would be related to dependency changes caused by upgrading to datapipes. That being said, I am still okay with maintaining both implementations if that would guarantee a better UX. Would we want to add all the datapipe backed datasets in `experimental/datasets` folder if we ended up maintaining both implementations? > Continuing on the discussion ([#1513 (comment)](https://github.com/pytorch/text/pull/1513#issuecomment-1013319134)) by @ejguan, I think it's worth considering this point. The point of discussion is whether we should keep both the implementations (current one and the one with datapipes) in upcoming release (0.12) and provide user-warning to switch to the new implementation? > > **Some thoughts** > > Pros: > > * Better handling of BC related issues, risk minimization of breaking user workflows in unexpected ways > * Give enough time to users to switch to new implementation, meanwhile making some educational blogs, tutorial for transition > * Minimize any risk related to torchdata being still in process of making first beta-release or API changes/adaptions > > Cons: > > * Cannot think of any, except a bit of extra maintenance > > @mthrok, @Nayef211 , @abhinavarora, @erip: would appreciate your thoughts here to help us reach a consensus. I would be wary of adding additional maintenance costs. Could you elaborate what is the BC breaking change. Since the API is the same, is it just the missing torchdata library? Given that torchdata is also releasing with our 0.12 release, I honestly don't see any serious issue with just migrating to the new code. Also the test failures will only impact nightly users right? In that case the warning message is very straightforward and the users can easily set up torchdata. Lease let me know if I am missing something. Thanks @abhinavarora and @Nayef211 for your thoughts on BC issue. Honestly, I am of similar impression and cannot think immediately of any obvious BC issues (which is why I wrote unexpected :) ). One of things new API doesn't support is `__next__` method, though I don't know how this might impact user if any. @Nayef211 regarding you question: > Would we want to add all the datapipe backed datasets in experimental/datasets folder if we ended up maintaining both implementations? I don't think we want to do that. One way to keep both the implementations is by switching to new implementation through some flag etc. By default users would still use the existing implementation and along with that get user-warning and settings information to switch to new implementation. This surely adds to some maintenance overhead which @abhinavarora already raised concerns about. I'd like to take a stab at the IMDB dataset Replying the comment from #1513 > > BTW, do we want to replace the old implementation directly? I think we may want to keep the original implementation at least one release cycle. > > Thanks @ejguan for this call out. I think you made a valid point. Perhaps we could support both the implementation with the ability to switch to new implementation by setting flags or something. Let's take this discussion on the issue (#1494 ) directly. If using a flag, I recommend that to make it a part of constructor. (should not be a big deal if the interface is same) Not a global flag. torchaudio has a global flag for I/O backend and it's not a good maintenance experience. It turned the codebase stateful and in a large code base, it becomes impossible to tell which downstream project sets/expects which flag state. Quick update: - UDPOS is done. I can't check if off here, but maybe someone else can. 😄 - The IWSLT datasets are a bit tricky for a couple of reasons: - The have nested tarballs. I have submitted a PR upstream to torchdata to add a [flatmap datapipe](https://github.com/pytorch/data/pull/179) and plan to add it to the torchtext repo until that's merged. - The files get cleaned and rewritten in-place. This isn't a strict requirement, but it's a bit delicate, so I'm trying to proceed with caution. - There's a lot of conditional logic depending on the file format. I'll need to think about how best to handle this. Probably just mapping a function which abstracts the conditions... hope it'll be serializable In the meantime, I'll take a stab at Multi30k -- it looks quite straightforward. I can't seem to find CC100 and SST2 impls -- are these new datasets for torchtext? > * UDPOS is done. I can't check if off here, but maybe someone else can. 😄 Done :) > * The have nested tarballs. I have submitted a PR upstream to torchdata to add a [flatmap datapipe](https://github.com/pytorch/data/pull/179) and plan to add it to the torchtext repo until that's merged. Could you please help provide more details as to where is this required? > In the meantime, I'll take a stab at Multi30k Great, thanks! > I can't seem to find CC100 and SST2 impls -- are these new datasets for torchtext? SST-2 is in experimental folder. @Nayef211 is working on it, and is currently blocked due to some internal fbcode dependency. I am looking at CC100. It is already added as a notebook example [here](https://github.com/pytorch/data/blob/main/examples/text/CC100.ipynb). Unfortunately, the host seems to be quite un-responsive and hence i am currently blocked to add this one. I am trying to contact some internal folks to figure out the path forward. > Could you please help provide more details ... Yes, it's [here](https://github.com/pytorch/text/blob/main/torchtext/datasets/iwslt2016.py#L231-L241). We extract contents from a tarball and inside the tarball are other tarballs. This requires something roughly like: ```python # [ 1.tgz, 2.tgz, ..., n.tgz] inner_tars = outer_tar.read_from_tar() # Yuck, an IterableDataPipe of IterableDataPipes... flatmap to the rescue # [ 1_1.txt, 1_2.txt, 2_1.txt, 2_2.txt, 3_1.txt, ...] inner_inner_files = inner_tars.flatmap(lambda inner_tar: FileOpener(inner_tar).read_from_tar()) ``` > inner_inner_files = inner_tars.flatmap(lambda inner_tar: FileOpener(inner_tar).read_from_tar()) I see, but isn't it that tar datapipe would recursively already do it and return all the inner files? @parmeet oh, I'm not sure... I didn't think so, but I guess I hadn't tried yet so I don't know. I'll give it a shot tomorrow. @parmeet looking at the implementation of the datapipe associated with the `read_from_tar` functional, it doesn't extract recursively. The PR in torchdata seems to moving forward so it will likely not be something we need to worry about much. > The PR in torchdata seems to moving forward so it will likely not be something we need to worry about much. Awesome! Thanks so much @erip for taking it forward. I guess these are the only two datasets left (apart for CC-100 :) ). Please feel free to post if there are any blockages :).
2022-01-31T20:52:00
pytorch/text
1,656
pytorch__text-1656
[ "1655" ]
8b08b87a6f914bca8ee2cd9b094c4a74a62509a9
diff --git a/torchtext/utils.py b/torchtext/utils.py --- a/torchtext/utils.py +++ b/torchtext/utils.py @@ -11,6 +11,9 @@ from ._download_hooks import _DATASET_DOWNLOAD_MANAGER +logger = logging.getLogger(__name__) + + def reporthook(t): """ https://github.com/tqdm/tqdm. @@ -61,7 +64,7 @@ def validate_file(file_obj, hash_value, hash_type="sha256"): def _check_hash(path, hash_value, hash_type): - logging.info("Validating hash {} matches hash of {}".format(hash_value, path)) + logger.info("Validating hash {} matches hash of {}".format(hash_value, path)) with open(path, "rb") as file_obj: if not validate_file(file_obj, hash_value, hash_type): raise RuntimeError( @@ -97,7 +100,7 @@ def download_from_url(url, path=None, root=".data", overwrite=False, hash_value= # skip download if path exists and overwrite is not True if os.path.exists(path): - logging.info("File %s already exists." % path) + logger.info("File %s already exists." % path) if not overwrite: if hash_value: _check_hash(path, hash_value, hash_type) @@ -113,7 +116,7 @@ def download_from_url(url, path=None, root=".data", overwrite=False, hash_value= # download data and move to path _DATASET_DOWNLOAD_MANAGER.get_local_path(url, destination=path) - logging.info("File {} downloaded.".format(path)) + logger.info("File {} downloaded.".format(path)) # validate if hash_value: @@ -147,7 +150,7 @@ def extract_archive(from_path, to_path=None, overwrite=False): to_path = os.path.dirname(from_path) if from_path.endswith((".tar.gz", ".tgz")): - logging.info("Opening tar file {}.".format(from_path)) + logger.info("Opening tar file {}.".format(from_path)) with tarfile.open(from_path, "r") as tar: files = [] for file_ in tar: @@ -155,32 +158,32 @@ def extract_archive(from_path, to_path=None, overwrite=False): if file_.isfile(): files.append(file_path) if os.path.exists(file_path): - logging.info("{} already extracted.".format(file_path)) + logger.info("{} already extracted.".format(file_path)) if not overwrite: continue tar.extract(file_, to_path) - logging.info("Finished extracting tar file {}.".format(from_path)) + logger.info("Finished extracting tar file {}.".format(from_path)) return files elif from_path.endswith(".zip"): assert zipfile.is_zipfile(from_path), from_path - logging.info("Opening zip file {}.".format(from_path)) + logger.info("Opening zip file {}.".format(from_path)) with zipfile.ZipFile(from_path, "r") as zfile: files = [] for file_ in zfile.namelist(): file_path = os.path.join(to_path, file_) files.append(file_path) if os.path.exists(file_path): - logging.info("{} already extracted.".format(file_path)) + logger.info("{} already extracted.".format(file_path)) if not overwrite: continue zfile.extract(file_, to_path) files = [f for f in files if os.path.isfile(f)] - logging.info("Finished extracting zip file {}.".format(from_path)) + logger.info("Finished extracting zip file {}.".format(from_path)) return files elif from_path.endswith(".gz"): - logging.info("Opening gz file {}.".format(from_path)) + logger.info("Opening gz file {}.".format(from_path)) default_block_size = 65536 filename = from_path[:-3] files = [filename] @@ -192,7 +195,7 @@ def extract_archive(from_path, to_path=None, overwrite=False): else: d_file.write(block) d_file.write(block) - logging.info("Finished extracting gz file {}.".format(from_path)) + logger.info("Finished extracting gz file {}.".format(from_path)) return files else:
torchtext data loader uses root logger ## 🐛 Bug ### Description This is not a behavioural bug, but a logging issue. `torchtext` dumps a large amount of logs while loading data sets when a Python root logger is configured. See Snapshots section for an example. Ideally, I should be able to suppress all information logs with a code like this: ```Python logging.getLogger('torchtext').setLevel(logging.WARN) ``` However, `torchtext` uses the root logger in `text/utils.py` (and perhaps other places), which means I am forced to disable the root logger, which is a bad idea (the root logger serves an important purpose, which is to capture logs for all modules which don't have a specific logger defined for them.) So, in [this line](https://github.com/pytorch/text/blob/8b08b87a6f914bca8ee2cd9b094c4a74a62509a9/torchtext/utils.py#L158), instead of doing: ```Python logging.info("{} already extracted.".format(file_path)) ``` this can be done: ```Python logging.getLogger(__name__).info("{} already extracted.".format(file_path)) ``` Typically, a Python module would have the following line defined at the top: ```Python log = logging.getLogger(__name__) ``` and then in the remainder of the file the `log` object is used for logging, e.g. `log.info`, etc. See [the official documentation](https://docs.python.org/3/library/logging.html) for more information. ### Reproduction You can reproduce this error by: 1. Defining a root logger that dumps to the console. 2. Loading a data set. I used the en-fr one in IWSLT2016, but I believe this is not related to a specific dataset, but the way logging is done in utils.py. ### Expected behavior `torchtext` should not use the root logger, and instead use a logger specific to the current module using the `__name__` keyword. ### Screenshots ``` 2022-03-13 16:20:18,123 INFO File /home/rafid/.torchtext/cache/IWSLT2016/2016-01.tgz already exists. 2022-03-13 16:20:18,124 INFO Validating hash c393ed3fc2a1b0f004b3331043f615ae matches hash of /home/rafid/.torchtext/cache/IWSLT2016/2016-01.tgz 2022-03-13 16:20:18,315 INFO Opening tar file /home/rafid/.torchtext/cache/IWSLT2016/2016-01.tgz. 2022-03-13 16:20:18,316 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/._subjeval.html already extracted. 2022-03-13 16:20:18,316 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/subjeval.html already extracted. 2022-03-13 16:20:18,316 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/._texts.html already extracted. 2022-03-13 16:20:18,316 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts.html already extracted. 2022-03-13 16:20:18,317 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/._tools.html already extracted. 2022-03-13 16:20:18,317 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/tools.html already extracted. 2022-03-13 16:20:18,317 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/fr/en/._.eval already extracted. 2022-03-13 16:20:18,317 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/fr/en/.eval already extracted. 2022-03-13 16:20:18,317 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/fr/en/._.info already extracted. 2022-03-13 16:20:18,318 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/fr/en/.info already extracted. 2022-03-13 16:20:18,318 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/fr/en/._fr-en.tgz already extracted. 2022-03-13 16:20:18,319 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/fr/en/fr-en.tgz already extracted. 2022-03-13 16:20:18,340 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/fr/._.eval already extracted. 2022-03-13 16:20:18,341 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/fr/.eval already extracted. 2022-03-13 16:20:18,341 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/fr/._.info already extracted. 2022-03-13 16:20:18,341 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/fr/.info already extracted. 2022-03-13 16:20:18,341 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/fr/._en-fr.tgz already extracted. 2022-03-13 16:20:18,341 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/fr/en-fr.tgz already extracted. 2022-03-13 16:20:18,363 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/de/._.eval already extracted. 2022-03-13 16:20:18,364 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/de/.eval already extracted. 2022-03-13 16:20:18,364 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/de/._.info already extracted. 2022-03-13 16:20:18,364 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/de/.info already extracted. 2022-03-13 16:20:18,364 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/de/._en-de.tgz already extracted. 2022-03-13 16:20:18,365 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/de/en-de.tgz already extracted. 2022-03-13 16:20:18,386 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/cs/._.eval already extracted. 2022-03-13 16:20:18,386 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/cs/.eval already extracted. 2022-03-13 16:20:18,386 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/cs/._.info already extracted. 2022-03-13 16:20:18,387 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/cs/.info already extracted. 2022-03-13 16:20:18,387 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/cs/._en-cs.tgz already extracted. 2022-03-13 16:20:18,387 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/cs/en-cs.tgz already extracted. 2022-03-13 16:20:18,398 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/ar/._.eval already extracted. 2022-03-13 16:20:18,399 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/ar/.eval already extracted. 2022-03-13 16:20:18,399 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/ar/._.info already extracted. 2022-03-13 16:20:18,399 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/ar/.info already extracted. 2022-03-13 16:20:18,399 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/ar/._en-ar.tgz already extracted. 2022-03-13 16:20:18,399 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/ar/en-ar.tgz already extracted. 2022-03-13 16:20:18,423 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/de/en/._.eval already extracted. 2022-03-13 16:20:18,424 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/de/en/.eval already extracted. 2022-03-13 16:20:18,424 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/de/en/._.info already extracted. 2022-03-13 16:20:18,424 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/de/en/.info already extracted. 2022-03-13 16:20:18,424 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/de/en/._de-en.tgz already extracted. 2022-03-13 16:20:18,425 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/de/en/de-en.tgz already extracted. 2022-03-13 16:20:18,445 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/cs/en/._.eval already extracted. 2022-03-13 16:20:18,445 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/cs/en/.eval already extracted. 2022-03-13 16:20:18,446 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/cs/en/._.info already extracted. 2022-03-13 16:20:18,446 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/cs/en/.info already extracted. 2022-03-13 16:20:18,446 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/cs/en/._cs-en.tgz already extracted. 2022-03-13 16:20:18,446 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/cs/en/cs-en.tgz already extracted. 2022-03-13 16:20:18,461 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/ar/en/._.eval already extracted. 2022-03-13 16:20:18,461 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/ar/en/.eval already extracted. 2022-03-13 16:20:18,461 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/ar/en/._.info already extracted. 2022-03-13 16:20:18,462 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/ar/en/.info already extracted. 2022-03-13 16:20:18,462 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/ar/en/._ar-en.tgz already extracted. 2022-03-13 16:20:18,462 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/ar/en/ar-en.tgz already extracted. 2022-03-13 16:20:18,486 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/subeval_files/._IWSLT16-HE-RELEASE.zip already extracted. 2022-03-13 16:20:18,486 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/subeval_files/IWSLT16-HE-RELEASE.zip already extracted. 2022-03-13 16:20:18,488 INFO Finished extracting tar file /home/rafid/.torchtext/cache/IWSLT2016/2016-01.tgz. 2022-03-13 16:20:18,489 INFO Opening tar file /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/ar/en-ar.tgz. 2022-03-13 16:20:18,490 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/ar/en-ar/IWSLT16.TED.dev2010.en-ar.ar.xml already extracted. 2022-03-13 16:20:18,491 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/ar/en-ar/IWSLT16.TED.dev2010.en-ar.en.xml already extracted. 2022-03-13 16:20:18,491 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/ar/en-ar/IWSLT16.TED.tst2010.en-ar.ar.xml already extracted. 2022-03-13 16:20:18,492 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/ar/en-ar/IWSLT16.TED.tst2010.en-ar.en.xml already extracted. 2022-03-13 16:20:18,493 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/ar/en-ar/IWSLT16.TED.tst2011.en-ar.ar.xml already extracted. 2022-03-13 16:20:18,494 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/ar/en-ar/IWSLT16.TED.tst2011.en-ar.en.xml already extracted. 2022-03-13 16:20:18,495 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/ar/en-ar/IWSLT16.TED.tst2012.en-ar.ar.xml already extracted. 2022-03-13 16:20:18,496 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/ar/en-ar/IWSLT16.TED.tst2012.en-ar.en.xml already extracted. 2022-03-13 16:20:18,497 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/ar/en-ar/IWSLT16.TED.tst2013.en-ar.ar.xml already extracted. 2022-03-13 16:20:18,498 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/ar/en-ar/IWSLT16.TED.tst2013.en-ar.en.xml already extracted. 2022-03-13 16:20:18,499 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/ar/en-ar/IWSLT16.TED.tst2014.en-ar.ar.xml already extracted. 2022-03-13 16:20:18,500 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/ar/en-ar/IWSLT16.TED.tst2014.en-ar.en.xml already extracted. 2022-03-13 16:20:18,500 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/ar/en-ar/README already extracted. 2022-03-13 16:20:18,501 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/ar/en-ar/train.ar already extracted. 2022-03-13 16:20:18,613 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/ar/en-ar/train.tags.en-ar.ar already extracted. 2022-03-13 16:20:18,728 INFO /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/ar/en-ar/train.tags.en-ar.en already extracted. 2022-03-13 16:20:18,819 INFO Finished extracting tar file /home/rafid/.torchtext/cache/IWSLT2016/2016-01/texts/en/ar/en-ar.tgz. ``` ### Environment ``` Collecting environment information... PyTorch version: 1.10.1 Is debug build: False CUDA used to build PyTorch: 11.3 ROCM used to build PyTorch: N/A OS: Fedora Linux 35 (Workstation Edition) (x86_64) GCC version: (GCC) 11.2.1 20220127 (Red Hat 11.2.1-9) Clang version: Could not collect CMake version: Could not collect Libc version: glibc-2.34 Python version: 3.9.7 (default, Sep 16 2021, 13:09:58) [GCC 7.5.0] (64-bit runtime) Python platform: Linux-5.16.12-200.fc35.x86_64-x86_64-with-glibc2.34 Is CUDA available: True CUDA runtime version: Could not collect GPU models and configuration: GPU 0: NVIDIA GeForce RTX 3090 Nvidia driver version: 510.47.03 cuDNN version: Could not collect HIP runtime version: N/A MIOpen runtime version: N/A Is XNNPACK available: True Versions of relevant libraries: [pip3] numpy==1.21.2 [pip3] torch==1.10.1 [pip3] torchaudio==0.10.1 [pip3] torchtext==0.11.1 [pip3] torchvision==0.11.2 [conda] blas 1.0 mkl [conda] cudatoolkit 11.3.1 h2bc3f7f_2 [conda] mkl 2021.4.0 h06a4308_640 [conda] mkl-service 2.4.0 py39h7f8727e_0 [conda] mkl_fft 1.3.1 py39hd3c417c_0 [conda] mkl_random 1.2.2 py39h51133e4_0 [conda] numpy 1.21.2 py39h20f2e39_0 [conda] numpy-base 1.21.2 py39h79a1101_0 [conda] pytorch 1.10.1 py3.9_cuda11.3_cudnn8.2.0_0 pytorch [conda] pytorch-mutex 1.0 cuda pytorch [conda] torchaudio 0.10.1 py39_cu113 pytorch [conda] torchtext 0.11.1 py39 pytorch [conda] torchvision 0.11.2 py39_cu113 pytorch ``` ### Additional context N/A
Thanks @rafidka for raising this issue. This make sense, we do have file specific loggers but this practice is not universal in the library. Will make PR to fix this.
2022-03-14T20:23:47
pytorch/text
1,805
pytorch__text-1805
[ "1154" ]
de070503431b644c50b7c611b46e7484ba12061f
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -4,6 +4,7 @@ import os import shutil import subprocess +import sys from pathlib import Path from build_tools import setup_helpers @@ -44,6 +45,18 @@ def _export_version(version, sha): fileobj.write("git_version = {}\n".format(repr(sha))) +def _init_submodule(): + print(" --- Initializing submodules") + try: + subprocess.check_call(["git", "submodule", "init"]) + subprocess.check_call(["git", "submodule", "update"]) + except Exception: + print(" --- Submodule initalization failed") + print("Please run:\n\tgit submodule update --init --recursive") + sys.exit(1) + print(" --- Initialized submodule") + + VERSION, SHA = _get_version() _export_version(VERSION, SHA) @@ -76,6 +89,7 @@ def run(self): shutil.rmtree(str(path), ignore_errors=True) +_init_submodule() setup_info = dict( # Metadata name="torchtext",
Make TorchText installable from direct reference In order to make `pip install https://github.com/pytorch/text` succeed `setup.py` should have logic to initialize submodules Add `check_submodules()` routine to setup.py to check if 'third_party/re2/CMakeLists.txt' is present on the filesystem and attempt to initialize submodules if it is not
2022-06-23T16:42:57
pytorch/text
1,889
pytorch__text-1889
[ "1875" ]
dfac1ee70a0219653221e25a26684299be870fa3
diff --git a/tools/setup_helpers/extension.py b/tools/setup_helpers/extension.py --- a/tools/setup_helpers/extension.py +++ b/tools/setup_helpers/extension.py @@ -21,6 +21,10 @@ _ROOT_DIR = _THIS_DIR.parent.parent.resolve() +def _get_cxx11_abi(): + return "-D_GLIBCXX_USE_CXX11_ABI=" + str(int(torch.compiled_with_cxx11_abi())) + + def get_ext_modules(): modules = [ Extension(name=_LIBTORCHTEXT_NAME, sources=[]), @@ -72,6 +76,7 @@ def build_extension(self, ext): "-DBUILD_SHARED_LIBS=OFF", "-DCMAKE_POLICY_DEFAULT_CMP0063=NEW", "-DSPM_ENABLE_SHARED=OFF", + f"-DTORCH_COMPILED_WITH_CXX_ABI={_get_cxx11_abi()}", ] build_args = ["--target", "install"]
diff --git a/.circleci/unittest/linux/scripts/run_test.sh b/.circleci/unittest/linux/scripts/run_test.sh --- a/.circleci/unittest/linux/scripts/run_test.sh +++ b/.circleci/unittest/linux/scripts/run_test.sh @@ -6,4 +6,5 @@ eval "$(./conda/bin/conda shell.bash hook)" conda activate ./env python -m torch.utils.collect_env -pytest --cov=torchtext --junitxml=test-results/junit.xml -v --durations 20 test +cd test +pytest --cov=torchtext --junitxml=test-results/junit.xml -v --durations 20 torchtext_unittest diff --git a/.circleci/unittest/windows/scripts/run_test.sh b/.circleci/unittest/windows/scripts/run_test.sh --- a/.circleci/unittest/windows/scripts/run_test.sh +++ b/.circleci/unittest/windows/scripts/run_test.sh @@ -6,4 +6,5 @@ eval "$(./conda/Scripts/conda.exe 'shell.bash' 'hook')" conda activate ./env python -m torch.utils.collect_env -pytest --cov=torchtext --junitxml=test-results/junit.xml -v --durations 20 test +cd test +pytest --cov=torchtext --junitxml=test-results/junit.xml -v --durations 20 torchtext_unittest diff --git a/test/.gitignore b/test/.gitignore deleted file mode 100644 diff --git a/test/integration_tests/conftest.py b/test/integration_tests/conftest.py --- a/test/integration_tests/conftest.py +++ b/test/integration_tests/conftest.py @@ -15,9 +15,9 @@ def pytest_addoption(parser): ) [email protected](scope="class") [email protected](autouse=True, scope="class") def temp_hub_dir(tmp_path_factory, pytestconfig): - if not pytestconfig.getoption("--use-tmp-hub-dir"): + if not pytestconfig.getoption("use_tmp_hub_dir"): yield else: tmp_dir = tmp_path_factory.mktemp("hub", numbered=True).resolve() diff --git a/test/prototype/integration_tests/test_models.py b/test/integration_tests/prototype/test_models.py similarity index 95% rename from test/prototype/integration_tests/test_models.py rename to test/integration_tests/prototype/test_models.py --- a/test/prototype/integration_tests/test_models.py +++ b/test/integration_tests/prototype/test_models.py @@ -1,9 +1,6 @@ import pytest # noqa: F401 import torch from parameterized import parameterized, parameterized_class -from test.common.assets import get_asset_path -from test.common.parameterized_utils import nested_params -from test.common.torchtext_test_case import TorchtextTestCase from torchtext.prototype.models import ( T5_BASE_ENCODER, T5_BASE, @@ -18,6 +15,9 @@ T5Transform, ) from torchtext.prototype.models.t5.wrapper import T5Wrapper +from torchtext_unittest.common.assets import get_asset_path +from torchtext_unittest.common.parameterized_utils import nested_params +from torchtext_unittest.common.torchtext_test_case import TorchtextTestCase BUNDLERS = { diff --git a/test/integration_tests/test_models.py b/test/integration_tests/test_models.py --- a/test/integration_tests/test_models.py +++ b/test/integration_tests/test_models.py @@ -7,9 +7,15 @@ XLMR_BASE_ENCODER, XLMR_LARGE_ENCODER, ) +from torchtext_unittest.common.assets import get_asset_path +from torchtext_unittest.common.torchtext_test_case import TorchtextTestCase -from ..common.assets import get_asset_path -from ..common.torchtext_test_case import TorchtextTestCase +BUNDLERS = { + "xlmr_base": XLMR_BASE_ENCODER, + "xlmr_large": XLMR_LARGE_ENCODER, + "roberta_base": ROBERTA_BASE_ENCODER, + "roberta_large": ROBERTA_LARGE_ENCODER, +} BUNDLERS = { "xlmr_base": XLMR_BASE_ENCODER, diff --git a/test/prototype/models/__init__.py b/test/prototype/models/__init__.py deleted file mode 100644 diff --git a/test/__init__.py b/test/torchtext_unittest/__init__.py similarity index 100% rename from test/__init__.py rename to test/torchtext_unittest/__init__.py diff --git a/test/asset/SST2/SST-2.zip b/test/torchtext_unittest/asset/SST2/SST-2.zip similarity index 100% rename from test/asset/SST2/SST-2.zip rename to test/torchtext_unittest/asset/SST2/SST-2.zip diff --git a/test/asset/bert_base_cased_vocab.txt b/test/torchtext_unittest/asset/bert_base_cased_vocab.txt similarity index 100% rename from test/asset/bert_base_cased_vocab.txt rename to test/torchtext_unittest/asset/bert_base_cased_vocab.txt diff --git a/test/asset/bert_base_uncased_vocab.txt b/test/torchtext_unittest/asset/bert_base_uncased_vocab.txt similarity index 100% rename from test/asset/bert_base_uncased_vocab.txt rename to test/torchtext_unittest/asset/bert_base_uncased_vocab.txt diff --git a/test/asset/clip_encoder.json b/test/torchtext_unittest/asset/clip_encoder.json similarity index 100% rename from test/asset/clip_encoder.json rename to test/torchtext_unittest/asset/clip_encoder.json diff --git a/test/asset/clip_vocab.bpe b/test/torchtext_unittest/asset/clip_vocab.bpe similarity index 100% rename from test/asset/clip_vocab.bpe rename to test/torchtext_unittest/asset/clip_vocab.bpe diff --git a/test/asset/glove.6B.zip b/test/torchtext_unittest/asset/glove.6B.zip similarity index 100% rename from test/asset/glove.6B.zip rename to test/torchtext_unittest/asset/glove.6B.zip diff --git a/test/asset/glove.840B.300d.zip b/test/torchtext_unittest/asset/glove.840B.300d.zip similarity index 100% rename from test/asset/glove.840B.300d.zip rename to test/torchtext_unittest/asset/glove.840B.300d.zip diff --git a/test/asset/gpt2_bpe_encoder.json b/test/torchtext_unittest/asset/gpt2_bpe_encoder.json similarity index 100% rename from test/asset/gpt2_bpe_encoder.json rename to test/torchtext_unittest/asset/gpt2_bpe_encoder.json diff --git a/test/asset/gpt2_bpe_vocab.bpe b/test/torchtext_unittest/asset/gpt2_bpe_vocab.bpe similarity index 100% rename from test/asset/gpt2_bpe_vocab.bpe rename to test/torchtext_unittest/asset/gpt2_bpe_vocab.bpe diff --git a/test/asset/label_names.txt b/test/torchtext_unittest/asset/label_names.txt similarity index 100% rename from test/asset/label_names.txt rename to test/torchtext_unittest/asset/label_names.txt diff --git a/test/asset/raw_datasets.jsonl b/test/torchtext_unittest/asset/raw_datasets.jsonl similarity index 100% rename from test/asset/raw_datasets.jsonl rename to test/torchtext_unittest/asset/raw_datasets.jsonl diff --git a/test/asset/roberta.base.output.pt b/test/torchtext_unittest/asset/roberta.base.output.pt similarity index 100% rename from test/asset/roberta.base.output.pt rename to test/torchtext_unittest/asset/roberta.base.output.pt diff --git a/test/asset/roberta.large.output.pt b/test/torchtext_unittest/asset/roberta.large.output.pt similarity index 100% rename from test/asset/roberta.large.output.pt rename to test/torchtext_unittest/asset/roberta.large.output.pt diff --git a/test/asset/spm_example.model b/test/torchtext_unittest/asset/spm_example.model similarity index 100% rename from test/asset/spm_example.model rename to test/torchtext_unittest/asset/spm_example.model diff --git a/test/asset/t5.base.encoder.output.pt b/test/torchtext_unittest/asset/t5.base.encoder.output.pt similarity index 100% rename from test/asset/t5.base.encoder.output.pt rename to test/torchtext_unittest/asset/t5.base.encoder.output.pt diff --git a/test/asset/t5.base.generation.output.pt b/test/torchtext_unittest/asset/t5.base.generation.output.pt similarity index 100% rename from test/asset/t5.base.generation.output.pt rename to test/torchtext_unittest/asset/t5.base.generation.output.pt diff --git a/test/asset/t5.base.model.output.pt b/test/torchtext_unittest/asset/t5.base.model.output.pt similarity index 100% rename from test/asset/t5.base.model.output.pt rename to test/torchtext_unittest/asset/t5.base.model.output.pt diff --git a/test/asset/t5.large.encoder.output.pt b/test/torchtext_unittest/asset/t5.large.encoder.output.pt similarity index 100% rename from test/asset/t5.large.encoder.output.pt rename to test/torchtext_unittest/asset/t5.large.encoder.output.pt diff --git a/test/asset/t5.large.generation.output.pt b/test/torchtext_unittest/asset/t5.large.generation.output.pt similarity index 100% rename from test/asset/t5.large.generation.output.pt rename to test/torchtext_unittest/asset/t5.large.generation.output.pt diff --git a/test/asset/t5.large.model.output.pt b/test/torchtext_unittest/asset/t5.large.model.output.pt similarity index 100% rename from test/asset/t5.large.model.output.pt rename to test/torchtext_unittest/asset/t5.large.model.output.pt diff --git a/test/asset/t5.small.encoder.output.pt b/test/torchtext_unittest/asset/t5.small.encoder.output.pt similarity index 100% rename from test/asset/t5.small.encoder.output.pt rename to test/torchtext_unittest/asset/t5.small.encoder.output.pt diff --git a/test/asset/t5.small.generation.output.pt b/test/torchtext_unittest/asset/t5.small.generation.output.pt similarity index 100% rename from test/asset/t5.small.generation.output.pt rename to test/torchtext_unittest/asset/t5.small.generation.output.pt diff --git a/test/asset/t5.small.model.output.pt b/test/torchtext_unittest/asset/t5.small.model.output.pt similarity index 100% rename from test/asset/t5.small.model.output.pt rename to test/torchtext_unittest/asset/t5.small.model.output.pt diff --git a/test/asset/t5_tokenizer_base.model b/test/torchtext_unittest/asset/t5_tokenizer_base.model similarity index 100% rename from test/asset/t5_tokenizer_base.model rename to test/torchtext_unittest/asset/t5_tokenizer_base.model diff --git a/test/asset/text_normalization_ag_news_ref_results.test b/test/torchtext_unittest/asset/text_normalization_ag_news_ref_results.test similarity index 100% rename from test/asset/text_normalization_ag_news_ref_results.test rename to test/torchtext_unittest/asset/text_normalization_ag_news_ref_results.test diff --git a/test/asset/text_normalization_ag_news_test.csv b/test/torchtext_unittest/asset/text_normalization_ag_news_test.csv similarity index 100% rename from test/asset/text_normalization_ag_news_test.csv rename to test/torchtext_unittest/asset/text_normalization_ag_news_test.csv diff --git a/test/asset/vectors_test.csv b/test/torchtext_unittest/asset/vectors_test.csv similarity index 100% rename from test/asset/vectors_test.csv rename to test/torchtext_unittest/asset/vectors_test.csv diff --git a/test/asset/vocab_raw_text_test.txt b/test/torchtext_unittest/asset/vocab_raw_text_test.txt similarity index 100% rename from test/asset/vocab_raw_text_test.txt rename to test/torchtext_unittest/asset/vocab_raw_text_test.txt diff --git a/test/asset/vocab_test.txt b/test/torchtext_unittest/asset/vocab_test.txt similarity index 100% rename from test/asset/vocab_test.txt rename to test/torchtext_unittest/asset/vocab_test.txt diff --git a/test/asset/vocab_test2.txt b/test/torchtext_unittest/asset/vocab_test2.txt similarity index 100% rename from test/asset/vocab_test2.txt rename to test/torchtext_unittest/asset/vocab_test2.txt diff --git a/test/asset/wiki.en.vec b/test/torchtext_unittest/asset/wiki.en.vec similarity index 100% rename from test/asset/wiki.en.vec rename to test/torchtext_unittest/asset/wiki.en.vec diff --git a/test/asset/xlmr.base.output.pt b/test/torchtext_unittest/asset/xlmr.base.output.pt similarity index 100% rename from test/asset/xlmr.base.output.pt rename to test/torchtext_unittest/asset/xlmr.base.output.pt diff --git a/test/asset/xlmr.large.output.pt b/test/torchtext_unittest/asset/xlmr.large.output.pt similarity index 100% rename from test/asset/xlmr.large.output.pt rename to test/torchtext_unittest/asset/xlmr.large.output.pt diff --git a/test/common/__init__.py b/test/torchtext_unittest/common/__init__.py similarity index 100% rename from test/common/__init__.py rename to test/torchtext_unittest/common/__init__.py diff --git a/test/common/assets.py b/test/torchtext_unittest/common/assets.py similarity index 100% rename from test/common/assets.py rename to test/torchtext_unittest/common/assets.py diff --git a/test/common/case_utils.py b/test/torchtext_unittest/common/case_utils.py similarity index 100% rename from test/common/case_utils.py rename to test/torchtext_unittest/common/case_utils.py diff --git a/test/common/parameterized_utils.py b/test/torchtext_unittest/common/parameterized_utils.py similarity index 100% rename from test/common/parameterized_utils.py rename to test/torchtext_unittest/common/parameterized_utils.py diff --git a/test/common/torchtext_test_case.py b/test/torchtext_unittest/common/torchtext_test_case.py similarity index 100% rename from test/common/torchtext_test_case.py rename to test/torchtext_unittest/common/torchtext_test_case.py diff --git a/test/csrc/__init__.py b/test/torchtext_unittest/csrc/__init__.py similarity index 100% rename from test/csrc/__init__.py rename to test/torchtext_unittest/csrc/__init__.py diff --git a/test/csrc/test_gpt2_bpe_tokenizer.py b/test/torchtext_unittest/csrc/test_gpt2_bpe_tokenizer.py similarity index 100% rename from test/csrc/test_gpt2_bpe_tokenizer.py rename to test/torchtext_unittest/csrc/test_gpt2_bpe_tokenizer.py diff --git a/test/data/__init__.py b/test/torchtext_unittest/data/__init__.py similarity index 100% rename from test/data/__init__.py rename to test/torchtext_unittest/data/__init__.py diff --git a/test/data/test_dataset_utils.py b/test/torchtext_unittest/data/test_dataset_utils.py similarity index 100% rename from test/data/test_dataset_utils.py rename to test/torchtext_unittest/data/test_dataset_utils.py diff --git a/test/data/test_functional.py b/test/torchtext_unittest/data/test_functional.py similarity index 100% rename from test/data/test_functional.py rename to test/torchtext_unittest/data/test_functional.py diff --git a/test/data/test_jit.py b/test/torchtext_unittest/data/test_jit.py similarity index 100% rename from test/data/test_jit.py rename to test/torchtext_unittest/data/test_jit.py diff --git a/test/data/test_metrics.py b/test/torchtext_unittest/data/test_metrics.py similarity index 100% rename from test/data/test_metrics.py rename to test/torchtext_unittest/data/test_metrics.py diff --git a/test/data/test_modules.py b/test/torchtext_unittest/data/test_modules.py similarity index 100% rename from test/data/test_modules.py rename to test/torchtext_unittest/data/test_modules.py diff --git a/test/data/test_utils.py b/test/torchtext_unittest/data/test_utils.py similarity index 100% rename from test/data/test_utils.py rename to test/torchtext_unittest/data/test_utils.py diff --git a/test/datasets/__init__.py b/test/torchtext_unittest/datasets/__init__.py similarity index 100% rename from test/datasets/__init__.py rename to test/torchtext_unittest/datasets/__init__.py diff --git a/test/datasets/common.py b/test/torchtext_unittest/datasets/common.py similarity index 100% rename from test/datasets/common.py rename to test/torchtext_unittest/datasets/common.py diff --git a/test/datasets/test_agnews.py b/test/torchtext_unittest/datasets/test_agnews.py similarity index 100% rename from test/datasets/test_agnews.py rename to test/torchtext_unittest/datasets/test_agnews.py diff --git a/test/datasets/test_amazonreviews.py b/test/torchtext_unittest/datasets/test_amazonreviews.py similarity index 100% rename from test/datasets/test_amazonreviews.py rename to test/torchtext_unittest/datasets/test_amazonreviews.py diff --git a/test/datasets/test_cc100.py b/test/torchtext_unittest/datasets/test_cc100.py similarity index 100% rename from test/datasets/test_cc100.py rename to test/torchtext_unittest/datasets/test_cc100.py diff --git a/test/datasets/test_cnndm.py b/test/torchtext_unittest/datasets/test_cnndm.py similarity index 100% rename from test/datasets/test_cnndm.py rename to test/torchtext_unittest/datasets/test_cnndm.py diff --git a/test/datasets/test_cola.py b/test/torchtext_unittest/datasets/test_cola.py similarity index 100% rename from test/datasets/test_cola.py rename to test/torchtext_unittest/datasets/test_cola.py diff --git a/test/datasets/test_conll2000chunking.py b/test/torchtext_unittest/datasets/test_conll2000chunking.py similarity index 100% rename from test/datasets/test_conll2000chunking.py rename to test/torchtext_unittest/datasets/test_conll2000chunking.py diff --git a/test/datasets/test_dbpedia.py b/test/torchtext_unittest/datasets/test_dbpedia.py similarity index 100% rename from test/datasets/test_dbpedia.py rename to test/torchtext_unittest/datasets/test_dbpedia.py diff --git a/test/datasets/test_enwik9.py b/test/torchtext_unittest/datasets/test_enwik9.py similarity index 100% rename from test/datasets/test_enwik9.py rename to test/torchtext_unittest/datasets/test_enwik9.py diff --git a/test/datasets/test_imdb.py b/test/torchtext_unittest/datasets/test_imdb.py similarity index 100% rename from test/datasets/test_imdb.py rename to test/torchtext_unittest/datasets/test_imdb.py diff --git a/test/datasets/test_iwslt2016.py b/test/torchtext_unittest/datasets/test_iwslt2016.py similarity index 100% rename from test/datasets/test_iwslt2016.py rename to test/torchtext_unittest/datasets/test_iwslt2016.py diff --git a/test/datasets/test_iwslt2017.py b/test/torchtext_unittest/datasets/test_iwslt2017.py similarity index 100% rename from test/datasets/test_iwslt2017.py rename to test/torchtext_unittest/datasets/test_iwslt2017.py diff --git a/test/datasets/test_mnli.py b/test/torchtext_unittest/datasets/test_mnli.py similarity index 100% rename from test/datasets/test_mnli.py rename to test/torchtext_unittest/datasets/test_mnli.py diff --git a/test/datasets/test_mrpc.py b/test/torchtext_unittest/datasets/test_mrpc.py similarity index 100% rename from test/datasets/test_mrpc.py rename to test/torchtext_unittest/datasets/test_mrpc.py diff --git a/test/datasets/test_multi30k.py b/test/torchtext_unittest/datasets/test_multi30k.py similarity index 100% rename from test/datasets/test_multi30k.py rename to test/torchtext_unittest/datasets/test_multi30k.py diff --git a/test/datasets/test_penntreebank.py b/test/torchtext_unittest/datasets/test_penntreebank.py similarity index 100% rename from test/datasets/test_penntreebank.py rename to test/torchtext_unittest/datasets/test_penntreebank.py diff --git a/test/datasets/test_qnli.py b/test/torchtext_unittest/datasets/test_qnli.py similarity index 100% rename from test/datasets/test_qnli.py rename to test/torchtext_unittest/datasets/test_qnli.py diff --git a/test/datasets/test_qqp.py b/test/torchtext_unittest/datasets/test_qqp.py similarity index 100% rename from test/datasets/test_qqp.py rename to test/torchtext_unittest/datasets/test_qqp.py diff --git a/test/datasets/test_rte.py b/test/torchtext_unittest/datasets/test_rte.py similarity index 100% rename from test/datasets/test_rte.py rename to test/torchtext_unittest/datasets/test_rte.py diff --git a/test/datasets/test_sogounews.py b/test/torchtext_unittest/datasets/test_sogounews.py similarity index 100% rename from test/datasets/test_sogounews.py rename to test/torchtext_unittest/datasets/test_sogounews.py diff --git a/test/datasets/test_squads.py b/test/torchtext_unittest/datasets/test_squads.py similarity index 100% rename from test/datasets/test_squads.py rename to test/torchtext_unittest/datasets/test_squads.py diff --git a/test/datasets/test_sst2.py b/test/torchtext_unittest/datasets/test_sst2.py similarity index 100% rename from test/datasets/test_sst2.py rename to test/torchtext_unittest/datasets/test_sst2.py diff --git a/test/datasets/test_stsb.py b/test/torchtext_unittest/datasets/test_stsb.py similarity index 100% rename from test/datasets/test_stsb.py rename to test/torchtext_unittest/datasets/test_stsb.py diff --git a/test/datasets/test_udpos.py b/test/torchtext_unittest/datasets/test_udpos.py similarity index 100% rename from test/datasets/test_udpos.py rename to test/torchtext_unittest/datasets/test_udpos.py diff --git a/test/datasets/test_wikitexts.py b/test/torchtext_unittest/datasets/test_wikitexts.py similarity index 100% rename from test/datasets/test_wikitexts.py rename to test/torchtext_unittest/datasets/test_wikitexts.py diff --git a/test/datasets/test_wnli.py b/test/torchtext_unittest/datasets/test_wnli.py similarity index 100% rename from test/datasets/test_wnli.py rename to test/torchtext_unittest/datasets/test_wnli.py diff --git a/test/datasets/test_yahooanswers.py b/test/torchtext_unittest/datasets/test_yahooanswers.py similarity index 100% rename from test/datasets/test_yahooanswers.py rename to test/torchtext_unittest/datasets/test_yahooanswers.py diff --git a/test/datasets/test_yelpreviews.py b/test/torchtext_unittest/datasets/test_yelpreviews.py similarity index 100% rename from test/datasets/test_yelpreviews.py rename to test/torchtext_unittest/datasets/test_yelpreviews.py diff --git a/test/models/__init__.py b/test/torchtext_unittest/models/__init__.py similarity index 100% rename from test/models/__init__.py rename to test/torchtext_unittest/models/__init__.py diff --git a/test/models/test_models.py b/test/torchtext_unittest/models/test_models.py similarity index 100% rename from test/models/test_models.py rename to test/torchtext_unittest/models/test_models.py diff --git a/test/models/test_transformers.py b/test/torchtext_unittest/models/test_transformers.py similarity index 100% rename from test/models/test_transformers.py rename to test/torchtext_unittest/models/test_transformers.py diff --git a/test/prototype/__init__.py b/test/torchtext_unittest/prototype/__init__.py similarity index 100% rename from test/prototype/__init__.py rename to test/torchtext_unittest/prototype/__init__.py diff --git a/test/prototype/integration_tests/__init__.py b/test/torchtext_unittest/prototype/models/__init__.py similarity index 100% rename from test/prototype/integration_tests/__init__.py rename to test/torchtext_unittest/prototype/models/__init__.py diff --git a/test/prototype/models/test_models.py b/test/torchtext_unittest/prototype/models/test_models.py similarity index 98% rename from test/prototype/models/test_models.py rename to test/torchtext_unittest/prototype/models/test_models.py --- a/test/prototype/models/test_models.py +++ b/test/torchtext_unittest/prototype/models/test_models.py @@ -2,8 +2,8 @@ from unittest.mock import patch import torch -from test.common.torchtext_test_case import TorchtextTestCase from torch.nn import functional as F +from torchtext_unittest.common.torchtext_test_case import TorchtextTestCase class TestModels(TorchtextTestCase): diff --git a/test/prototype/models/test_transforms.py b/test/torchtext_unittest/prototype/models/test_transforms.py similarity index 93% rename from test/prototype/models/test_transforms.py rename to test/torchtext_unittest/prototype/models/test_transforms.py --- a/test/prototype/models/test_transforms.py +++ b/test/torchtext_unittest/prototype/models/test_transforms.py @@ -1,7 +1,7 @@ import torch -from test.common.assets import get_asset_path -from test.common.torchtext_test_case import TorchtextTestCase from torchtext.prototype.models import T5Transform +from torchtext_unittest.common.assets import get_asset_path +from torchtext_unittest.common.torchtext_test_case import TorchtextTestCase class TestTransforms(TorchtextTestCase): diff --git a/test/prototype/test_functional.py b/test/torchtext_unittest/prototype/test_functional.py similarity index 100% rename from test/prototype/test_functional.py rename to test/torchtext_unittest/prototype/test_functional.py diff --git a/test/prototype/test_transforms.py b/test/torchtext_unittest/prototype/test_transforms.py similarity index 97% rename from test/prototype/test_transforms.py rename to test/torchtext_unittest/prototype/test_transforms.py --- a/test/prototype/test_transforms.py +++ b/test/torchtext_unittest/prototype/test_transforms.py @@ -3,14 +3,14 @@ import tempfile import torch -from test.common.assets import get_asset_path -from test.common.torchtext_test_case import TorchtextTestCase from torchtext.prototype.transforms import ( sentencepiece_processor, sentencepiece_tokenizer, VectorTransform, ) from torchtext.prototype.vectors import FastText +from torchtext_unittest.common.assets import get_asset_path +from torchtext_unittest.common.torchtext_test_case import TorchtextTestCase class TestTransforms(TorchtextTestCase): diff --git a/test/prototype/test_vectors.py b/test/torchtext_unittest/prototype/test_vectors.py similarity index 98% rename from test/prototype/test_vectors.py rename to test/torchtext_unittest/prototype/test_vectors.py --- a/test/prototype/test_vectors.py +++ b/test/torchtext_unittest/prototype/test_vectors.py @@ -4,8 +4,8 @@ import unittest import torch -from test.common.torchtext_test_case import TorchtextTestCase from torchtext.prototype.vectors import build_vectors +from torchtext_unittest.common.torchtext_test_case import TorchtextTestCase class TestVectors(TorchtextTestCase): diff --git a/test/prototype/test_with_asset.py b/test/torchtext_unittest/prototype/test_with_asset.py similarity index 99% rename from test/prototype/test_with_asset.py rename to test/torchtext_unittest/prototype/test_with_asset.py --- a/test/prototype/test_with_asset.py +++ b/test/torchtext_unittest/prototype/test_with_asset.py @@ -6,7 +6,6 @@ from functools import partial import torch -from test.common.torchtext_test_case import TorchtextTestCase from torch.utils.data import DataLoader from torchtext.data.functional import custom_replace from torchtext.prototype.transforms import ( @@ -19,6 +18,7 @@ from torchtext.prototype.vectors import build_vectors, FastText, GloVe, load_vectors_from_file_path from torchtext.prototype.vocab_factory import build_vocab_from_text_file, load_vocab_from_file from torchtext.utils import download_from_url +from torchtext_unittest.common.torchtext_test_case import TorchtextTestCase from ..common.assets import get_asset_path diff --git a/test/test_build.py b/test/torchtext_unittest/test_build.py similarity index 100% rename from test/test_build.py rename to test/torchtext_unittest/test_build.py diff --git a/test/test_functional.py b/test/torchtext_unittest/test_functional.py similarity index 100% rename from test/test_functional.py rename to test/torchtext_unittest/test_functional.py diff --git a/test/test_transforms.py b/test/torchtext_unittest/test_transforms.py similarity index 100% rename from test/test_transforms.py rename to test/torchtext_unittest/test_transforms.py diff --git a/test/test_utils.py b/test/torchtext_unittest/test_utils.py similarity index 98% rename from test/test_utils.py rename to test/torchtext_unittest/test_utils.py --- a/test/test_utils.py +++ b/test/torchtext_unittest/test_utils.py @@ -5,9 +5,9 @@ import unittest from urllib.parse import urljoin -from test.common.assets import conditional_remove, get_asset_path from torchtext import _TEXT_BUCKET from torchtext import utils +from torchtext_unittest.common.assets import conditional_remove, get_asset_path from .common.torchtext_test_case import TorchtextTestCase diff --git a/test/test_vocab.py b/test/torchtext_unittest/test_vocab.py similarity index 99% rename from test/test_vocab.py rename to test/torchtext_unittest/test_vocab.py --- a/test/test_vocab.py +++ b/test/torchtext_unittest/test_vocab.py @@ -4,8 +4,8 @@ import pytest import torch -from test.common.torchtext_test_case import TorchtextTestCase from torchtext.vocab import build_vocab_from_iterator, vocab +from torchtext_unittest.common.torchtext_test_case import TorchtextTestCase class TestVocab(TorchtextTestCase):
Error running unit tests when building with setup.py install ## 🐛 Bug **Describe the bug** A clear and concise description of what the bug is. When building with python setup.py install, running pytest from either the project root directory or the test/ directory causes the error `ImportError: torchtext C++ Extension is not found`. This can be worked-around by renaming the torchtext subdirectory, or by instead using python setup.py develop like the CI does (see .circleci/unittest/linux/scripts/install.sh#L36). **To Reproduce** Steps to reproduce the behavior: 1. Follow the build steps like normal, running python setup.py install 2. Run pytest 3. Every test fails with the error `ImportError: torchtext C++ Extension is not found`. **Expected behavior** A clear and concise description of what you expected to happen. The tests should succeed even when installing with setup.py install, either running pytest from the project root or the test/ directory (this is the case in pytorch) without having to rename the torchtext subdirectory. **Screenshots** If applicable, add screenshots to help explain your problem. **Environment** Please copy and paste the output from our [environment collection script](https://raw.githubusercontent.com/pytorch/pytorch/master/torch/utils/collect_env.py) (or fill out the checklist below manually). You can get the script and run it with: ``` wget https://raw.githubusercontent.com/pytorch/pytorch/master/torch/utils/collect_env.py # For security purposes, please check the contents of collect_env.py before running it. python collect_env.py python -c "import torchtext; print(\"torchtext version is \", torchtext.__version__)" ``` - PyTorch Version (e.g., 1.0): 1.12 - OS (e.g., Linux): Linux - How you installed PyTorch (`conda`, `pip`, source): Compiled from source - Build command you used (if compiling from source): python3 ./setup.py install - Python version: 3.7.13 - CUDA/cuDNN version: ROCm version 5.2 - GPU models and configuration: N/A - Any other relevant information: **Additional context** Add any other context about the problem here.
https://github.com/pytorch/text/pull/1874 resolves this. Hi @parmeet. While installing torchdata does satisfy one of the testing requirements, I'm still running into the problem where the tests will error out with `ImportError: torchtext C++ Extension is not found` if I build with `setup.py install` instead of `setup.py develop`. Is there any way to fix this issue? > Hi @parmeet. While installing torchdata does satisfy one of the testing requirements, I'm still running into the problem where the tests will error out with `ImportError: torchtext C++ Extension is not found` if I build with `setup.py install` instead of `setup.py develop`. Is there any way to fix this issue? This happens because the source code directory shadows the installed package. One proper fix is to introduce intermediate directory and put all the unit test code in there. In TorchAudio, unit test codes are placed in `torchaudio_unittest` directory. There was a PR to do this clean up but it got staled. https://github.com/pytorch/text/pull/1223 cc @Nayef211
2022-08-31T04:50:01
pytorch/text
1,898
pytorch__text-1898
[ "1883" ]
67d26928d2bba65a22666ae6b2e3bd3fdaee8c7d
diff --git a/torchtext/transforms.py b/torchtext/transforms.py --- a/torchtext/transforms.py +++ b/torchtext/transforms.py @@ -564,21 +564,31 @@ class BERTTokenizer(Module): :type strip_accents: Optional[bool] :param return_tokens: Indicate whether to return tokens. If false, returns corresponding token IDs as strings (default: False) :type return_tokens: bool + :param never_split: Collection of tokens which will not be split during tokenization. (default: None) + :type never_split: Optional[List[str]] """ __jit_unused_properties__ = ["is_jitable"] def __init__( - self, vocab_path: str, do_lower_case: bool = True, strip_accents: Optional[bool] = None, return_tokens=False + self, + vocab_path: str, + do_lower_case: bool = True, + strip_accents: Optional[bool] = None, + return_tokens=False, + never_split: Optional[List[str]] = None, ) -> None: super().__init__() + if never_split is None: + never_split = [] self.bert_model = BERTEncoderPyBind( - get_asset_local_path(vocab_path, overwite=True), do_lower_case, strip_accents + get_asset_local_path(vocab_path, overwite=True), do_lower_case, strip_accents, never_split ) self._return_tokens = return_tokens self._vocab_path = vocab_path self._do_lower_case = do_lower_case self._strip_accents = strip_accents + self._never_split = never_split @property def is_jitable(self): @@ -654,7 +664,7 @@ def __prepare_scriptable__(self): if not self.is_jitable: tokenizer_copy = deepcopy(self) tokenizer_copy.bert_model = torch.classes.torchtext.BERTEncoder( - self._vocab_path, self._do_lower_case, self._strip_accents + self._vocab_path, self._do_lower_case, self._strip_accents, self._never_split ) return tokenizer_copy
diff --git a/test/torchtext_unittest/test_transforms.py b/test/torchtext_unittest/test_transforms.py --- a/test/torchtext_unittest/test_transforms.py +++ b/test/torchtext_unittest/test_transforms.py @@ -1,5 +1,6 @@ import os from collections import OrderedDict +from typing import List, Optional from unittest.mock import patch import torch @@ -586,7 +587,9 @@ def test_clip_tokenizer_save_load_torchscript(self) -> None: class TestBERTTokenizer(TorchtextTestCase): - def _load_tokenizer(self, test_scripting: bool, do_lower_case: bool, return_tokens: bool): + def _load_tokenizer( + self, test_scripting: bool, do_lower_case: bool, return_tokens: bool, never_split: Optional[List[str]] = None + ): if do_lower_case: vocab_file = "bert_base_uncased_vocab.txt" else: @@ -596,46 +599,117 @@ def _load_tokenizer(self, test_scripting: bool, do_lower_case: bool, return_toke vocab_path=get_asset_path(vocab_file), do_lower_case=do_lower_case, return_tokens=return_tokens, + never_split=never_split, ) if test_scripting: tokenizer = torch.jit.script(tokenizer) return tokenizer - def _bert_tokenizer(self, tokenizer, do_lower_case): + def _bert_tokenizer(self, tokenizer, do_lower_case, never_split: Optional[List[str]] = None): sample_texts = [ "Hello World!, how are you?", "Hélló WoŕlḊ¿", "Respublica superiorem", "Avdija Vršajević în", + " \tHeLLo!how \n Are yoU? [UNK]", + "hi world [UNK] [CLS]", + "testing, [UNK] words! [SEP]", ] - if do_lower_case: - expected_tokens = [ - ["hello", "world", "!", ",", "how", "are", "you", "?"], - ["hello", "world", "¿"], - ["res", "##pu", "##bl", "##ica", "superior", "##em"], - ["av", "##di", "##ja", "vr", "##sa", "##jevic", "in"], - ] - expected_token_ids = [ - ["7592", "2088", "999", "1010", "2129", "2024", "2017", "1029"], - ["7592", "2088", "1094"], - ["24501", "14289", "16558", "5555", "6020", "6633"], - ["20704", "4305", "3900", "27830", "3736", "26782", "1999"], - ] + if not never_split: + if do_lower_case: + expected_tokens = [ + ["hello", "world", "!", ",", "how", "are", "you", "?"], + ["hello", "world", "¿"], + ["res", "##pu", "##bl", "##ica", "superior", "##em"], + ["av", "##di", "##ja", "vr", "##sa", "##jevic", "in"], + ["hello", "!", "how", "are", "you", "?", "[", "un", "##k", "]"], + ["hi", "world", "[", "un", "##k", "]", "[", "cl", "##s", "]"], + ["testing", ",", "[", "un", "##k", "]", "words", "!", "[", "sep", "]"], + ] + expected_token_ids = [ + ["7592", "2088", "999", "1010", "2129", "2024", "2017", "1029"], + ["7592", "2088", "1094"], + ["24501", "14289", "16558", "5555", "6020", "6633"], + ["20704", "4305", "3900", "27830", "3736", "26782", "1999"], + ["7592", "999", "2129", "2024", "2017", "1029", "1031", "4895", "2243", "1033"], + ["7632", "2088", "1031", "4895", "2243", "1033", "1031", "18856", "2015", "1033"], + ["5604", "1010", "1031", "4895", "2243", "1033", "2616", "999", "1031", "19802", "1033"], + ] + else: + expected_tokens = [ + ["Hello", "World", "!", ",", "how", "are", "you", "?"], + ["H", "##é", "##ll", "##ó", "[UNK]", "¿"], + ["Re", "##sp", "##ub", "##lica", "superior", "##em"], + ["A", "##v", "##di", "##ja", "V", "##r", "##ša", "##je", "##vić", "î", "##n"], + ["He", "##LL", "##o", "!", "how", "Are", "yo", "##U", "?", "[", "UN", "##K", "]"], + ["hi", "world", "[", "UN", "##K", "]", "[", "C", "##LS", "]"], + ["testing", ",", "[", "UN", "##K", "]", "words", "!", "[", "SE", "##P", "]"], + ] + expected_token_ids = [ + ["8667", "1291", "106", "117", "1293", "1132", "1128", "136"], + ["145", "2744", "2339", "7774", "100", "225"], + ["11336", "20080", "10354", "9538", "7298", "5521"], + ["138", "1964", "3309", "3174", "159", "1197", "23834", "5561", "10225", "260", "1179"], + [ + "1124", + "23955", + "1186", + "106", + "1293", + "2372", + "26063", + "2591", + "136", + "164", + "7414", + "2428", + "166", + ], + ["20844", "1362", "164", "7414", "2428", "166", "164", "140", "15928", "166"], + ["5193", "117", "164", "7414", "2428", "166", "1734", "106", "164", "12342", "2101", "166"], + ] else: - expected_tokens = [ - ["Hello", "World", "!", ",", "how", "are", "you", "?"], - ["H", "##é", "##ll", "##ó", "[UNK]", "¿"], - ["Re", "##sp", "##ub", "##lica", "superior", "##em"], - ["A", "##v", "##di", "##ja", "V", "##r", "##ša", "##je", "##vić", "î", "##n"], - ] - expected_token_ids = [ - ["8667", "1291", "106", "117", "1293", "1132", "1128", "136"], - ["145", "2744", "2339", "7774", "100", "225"], - ["11336", "20080", "10354", "9538", "7298", "5521"], - ["138", "1964", "3309", "3174", "159", "1197", "23834", "5561", "10225", "260", "1179"], - ] + if do_lower_case: + expected_tokens = [ + ["hello", "world", "!", ",", "how", "are", "you", "?"], + ["hello", "world", "¿"], + ["res", "##pu", "##bl", "##ica", "superior", "##em"], + ["av", "##di", "##ja", "vr", "##sa", "##jevic", "in"], + ["hello", "!", "how", "are", "you", "?", "[UNK]"], + ["hi", "world", "[UNK]", "[CLS]"], + ["testing", ",", "[UNK]", "words", "!", "[", "sep", "]"], + ] + expected_token_ids = [ + ["7592", "2088", "999", "1010", "2129", "2024", "2017", "1029"], + ["7592", "2088", "1094"], + ["24501", "14289", "16558", "5555", "6020", "6633"], + ["20704", "4305", "3900", "27830", "3736", "26782", "1999"], + ["7592", "999", "2129", "2024", "2017", "1029", "100"], + ["7632", "2088", "100", "101"], + ["5604", "1010", "100", "2616", "999", "1031", "19802", "1033"], + ] + + else: + expected_tokens = [ + ["Hello", "World", "!", ",", "how", "are", "you", "?"], + ["H", "##é", "##ll", "##ó", "[UNK]", "¿"], + ["Re", "##sp", "##ub", "##lica", "superior", "##em"], + ["A", "##v", "##di", "##ja", "V", "##r", "##ša", "##je", "##vić", "î", "##n"], + ["He", "##LL", "##o", "!", "how", "Are", "yo", "##U", "?", "[UNK]"], + ["hi", "world", "[UNK]", "[CLS]"], + ["testing", ",", "[UNK]", "words", "!", "[", "SE", "##P", "]"], + ] + expected_token_ids = [ + ["8667", "1291", "106", "117", "1293", "1132", "1128", "136"], + ["145", "2744", "2339", "7774", "100", "225"], + ["11336", "20080", "10354", "9538", "7298", "5521"], + ["138", "1964", "3309", "3174", "159", "1197", "23834", "5561", "10225", "260", "1179"], + ["1124", "23955", "1186", "106", "1293", "2372", "26063", "2591", "136", "100"], + ["20844", "1362", "100", "101"], + ["5193", "117", "100", "1734", "106", "164", "12342", "2101", "166"], + ] # test batch of sentences if tokenizer._return_tokens: @@ -650,14 +724,18 @@ def _bert_tokenizer(self, tokenizer, do_lower_case): else: self.assertEqual(tokenizer(txt), expected_token_ids[idx]) - @nested_params([True, False], [True, False], [True, False]) - def test_bert_tokenizer(self, test_scripting, do_lower_case, return_tokens): + @nested_params([True, False], [True, False], [True, False], [[], None, ["[UNK]", "[CLS]"]]) + def test_bert_tokenizer(self, test_scripting, do_lower_case, return_tokens, never_split): """test tokenization on single sentence input as well as batch on sentences""" self._bert_tokenizer( self._load_tokenizer( - test_scripting=test_scripting, do_lower_case=do_lower_case, return_tokens=return_tokens + test_scripting=test_scripting, + do_lower_case=do_lower_case, + return_tokens=return_tokens, + never_split=never_split, ), do_lower_case=do_lower_case, + never_split=never_split, ) @nested_params([True, False], [True, False], [True, False])
Add `never_split` kwarg to BERTTokenizer to achieve parity with `transformers.BertTokenizer` ## 🚀 Feature Add functionality to BERTTokenizer so that it does not split/tokenize special tokens like regular words. **Motivation** The HuggingFace [BertTokenizer](https://github.com/huggingface/transformers/blob/bbbb453e5869a5fec4925b02f1265c9e6bfc3ebb/src/transformers/models/bert/tokenization_bert.py#L137) is able to recognize its own special tokens and ensure that they are not split during the tokenization process. For example, if given the following input: ``` "\tHeLLo!how \n Are yoU? [UNK]" ``` The HuggingFace (HF) tokenizer returns the "[UNK]" token un-split, whereas the TorchText (TT) tokenizer returns it split: ``` HF (expected): ['hello', '!', 'how', 'are', 'you', '?', '[UNK]'] TT (actual): ['hello', '!', 'how', 'are', 'you', '?', '[', 'un', '##k', ']'] ``` **Pitch** A `never_split` keyword argument at the constructor-level which enables the user to specify which tokens to ignore during tokenization. Such a keyword argument would be flexible and give the user the freedom to adapt to various other tokenization schemes. An example interface: ``` tt_tokenizer = BERTTokenizer( vocab_path=vocab_file, do_lower_case=True, return_tokens=True, never_split=[ "[UNK]", "[CLS]", "[SEP]", "[PAD]", ], ) ``` This closely matches the existing HuggingFace BertTokenizer interface (constructor level kwarg [here](https://github.com/huggingface/transformers/blob/bbbb453e5869a5fec4925b02f1265c9e6bfc3ebb/src/transformers/models/bert/tokenization_bert.py#L189), `tokenize` function implementation [here](https://github.com/huggingface/transformers/blob/bbbb453e5869a5fec4925b02f1265c9e6bfc3ebb/src/transformers/models/bert/tokenization_bert.py#L244)). If the user were able to instantiate the HuggingFace tokenizer with which they were attempting to achieve parity, the user could trivially assign the `never_split` keyword argument to its special tokens: ``` import transformers hf_tokenizer = transformers.AutoTokenizer.from_pretrained("bert-base-uncased") tt_tokenizer = BERTTokenizer( vocab_path=vocab_file, do_lower_case=True, return_tokens=True, never_split=hf_tokenizer.all_special_tokens, ) ``` **Alternatives** None that are more straightforward than this. **Additional context** A full reproduction of the above disparity in functionality, as well as a comment about the requested interface can be found in this Gist: https://gist.github.com/geoffreyangus/7b4c04f1e485c9c4091728bff1414134
2022-09-13T20:23:30
pytorch/text
1,912
pytorch__text-1912
[ "1904" ]
9b06d563f5a513081642b37a6a3b1b12a24eb8b0
diff --git a/torchtext/datasets/multi30k.py b/torchtext/datasets/multi30k.py --- a/torchtext/datasets/multi30k.py +++ b/torchtext/datasets/multi30k.py @@ -12,11 +12,10 @@ from torchdata.datapipes.iter import FileOpener, IterableWrapper from torchtext._download_hooks import HttpReader -# TODO: Update URL to original once the server is back up (see https://github.com/pytorch/text/issues/1756) URL = { - "train": r"https://raw.githubusercontent.com/neychev/small_DL_repo/master/datasets/Multi30k/training.tar.gz", - "valid": r"https://raw.githubusercontent.com/neychev/small_DL_repo/master/datasets/Multi30k/validation.tar.gz", - "test": r"https://raw.githubusercontent.com/neychev/small_DL_repo/master/datasets/Multi30k/mmt16_task1_test.tar.gz", + "train": "http://www.quest.dcs.shef.ac.uk/wmt16_files_mmt/training.tar.gz", + "valid": "http://www.quest.dcs.shef.ac.uk/wmt16_files_mmt/validation.tar.gz", + "test": "http://www.quest.dcs.shef.ac.uk/wmt16_files_mmt/mmt16_task1_test.tar.gz", } MD5 = {
diff --git a/test/torchtext_unittest/prototype/test_functional.py b/test/torchtext_unittest/prototype/test_functional.py --- a/test/torchtext_unittest/prototype/test_functional.py +++ b/test/torchtext_unittest/prototype/test_functional.py @@ -1,6 +1,4 @@ import os -import platform -import unittest import torch import torchtext.data as data @@ -10,8 +8,6 @@ class TestFunctional(TorchtextTestCase): - # TODO(Nayef211): remove decorator once https://github.com/pytorch/pytorch/issues/38207 is closed - @unittest.skipIf(platform.system() == "Windows", "Test is known to fail on Windows.") def test_BasicEnglishNormalize(self) -> None: test_sample = "'\".<br />,()!?;: Basic English Normalization for a Line of Text '\".<br />,()!?;:" ref_results = [
todo-decorator-remove-solved Removed the code as the issue is closed.
@arnavmehta7 thanks for creating this! Can you please fix the [linter issues](https://app.circleci.com/pipelines/github/pytorch/text/6752/workflows/6d68e250-d994-490d-bc96-f5fd360f4a81/jobs/233009) that show up on CI before we merge the PR? @Nayef211 Thanks, I've tried to do that but I'm still unable to do so. I'm quite new to opensource. I'd be grateful if you can tell me how do I correct that. EDIT:- I ran ```pre-commit ``` to find the solution. How can I fix these MacOS build issues? > How can I fix these MacOS build issues? This was fixed by https://github.com/pytorch/text/pull/1889 and should be fixed in your PR once you rebase on the latest main branch. > > How can I fix these MacOS build issues? > > This was fixed by #1889 and should be fixed in your PR once you rebase on the latest main branch. Would I need to sync again then do these changes again? EDIT: JUST TRYING THAT Still MacOS errors? Can you point out my mistake, I'm extremely sorry if I have done something wrong EDIT: Still 3 errors :( > Still MacOS errors? Can you point out my mistake, I'm extremely sorry if I have done something wrong > > EDIT: Still 3 errors :( @arnavmehta7 the current failures are not related to your changes and are caused by flaky tests. Thanks again for working on this. I think you might need to merge in the latest changes from the main branch again since it looks like some of the changes from the latest commits are not reflected in your PR. @Nayef211 Thanks for guidance, I've done that already :D @Nayef211 Hey, It is working.
2022-09-26T22:09:15
pytorch/text
1,914
pytorch__text-1914
[ "1911" ]
5c48f4a4e9f4691428de7582041115876b9368c5
diff --git a/torchtext/datasets/imdb.py b/torchtext/datasets/imdb.py --- a/torchtext/datasets/imdb.py +++ b/torchtext/datasets/imdb.py @@ -20,6 +20,8 @@ "test": 25000, } +MAP_LABELS = {"neg": 1, "pos": 2} + _PATH = "aclImdb_v1.tar.gz" DATASET_NAME = "IMDB" @@ -50,7 +52,7 @@ def _cache_filepath_fn(root, decompressed_folder, split, x): def _modify_res(t): - return Path(t[0]).parts[-1], t[1] + return MAP_LABELS[Path(t[0]).parts[-1]], t[1] def filter_imdb_data(key, fname):
diff --git a/test/torchtext_unittest/datasets/test_imdb.py b/test/torchtext_unittest/datasets/test_imdb.py --- a/test/torchtext_unittest/datasets/test_imdb.py +++ b/test/torchtext_unittest/datasets/test_imdb.py @@ -29,8 +29,8 @@ def _get_mock_dataset(root_dir): for i in range(5): # all negative labels are read first before positive labels in the # IMDB dataset implementation - label = "neg" if i < 2 else "pos" - cur_dir = pos_dir if label == "pos" else neg_dir + label = 1 if i < 2 else 2 + cur_dir = pos_dir if label == 2 else neg_dir txt_file = os.path.join(cur_dir, f"{i}{i}_{i}.txt") with open(txt_file, "w", encoding="utf-8") as f: rand_string = get_random_unicode(seed)
update documentation to reflect IMDB output When attempting to use the IMDB api, I got results that were different from what the docs suggested. This PR attempts to update the docs with the correct output of the IMDB api.
@acxz I think this might have been an oversight when the dataset was implemented. To be consistent with our other text classification dataset, we do want to return labels as integers. If you want to take this on, it would be as simple as adding a `MAP_LABELS` similar to how we do it in the QNLI dataset. https://github.com/pytorch/text/blob/fd49d42c6c90fc4b556b63227f3509292bbdba11/torchtext/datasets/qnli.py#L40 And then we can do a simple label lookup in the `_modify_res` method like so https://github.com/pytorch/text/blob/fd49d42c6c90fc4b556b63227f3509292bbdba11/torchtext/datasets/qnli.py#L59 Ah I see, I'll take a stab at this in the upcoming weekend. Thanks for the implementation pointers. @acxz lmk if you still plan on taking this on, otherwise I'm happy to submit a PR for it this week 😄 Yeah, actually if you could take it on that would be great. Ended up traveling this weekend and this week is looking a bit busy. Thanks for that!
2022-09-27T17:00:45
pytorch/text
2,102
pytorch__text-2102
[ "2002" ]
db26565394efeee55669ff843b51cb5608b17ae8
diff --git a/torchtext/models/roberta/bundler.py b/torchtext/models/roberta/bundler.py --- a/torchtext/models/roberta/bundler.py +++ b/torchtext/models/roberta/bundler.py @@ -160,16 +160,35 @@ def encoderConf(self) -> RobertaEncoderConf: return self._encoder_conf -XLMR_BASE_ENCODER = RobertaBundle( - _path=urljoin(_TEXT_BUCKET, "xlmr.base.encoder.pt"), - _encoder_conf=RobertaEncoderConf(vocab_size=250002), - transform=lambda: T.Sequential( +def xlmr_transform(truncate_length: int) -> Module: + """Standard transform for XLMR models.""" + return T.Sequential( T.SentencePieceTokenizer(urljoin(_TEXT_BUCKET, "xlmr.sentencepiece.bpe.model")), T.VocabTransform(load_state_dict_from_url(urljoin(_TEXT_BUCKET, "xlmr.vocab.pt"))), - T.Truncate(254), + T.Truncate(truncate_length), T.AddToken(token=0, begin=True), T.AddToken(token=2, begin=False), - ), + ) + + +def roberta_transform(truncate_length: int) -> Module: + """Standard transform for RoBERTa models.""" + return T.Sequential( + T.GPT2BPETokenizer( + encoder_json_path=urljoin(_TEXT_BUCKET, "gpt2_bpe_encoder.json"), + vocab_bpe_path=urljoin(_TEXT_BUCKET, "gpt2_bpe_vocab.bpe"), + ), + T.VocabTransform(load_state_dict_from_url(urljoin(_TEXT_BUCKET, "roberta.vocab.pt"))), + T.Truncate(truncate_length), + T.AddToken(token=0, begin=True), + T.AddToken(token=2, begin=False), + ) + + +XLMR_BASE_ENCODER = RobertaBundle( + _path=urljoin(_TEXT_BUCKET, "xlmr.base.encoder.pt"), + _encoder_conf=RobertaEncoderConf(vocab_size=250002), + transform=lambda: xlmr_transform(254), ) XLMR_BASE_ENCODER.__doc__ = """ @@ -193,13 +212,7 @@ def encoderConf(self) -> RobertaEncoderConf: _encoder_conf=RobertaEncoderConf( vocab_size=250002, embedding_dim=1024, ffn_dimension=4096, num_attention_heads=16, num_encoder_layers=24 ), - transform=lambda: T.Sequential( - T.SentencePieceTokenizer(urljoin(_TEXT_BUCKET, "xlmr.sentencepiece.bpe.model")), - T.VocabTransform(load_state_dict_from_url(urljoin(_TEXT_BUCKET, "xlmr.vocab.pt"))), - T.Truncate(510), - T.AddToken(token=0, begin=True), - T.AddToken(token=2, begin=False), - ), + transform=lambda: xlmr_transform(510), ) XLMR_LARGE_ENCODER.__doc__ = """ @@ -221,16 +234,7 @@ def encoderConf(self) -> RobertaEncoderConf: ROBERTA_BASE_ENCODER = RobertaBundle( _path=urljoin(_TEXT_BUCKET, "roberta.base.encoder.pt"), _encoder_conf=RobertaEncoderConf(vocab_size=50265), - transform=lambda: T.Sequential( - T.GPT2BPETokenizer( - encoder_json_path=urljoin(_TEXT_BUCKET, "gpt2_bpe_encoder.json"), - vocab_bpe_path=urljoin(_TEXT_BUCKET, "gpt2_bpe_vocab.bpe"), - ), - T.VocabTransform(load_state_dict_from_url(urljoin(_TEXT_BUCKET, "roberta.vocab.pt"))), - T.Truncate(254), - T.AddToken(token=0, begin=True), - T.AddToken(token=2, begin=False), - ), + transform=lambda: roberta_transform(254), ) ROBERTA_BASE_ENCODER.__doc__ = """ @@ -263,16 +267,7 @@ def encoderConf(self) -> RobertaEncoderConf: num_attention_heads=16, num_encoder_layers=24, ), - transform=lambda: T.Sequential( - T.GPT2BPETokenizer( - encoder_json_path=urljoin(_TEXT_BUCKET, "gpt2_bpe_encoder.json"), - vocab_bpe_path=urljoin(_TEXT_BUCKET, "gpt2_bpe_vocab.bpe"), - ), - T.VocabTransform(load_state_dict_from_url(urljoin(_TEXT_BUCKET, "roberta.vocab.pt"))), - T.Truncate(510), - T.AddToken(token=0, begin=True), - T.AddToken(token=2, begin=False), - ), + transform=lambda: roberta_transform(510), ) ROBERTA_LARGE_ENCODER.__doc__ = """ @@ -302,16 +297,7 @@ def encoderConf(self) -> RobertaEncoderConf: num_encoder_layers=6, padding_idx=1, ), - transform=lambda: T.Sequential( - T.GPT2BPETokenizer( - encoder_json_path=urljoin(_TEXT_BUCKET, "gpt2_bpe_encoder.json"), - vocab_bpe_path=urljoin(_TEXT_BUCKET, "gpt2_bpe_vocab.bpe"), - ), - T.VocabTransform(load_state_dict_from_url(urljoin(_TEXT_BUCKET, "roberta.vocab.pt"))), - T.Truncate(510), - T.AddToken(token=0, begin=True), - T.AddToken(token=2, begin=False), - ), + transform=lambda: roberta_transform(510), ) ROBERTA_DISTILLED_ENCODER.__doc__ = """
Change transforms in RoBERTa into classes Currently, transforms in the RobertaBundle are defined as anonymous lambda functions. These are not pickleable and cannot be imported for use anywhere else. Ex proposal: ``` lambda: T.Sequential( T.SentencePieceTokenizer(urljoin(_TEXT_BUCKET, "xlmr.sentencepiece.bpe.model")), T.VocabTransform(load_state_dict_from_url(urljoin(_TEXT_BUCKET, "xlmr.vocab.pt"))), T.Truncate(510), T.AddToken(token=0, begin=True), T.AddToken(token=2, begin=False), ), ``` --> ``` class RobertaTransform: def __init__(self, truncate_length=510): self.transform = T.Sequential( T.SentencePieceTokenizer(urljoin(_TEXT_BUCKET, "xlmr.sentencepiece.bpe.model")), T.VocabTransform(load_state_dict_from_url(urljoin(_TEXT_BUCKET, "xlmr.vocab.pt"))), T.Truncate(truncate_length), T.AddToken(token=0, begin=True), T.AddToken(token=2, begin=False), ), def __call__(self, text): self.transform(text) ```
2023-03-08T18:53:35
pytorch/text
2,144
pytorch__text-2144
[ "2140" ]
df95462c562393946aea7f30608e47c69ea3ff58
diff --git a/torchtext/vocab/vectors.py b/torchtext/vocab/vectors.py --- a/torchtext/vocab/vectors.py +++ b/torchtext/vocab/vectors.py @@ -64,6 +64,9 @@ def __getitem__(self, token): else: return self.unk_init(torch.Tensor(self.dim)) + def __contains__(self, token): + return token in self.stoi + def cache(self, name, cache, url=None, max_vectors=None): import ssl
Implementing __contains__ for vocab.Vectors class ## 🚀 Feature Isn't it better to implement \_\_contains\_\_ for Vectors class? In this way, one can easily find out whether a vocab is in the self.itos or not.
Thanks for opening an issue @saeeddhqan! If you want to propose this feature, we can help with testing and approving.
2023-04-05T16:58:54
pytorch/text
2,195
pytorch__text-2195
[ "2189" ]
b5e2a1b0a7a0c570ddef4008bc67773042415e0f
diff --git a/torchtext/datasets/iwslt2017.py b/torchtext/datasets/iwslt2017.py --- a/torchtext/datasets/iwslt2017.py +++ b/torchtext/datasets/iwslt2017.py @@ -11,7 +11,7 @@ _wrap_split_argument, ) -URL = "https://drive.google.com/u/0/uc?id=12ycYSzLIG253AFN35Y6qoyf9wtkOjakp" +URL = "https://fbk.sharepoint.com/sites/MTUnit/_layouts/15/download.aspx?SourceUrl=%2Fsites%2FMTUnit%2FShared%20Documents%2Fwebsites%2FWIT3%2Dlibrary%2F2017%2D01%2Dtrnmted%2Etgz" _PATH = "2017-01-trnmted.tgz" MD5 = "aca701032b1c4411afc4d9fa367796ba"
404 Client Error in IWSLT2017 and IWSLT2016 ## 🐛 Bug ``` from torchtext.vocab import build_vocab_from_iterator special_symbols = ['<unk>', '<pad>', '<bos>', '<eos>'] def yield_tokens(data_iter: Iterable) -> List[str]: for data_sample in data_iter: yield token_transform(data_sample) train_iter = IWSLT2017(split="train") build_vocab_from_iterator(yield_tokens(train_iter), min_freq=1, specials=special_symbols, special_first=True) ``` When I run above code, it shows below error: `requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://drive.google.com/uc?id=12ycYSzLIG253AFN35Y6qoyf9wtkOjakp` I think some download link for the data is broken.
2023-07-29T12:51:04
mozilla/telemetry-analysis-service
228
mozilla__telemetry-analysis-service-228
[ "227" ]
ceeb9064705e0f9d4e01555308c5febe05ee7c4b
diff --git a/atmo/jobs/models.py b/atmo/jobs/models.py --- a/atmo/jobs/models.py +++ b/atmo/jobs/models.py @@ -210,8 +210,8 @@ def run(self): def terminate(self): """Stop the currently running scheduled Spark job.""" - if self.current_run_jobflow_id: - self.provisioner.stop(self.current_run_jobflow_id) + if self.is_expired and self.current_run_jobflow_id: + self.cluster_provisioner.stop(self.current_run_jobflow_id) def cleanup(self): """Remove the Spark job notebook file from S3"""
diff --git a/tests/test_jobs.py b/tests/test_jobs.py --- a/tests/test_jobs.py +++ b/tests/test_jobs.py @@ -14,6 +14,16 @@ from atmo.jobs import models [email protected] +def cluster_provisioner_mocks(mocker): + return { + 'stop': mocker.patch( + 'atmo.clusters.provisioners.ClusterProvisioner.stop', + return_value=None, + ), + } + + @pytest.fixture def sparkjob_provisioner_mocks(mocker): return { @@ -393,6 +403,8 @@ def test_spark_job_second_run_should_run(now, test_user): def test_spark_job_is_expired(now, test_user): + # Test that a spark job `is_expired` if it has run for longer than + # its timeout. spark_job = models.SparkJob.objects.create( identifier='test-spark-job-6', description='description', @@ -405,9 +417,6 @@ def test_spark_job_is_expired(now, test_user): created_by=test_user, current_run_jobflow_id='my-jobflow-id', ) - # A spark job expires if: - # or has run before and finished (or not) - # it hasn't run for longer than its timeout timeout_run_date = now - timedelta(hours=12) running_status = Cluster.STATUS_RUNNING @@ -438,6 +447,37 @@ def test_spark_job_is_expired(now, test_user): assert spark_job.is_expired +def test_spark_job_terminates(now, test_user, cluster_provisioner_mocks): + # Test that a spark job's `terminate` tells the EMR to terminate correctly. + spark_job = models.SparkJob.objects.create( + identifier='test-spark-job-7', + description='description', + notebook_s3_key=u'jobs/test-spark-job/test-notebook.ipynb', + result_visibility='private', + size=5, + interval_in_hours=1, + job_timeout=12, + start_date=now - timedelta(days=1), + created_by=test_user, + current_run_jobflow_id='jobflow-id', + ) + + timeout_run_date = now - timedelta(hours=12) + running_status = Cluster.STATUS_RUNNING + + # Test job does not terminate if not expired. + spark_job.last_run_date = timeout_run_date + timedelta(seconds=1) + spark_job.most_recent_status = running_status + spark_job.terminate() + cluster_provisioner_mocks['stop'].assert_not_called() + + # Test job terminates when expired. + spark_job.last_run_date = timeout_run_date + spark_job.most_recent_status = running_status + spark_job.terminate() + cluster_provisioner_mocks['stop'].assert_called_with(u'jobflow-id') + + def test_check_identifier_taken(client, test_user): # create a test job to edit later identifier = 'test-spark-job'
AttributeError: 'SparkJobProvisioner' object has no attribute 'stop' While testing locally in a branch I bumped into this. I didn't test it on master but looking at the code this seems like it may also be a problem. The `SparkJob.terminate` calls `self.provisioner.stop(self.current_run_jobflow_id)`, where `self.provisioner` is a `SparkJobProvisioner`. But currently the `SparkJobProvisioner` has no `stop` method and neither does the parent class, it is only defined on the `ClusterProvisioner`. In my branch I changed the `terminate` method to call `self.cluster_provisioner.stop` instead and it fixed my issue locally.
2017-02-14T01:37:00
mozilla/telemetry-analysis-service
246
mozilla__telemetry-analysis-service-246
[ "245" ]
4149afcf7b4c1866f91fd3af3205c9326cd728fc
diff --git a/atmo/worker.py b/atmo/worker.py new file mode 100644 --- /dev/null +++ b/atmo/worker.py @@ -0,0 +1,26 @@ +from django.db import connections, DatabaseError, InterfaceError +from rq_retry import RetryWorker + + +class ConnectionClosingRetryWorker(RetryWorker): + def close_database(self): + for connection in connections.all(): + try: + connection.close() + except InterfaceError: + pass + except DatabaseError as exc: + str_exc = str(exc) + if 'closed' not in str_exc and 'not connected' not in str_exc: + raise + + def perform_job(self, *args, **kwargs): + self.close_database() + try: + return super().perform_job(*args, **kwargs) + finally: + self.close_database() + + def work(self, *args, **kwargs): + self.close_database() + return super().work(*args, **kwargs)
Handle dropped database connections gracefully In https://sentry.prod.mozaws.net/operations/atmo-stage/issues/383510/ we see that the database connection is closed prematurely and neither Django nor psycopg is able to recover from that. The error is well known to be related to using process fork with open connections: http://pythonhosted.org/psycopg2/usage.html#thread-safety This is related to https://github.com/ui/django-rq/issues/216 and https://github.com/celery/celery/blob/4d63867c8281e94c74dcdf84fe2a441eaed6671b/celery/fixups/django.py#L135-L192.
2017-02-20T12:30:50
mozilla/telemetry-analysis-service
258
mozilla__telemetry-analysis-service-258
[ "257" ]
95c7d56bdd878171d9b9bf84c549898c6dbebd18
diff --git a/atmo/clusters/views.py b/atmo/clusters/views.py --- a/atmo/clusters/views.py +++ b/atmo/clusters/views.py @@ -15,7 +15,13 @@ @login_required def new_cluster(request): - if request.user.created_sshkeys.count() == 0: + initial = { + 'identifier': '{}-telemetry-analysis'.format(user_display(request.user)), + 'size': 1, + } + ssh_key_count = request.user.created_sshkeys.count() + + if ssh_key_count == 0: messages.error( request, mark_safe( @@ -25,10 +31,10 @@ def new_cluster(request): ) ) return redirect('keys-new') - initial = { - 'identifier': '{}-telemetry-analysis'.format(user_display(request.user)), - 'size': 1, - } + elif ssh_key_count == 1: + # If only 1 ssh key, make it pre-selected. + initial['ssh_key'] = request.user.created_sshkeys.values('pk')[0]['pk'] + form = NewClusterForm( request.user, initial=initial,
diff --git a/tests/test_clusters.py b/tests/test_clusters.py --- a/tests/test_clusters.py +++ b/tests/test_clusters.py @@ -4,8 +4,10 @@ from datetime import timedelta import pytest -from django.utils import timezone +from allauth.account.utils import user_display +from django.contrib.messages import get_messages from django.core.urlresolvers import reverse +from django.utils import timezone from atmo.clusters import models @@ -32,6 +34,26 @@ def cluster_provisioner_mocks(mocker): } +def test_cluster_form_defaults(client, test_user, ssh_key): + response = client.post(reverse('clusters-new'), {}, follow=True) + + form = response.context['form'] + + assert form.errors + assert (form.initial['identifier'] == + '{}-telemetry-analysis'.format(user_display(test_user))) + assert form.initial['size'] == 1 + assert form.initial['ssh_key'] == ssh_key.id + + +def test_no_keys_redirect(client, test_user): + response = client.post(reverse('clusters-new'), {}, follow=True) + assert response.status_code == 200 + assert response.redirect_chain[-1] == (reverse('keys-new'), 302) + assert ('No SSH keys associated to you' in + [m for m in get_messages(response.wsgi_request)][0].message) + + def test_create_cluster(client, test_user, ssh_key, cluster_provisioner_mocks): start_date = timezone.now()
ATMO should pre-click my single SSH key Would save me thousands of milliseconds every time I launch a cluster ;)
2017-02-23T19:52:27
mozilla/telemetry-analysis-service
289
mozilla__telemetry-analysis-service-289
[ "284" ]
1f10ed2d3907be0169001c75e05f181fc3bf98a4
diff --git a/atmo/jobs/jobs.py b/atmo/jobs/jobs.py --- a/atmo/jobs/jobs.py +++ b/atmo/jobs/jobs.py @@ -1,9 +1,15 @@ # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, you can obtain one at http://mozilla.org/MPL/2.0/. +from django.db import transaction +import logging import newrelic.agent from .models import SparkJob +from atmo.clusters.models import Cluster +from atmo.clusters.provisioners import ClusterProvisioner + +logger = logging.getLogger(__name__) @newrelic.agent.background_task(group='RQ') @@ -11,20 +17,52 @@ def run_jobs(): """ Run all the scheduled tasks that are supposed to run. """ + # first let's update the job statuses if there are prior runs run_jobs = [] - for job in SparkJob.objects.all(): - # first let's update the status if there is a prior run - if job.latest_run: - job.latest_run.update_status() - - # then let's check if the job should be run at all - if job.should_run(): - job.run() - run_jobs.append(job.identifier) - - # and then check if the job is expired and terminate it if needed - if job.is_expired: - # This shouldn't be required as we set a timeout in the bootstrap script, - # but let's keep it as a guard. - job.terminate() + jobs = SparkJob.objects.all() + + # get the jobs with prior runs + jobs_with_active_runs = jobs.filter( + runs__status__in=Cluster.ACTIVE_STATUS_LIST, + ).prefetch_related('runs') + logger.debug('Updating Spark jobs: %s', jobs_with_active_runs) + + # create a map between the jobflow ids of the latest runs and the jobs + jobflow_job_map = { + job.latest_run.jobflow_id: job + for job in jobs_with_active_runs + } + # get the created dates of the job runs to limit the ListCluster API call + provisioner = ClusterProvisioner() + runs_created_at = jobs_with_active_runs.datetimes('runs__created_at', 'day') + logger.debug('Fetching clusters older than %s', runs_created_at[0]) + + cluster_list = provisioner.list(created_after=runs_created_at[0]) + logger.debug('Clusters found: %s', cluster_list) + + for cluster_info in cluster_list: + # filter out the clusters that don't relate to the job run ids + job = jobflow_job_map.get(cluster_info['jobflow_id'], None) + if job is None: + continue + logger.debug('Updating job status for %s, latest run %s', job, job.latest_run) + # update the latest run status + with transaction.atomic(): + job.latest_run.update_status(cluster_info) + + for job in jobs: + with transaction.atomic(): + # then let's check if the job should be run at all + should_run = job.should_run() + logger.debug('Checking if job %s should run: %s', job, should_run) + if should_run: + job.run() + run_jobs.append(job.identifier) + + # and then check if the job is expired and terminate it if needed + if job.is_expired: + logger.debug('Job %s is expired and is terminated', job) + # This shouldn't be required as we set a timeout in the bootstrap script, + # but let's keep it as a guard. + job.terminate() return run_jobs diff --git a/atmo/jobs/models.py b/atmo/jobs/models.py --- a/atmo/jobs/models.py +++ b/atmo/jobs/models.py @@ -154,6 +154,21 @@ def notebook_s3_object(self): def get_absolute_url(self): return reverse('jobs-detail', kwargs={'id': self.id}) + def is_due(self, now=None): + """ + Whether the scheduled Spark job is due to be run based on the + latest run and the configured interval in hours. + """ + if now is None: + now = timezone.now() + if not self.latest_run or self.latest_run.scheduled_date is None: + # job has never run before + hours_since_last_run = float('inf') + else: + hours_since_last_run = (now - self.latest_run.scheduled_date).total_seconds() // 3600 + + return hours_since_last_run >= self.interval_in_hours + def should_run(self): """Whether the scheduled Spark job should run.""" if not self.is_runnable: @@ -162,14 +177,11 @@ def should_run(self): active = self.start_date <= now if self.end_date is not None: active = active and self.end_date >= now - if not self.latest_run or self.latest_run.scheduled_date is None: - # job has never run before - hours_since_last_run = float('inf') - else: - hours_since_last_run = ( - (now - self.latest_run.scheduled_date).total_seconds() // 3600) - can_run_now = hours_since_last_run >= self.interval_in_hours - return self.is_enabled and active and can_run_now + return ( + self.is_enabled and + active and + self.is_due(now) + ) def run(self): """Actually run the scheduled Spark job.""" @@ -189,7 +201,7 @@ def run(self): run = self.runs.create( spark_job=self, jobflow_id=jobflow_id, - scheduled_date = timezone.now(), + scheduled_date=timezone.now(), ) # Remove the cached latest run to this objects will requery it. try: @@ -265,18 +277,18 @@ def __repr__(self): def get_info(self): return self.spark_job.cluster_provisioner.info(self.jobflow_id) - def update_status(self): + def update_status(self, info=None): """ Updates latest status and life cycle datetimes. """ - info = self.get_info() - if info is not None: - if self.status != info['state']: - self.status = info['state'] - if self.status == Cluster.STATUS_RUNNING: - self.run_date = timezone.now() - elif self.status in (Cluster.STATUS_TERMINATED, - Cluster.STATUS_TERMINATED_WITH_ERRORS): - self.terminated_date = timezone.now() - self.save() + if info is None: + info = self.get_info() + if self.status != info['state']: + self.status = info['state'] + if self.status == Cluster.STATUS_RUNNING: + self.run_date = timezone.now() + elif self.status in (Cluster.STATUS_TERMINATED, + Cluster.STATUS_TERMINATED_WITH_ERRORS): + self.terminated_date = timezone.now() + self.save() return self.status
Use list_cluster EMR API for updating job run status We currently facing lots of AWS API throttling when updating individual job run statuses before deciding to run them or not. We basically run one `describe_cluster` call per jobs per call against the `run_jobs` job.
2017-03-07T14:45:25
mozilla/telemetry-analysis-service
338
mozilla__telemetry-analysis-service-338
[ "337" ]
e69f31b969b46400729b1f3bb86a7de740839f01
diff --git a/atmo/settings.py b/atmo/settings.py --- a/atmo/settings.py +++ b/atmo/settings.py @@ -475,9 +475,14 @@ def LOGGING(self): 'handlers': ['console'], 'propagate': False, }, - 'request.summary': { + 'redbeat.schedulers': { + 'level': 'DEBUG', 'handlers': ['console'], + 'propagate': False, + }, + 'request.summary': { 'level': 'DEBUG', + 'handlers': ['console'], 'propagate': False, }, },
Configure readbeat.scheduler logger to use mozlog There is a logger in https://github.com/sibson/redbeat/blob/efc9491b2ffc6d9d544693143b42d771ec60f9c2/redbeat/schedulers.py#L61 that needs to be checked for using mozlog to show up in Kibana.
2017-03-24T09:34:29
mozilla/telemetry-analysis-service
349
mozilla__telemetry-analysis-service-349
[ "348" ]
7e9457e3b92bb865fa0b7929120d33e03bde9afc
diff --git a/atmo/urls.py b/atmo/urls.py --- a/atmo/urls.py +++ b/atmo/urls.py @@ -15,7 +15,7 @@ admin.site.login = login_required(admin.site.login) urlpatterns = [ - url(r'^$', views.dashboard, name='dashboard'), + url(r'^$', views.DashboardView.as_view(), name='dashboard'), url(r'^admin/', include(admin.site.urls)), url(r'clusters/', include('atmo.clusters.urls')), diff --git a/atmo/views.py b/atmo/views.py --- a/atmo/views.py +++ b/atmo/views.py @@ -6,8 +6,9 @@ from django.http import HttpResponseServerError from django.shortcuts import redirect from django.template import Context, TemplateDoesNotExist, loader -from django.template.response import TemplateResponse +from django.utils.decorators import method_decorator from django.views.decorators.csrf import requires_csrf_token +from django.views.generic.base import TemplateView from guardian.shortcuts import get_objects_for_group, get_objects_for_user from .clusters.models import Cluster @@ -15,83 +16,94 @@ from .jobs.models import SparkJob -@login_required -@modified_date -def dashboard(request): +@method_decorator(login_required, name='dispatch') +@method_decorator(modified_date, name='dispatch') +class DashboardView(TemplateView): + template_name = 'atmo/dashboard.html' + http_method_names = ['get', 'head'] # allowed filters for clusters - default_cluster_filter = 'active' - clusters_filters = ['active', 'terminated', 'failed', 'all'] - - # the cluster filter defaults to active ones - clusters_shown = request.GET.get('clusters', default_cluster_filter) - if clusters_shown not in clusters_filters: - clusters_shown = default_cluster_filter - - # get the model manager method depending on the cluster filter - # and call it to get the base queryset - clusters = get_objects_for_user( - request.user, - 'clusters.view_cluster', - getattr(Cluster.objects, clusters_shown)().order_by('-start_date'), - use_groups=False, - with_superuser=False, - ) - - sparkjob_qs = SparkJob.objects.all().order_by('-start_date') - group = Group.objects.filter(name='Spark job maintainers').first() - is_sparkjob_maintainer = group and group in request.user.groups.all() - + active_cluster_filter = 'active' + default_cluster_filter = active_cluster_filter + clusters_filters = [active_cluster_filter, 'terminated', 'failed', 'all'] # Filters for jobs. - default_job_filter = 'mine' - jobs_filters = ['mine', 'all'] - - jobs_shown = request.GET.get('jobs', default_job_filter) - if jobs_shown not in jobs_filters: - jobs_shown = default_job_filter - - # Redirect if user isn't in the right group. - if jobs_shown == 'all' and not is_sparkjob_maintainer: - return redirect('dashboard') - - if jobs_shown == 'mine': - spark_jobs = get_objects_for_user( - request.user, - 'jobs.view_sparkjob', - sparkjob_qs, + all_job_filter = 'all' + mine_job_filter = 'mine' + default_job_filter = mine_job_filter + jobs_filters = [mine_job_filter, all_job_filter] + maintainer_group_name = 'Spark job maintainers' + + def dispatch(self, request, *args, **kwargs): + self.clusters_shown = self.request.GET.get('clusters', self.default_cluster_filter) + if self.clusters_shown not in self.clusters_filters: + self.clusters_shown = self.default_cluster_filter + + self.jobs_maintainer_group = Group.objects.filter(name=self.maintainer_group_name).first() + self.is_sparkjob_maintainer = ( + self.jobs_maintainer_group and + self.jobs_maintainer_group in self.request.user.groups.all() + ) + + self.jobs_shown = self.request.GET.get('jobs', self.default_job_filter) + if self.jobs_shown not in self.jobs_filters: + self.jobs_shown = self.default_job_filter + + # Redirect if user isn't in the right group. + if self.jobs_shown == self.all_job_filter and not self.is_sparkjob_maintainer: + return redirect('dashboard') + return super().dispatch(request, *args, **kwargs) + + def get_context_data(self, **kwargs): + context = super().get_context_data(**kwargs) + + # get the model manager method depending on the cluster filter + # and call it to get the base queryset + clusters = get_objects_for_user( + self.request.user, + 'clusters.view_cluster', + getattr(Cluster.objects, self.clusters_shown)().order_by('-start_date'), use_groups=False, with_superuser=False, ) - elif jobs_shown == 'all': - spark_jobs = get_objects_for_group( - group, - 'jobs.view_sparkjob', - sparkjob_qs, - any_perm=False, - accept_global_perms=False, - ) - # a list of modification datetimes of the clusters and Spark jobs to use - # for getting the last changes on the dashboard - cluster_mod_datetimes = list(clusters.values_list('modified_at', flat=True)) - spark_job_mod_datetimes = [ - spark_job.latest_run.modified_at - for spark_job in spark_jobs.with_runs().order_by('-runs__modified_at') - ] - modified_datetimes = sorted(cluster_mod_datetimes + spark_job_mod_datetimes, reverse=True) - - context = { - 'clusters': clusters, - 'clusters_shown': clusters_shown, - 'clusters_filters': clusters_filters, - 'spark_jobs': spark_jobs, - 'jobs_shown': jobs_shown, - 'jobs_filters': jobs_filters, - 'is_sparkjob_maintainer': is_sparkjob_maintainer, - } - if modified_datetimes: - context['modified_date'] = modified_datetimes[0] - - return TemplateResponse(request, 'atmo/dashboard.html', context=context) + sparkjob_qs = SparkJob.objects.all().order_by('-start_date') + + if self.jobs_shown == self.mine_job_filter: + spark_jobs = get_objects_for_user( + self.request.user, + 'jobs.view_sparkjob', + sparkjob_qs, + use_groups=False, + with_superuser=False, + ) + elif self.jobs_shown == self.all_job_filter: + spark_jobs = get_objects_for_group( + self.jobs_maintainer_group, + 'jobs.view_sparkjob', + sparkjob_qs, + any_perm=False, + accept_global_perms=False, + ) + else: + spark_jobs = sparkjob_qs.none() + + context.update({ + 'clusters': clusters, + 'spark_jobs': spark_jobs, + }) + + # a list of modification datetimes of the clusters and Spark jobs to use + # for getting the last changes on the dashboard + cluster_mod_datetimes = list(clusters.values_list('modified_at', flat=True)) + spark_job_mod_datetimes = [ + spark_job.latest_run.modified_at + for spark_job in spark_jobs.with_runs().order_by('-runs__modified_at') + ] + modified_datetimes = sorted(cluster_mod_datetimes + spark_job_mod_datetimes, reverse=True) + + if modified_datetimes: + context['modified_date'] = modified_datetimes[0] + + return context @requires_csrf_token
Add user column to spark job table on dashboard To only be seen by admins in the "Spark job maintainers" group.
2017-03-29T12:59:28
mozilla/telemetry-analysis-service
401
mozilla__telemetry-analysis-service-401
[ "190" ]
316e13fc0b0d38ace9e0d7e6056b66d969450a8f
diff --git a/atmo/jobs/models.py b/atmo/jobs/models.py --- a/atmo/jobs/models.py +++ b/atmo/jobs/models.py @@ -146,6 +146,9 @@ def download(self): def edit(self): return reverse('jobs-edit', kwargs={'id': self.id}) + def run(self): + return reverse('jobs-run', kwargs={'id': self.id}) + __str__ = autostr('{self.identifier}') __repr__ = autorepr(['identifier', 'size', 'is_enabled']) @@ -168,10 +171,6 @@ def schedule(self): from .schedules import SparkJobSchedule return SparkJobSchedule(self) - @property - def results(self): - return self.provisioner.results(self.identifier, self.is_public) - def has_future_end_date(self, now): # no end date means it'll always be due if self.end_date is None: @@ -250,6 +249,10 @@ def notebook_name(self): def notebook_s3_object(self): return self.provisioner.get(self.notebook_s3_key) + @cached_property + def results(self): + return self.provisioner.results(self.identifier, self.is_public) + def get_latest_run(self): try: return self.runs.latest() diff --git a/atmo/jobs/urls.py b/atmo/jobs/urls.py --- a/atmo/jobs/urls.py +++ b/atmo/jobs/urls.py @@ -12,5 +12,6 @@ url(r'^(?P<id>\d+)/delete/', views.delete_spark_job, name='jobs-delete'), url(r'^(?P<id>\d+)/download/', views.download_spark_job, name='jobs-download'), url(r'^(?P<id>\d+)/edit/', views.edit_spark_job, name='jobs-edit'), + url(r'^(?P<id>\d+)/run/', views.run_spark_job, name='jobs-run'), url(r'^(?P<id>\d+)/$', views.detail_spark_job, name='jobs-detail'), ] diff --git a/atmo/jobs/views.py b/atmo/jobs/views.py --- a/atmo/jobs/views.py +++ b/atmo/jobs/views.py @@ -4,12 +4,15 @@ import logging from allauth.account.utils import user_display +from botocore.exceptions import ClientError from django.contrib.auth.decorators import login_required +from django.contrib import messages from django.http import (HttpResponse, HttpResponseNotFound, StreamingHttpResponse) from django.shortcuts import redirect, render from django.template.response import TemplateResponse from django.utils import timezone +from django.utils.safestring import mark_safe from django.utils.text import get_valid_filename from ..clusters.models import EMRRelease @@ -133,3 +136,48 @@ def download_spark_job(request, id): ) response['Content-Length'] = spark_job.notebook_s3_object['ContentLength'] return response + + +@login_required +@view_permission_required(SparkJob) +def run_spark_job(request, id): + spark_job = SparkJob.objects.get(pk=id) + if not spark_job.is_runnable: + messages.error( + request, + mark_safe( + '<h4>Run now unavailable.</h4>' + "The Spark job can't be run manually at this time. Please try again later." + ) + ) + return redirect(spark_job) + + if request.method == 'POST': + if spark_job.latest_run: + try: + spark_job.latest_run.update_status() + except ClientError: + messages.error( + request, + mark_safe( + '<h4>Spark job API error</h4>' + "The Spark job can't be run at the moment since there was a " + "problem with fetching the status of the previous job run. " + "Please try again later." + ) + ) + return redirect(spark_job) + + spark_job.run() + latest_run = spark_job.get_latest_run() + if latest_run: + schedule_entry = spark_job.schedule.get() + schedule_entry.reschedule( + last_run_at=spark_job.latest_run.scheduled_date, + ) + return redirect(spark_job) + + context = { + 'spark_job': spark_job, + } + return render(request, 'atmo/jobs/run.html', context=context)
diff --git a/tests/jobs/test_views.py b/tests/jobs/test_views.py --- a/tests/jobs/test_views.py +++ b/tests/jobs/test_views.py @@ -3,6 +3,7 @@ # file, you can obtain one at http://mozilla.org/MPL/2.0/. from datetime import datetime, timedelta +from botocore.exceptions import ClientError from django.core.urlresolvers import reverse from django.utils import timezone from freezegun import freeze_time @@ -290,3 +291,99 @@ def test_check_identifier_available(client, spark_job): response = client.get(available_url + '?identifier=completely-different') assert b'identifier available' in response.content + + +def test_run_without_latest_run(client, messages, mocker, one_hour_ago, spark_job): + run = mocker.patch('atmo.jobs.models.SparkJob.run') + update_status = mocker.patch('atmo.jobs.models.SparkJobRun.update_status') + mocker.patch( + 'atmo.jobs.models.SparkJob.results', + new_callable=mocker.PropertyMock, + return_valurn=[], + ) + assert spark_job.is_runnable + response = client.get(spark_job.urls.run, follow=True) + assert response.status_code == 200 + assert not response.redirect_chain + assert run.call_count == 0 + assert update_status.call_count == 0 + + response = client.post(spark_job.urls.run, follow=True) + assert run.call_count == 1 + assert update_status.call_count == 0 + assert response.status_code == 200 + assert response.redirect_chain[-1] == (spark_job.urls.detail, 302) + + +def test_run_with_latest_run(client, messages, mocker, one_hour_ago, spark_job): + run = mocker.patch('atmo.jobs.models.SparkJob.run') + update_status = mocker.patch('atmo.jobs.models.SparkJobRun.update_status') + mocker.patch( + 'atmo.jobs.models.SparkJob.results', + new_callable=mocker.PropertyMock, + return_valurn=[], + ) + spark_job.runs.create( + jobflow_id='my-jobflow-id', + status=Cluster.STATUS_TERMINATED, + scheduled_date=one_hour_ago, + ) + assert spark_job.is_runnable + response = client.get(spark_job.urls.run, follow=True) + assert response.status_code == 200 + assert not response.redirect_chain + assert run.call_count == 0 + assert update_status.call_count == 0 + + response = client.post(spark_job.urls.run, follow=True) + assert run.call_count == 1 + assert update_status.call_count == 1 + assert response.status_code == 200 + assert response.redirect_chain[-1] == (spark_job.urls.detail, 302) + + +def test_run_with_client_error(client, messages, mocker, one_hour_ago, spark_job): + run = mocker.patch('atmo.jobs.models.SparkJob.run') + update_status = mocker.patch( + 'atmo.jobs.models.SparkJobRun.update_status', + side_effect=ClientError({ + 'Error': { + 'Code': 'Code', + 'Message': 'Message', + } + }, 'operation_name'), + ) + mocker.patch( + 'atmo.jobs.models.SparkJob.results', + new_callable=mocker.PropertyMock, + return_valurn=[], + ) + spark_job.runs.create( + jobflow_id='my-jobflow-id', + status=Cluster.STATUS_TERMINATED, + scheduled_date=one_hour_ago, + ) + response = client.post(spark_job.urls.run, follow=True) + assert run.call_count == 0 + assert update_status.call_count == 1 + assert response.status_code == 200 + assert response.redirect_chain[-1] == (spark_job.urls.detail, 302) + messages.assert_message_contains(response, 'Spark job API error') + + +def test_run_not_runnable(client, messages, mocker, now, spark_job): + results = mocker.patch( + 'atmo.jobs.models.SparkJob.results', + new_callable=mocker.PropertyMock, + return_valurn=[], + ) + spark_job.runs.create( + jobflow_id='my-jobflow-id', + status=Cluster.STATUS_RUNNING, + scheduled_date=now, + ) + assert not spark_job.is_runnable + response = client.post(spark_job.urls.run, follow=True) + assert response.redirect_chain[-1] == (spark_job.urls.detail, 302) + messages.assert_message_contains(response, 'Run now unavailable') + assert results.call_count == 2
Scheduled jobs should have an option to be run "right now" https://bugzilla.mozilla.org/show_bug.cgi?id=1309567
2017-04-26T13:44:54
mozilla/telemetry-analysis-service
410
mozilla__telemetry-analysis-service-410
[ "374" ]
1b7d456fff8a65e2d23272bd5a76be84c51f6d99
diff --git a/atmo/jobs/models.py b/atmo/jobs/models.py --- a/atmo/jobs/models.py +++ b/atmo/jobs/models.py @@ -237,6 +237,11 @@ def should_run(self): def is_public(self): return self.result_visibility == self.RESULT_PUBLIC + @property + def is_active(self): + return (self.latest_run and + self.latest_run.status in Cluster.ACTIVE_STATUS_LIST) + @property def notebook_name(self): return self.notebook_s3_key.rsplit('/', 1)[-1] diff --git a/atmo/jobs/templatetags/notebook.py b/atmo/jobs/templatetags/notebook.py --- a/atmo/jobs/templatetags/notebook.py +++ b/atmo/jobs/templatetags/notebook.py @@ -4,6 +4,7 @@ from django import template from django.template.defaultfilters import stringfilter + register = template.Library() diff --git a/atmo/jobs/templatetags/status.py b/atmo/jobs/templatetags/status.py new file mode 100644 --- /dev/null +++ b/atmo/jobs/templatetags/status.py @@ -0,0 +1,30 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, you can obtain one at http://mozilla.org/MPL/2.0/. +from django import template +from django.template.defaultfilters import stringfilter + +from atmo.clusters.models import Cluster + + +register = template.Library() + + [email protected] +@stringfilter +def status_icon(status): + if status in Cluster.ACTIVE_STATUS_LIST: + return 'glyphicon-play' + elif status in Cluster.TERMINATED_STATUS_LIST: + return 'glyphicon-stop' + elif status in Cluster.FAILED_STATUS_LIST: + return 'glyphicon-exclamation-sign' + + [email protected] +@stringfilter +def status_color(status): + if status in Cluster.ACTIVE_STATUS_LIST: + return 'status-running' + elif status in Cluster.FAILED_STATUS_LIST: + return 'status-errors'
diff --git a/tests/jobs/test_models.py b/tests/jobs/test_models.py --- a/tests/jobs/test_models.py +++ b/tests/jobs/test_models.py @@ -119,6 +119,7 @@ def test_update_status_running(request, mocker, }, ) spark_job.latest_run.update_status() + assert spark_job.is_active assert spark_job.latest_run.status == Cluster.STATUS_RUNNING assert spark_job.latest_run.scheduled_date == one_hour_ago assert spark_job.latest_run.run_date == now @@ -245,6 +246,7 @@ def test_has_timed_out_never_ran(has_timed_out_factory): spark_job, timeout_delta = has_timed_out_factory() spark_job.latest_run.scheduled_date = None spark_job.latest_run.status = models.DEFAULT_STATUS + assert not spark_job.is_active assert spark_job.is_runnable assert spark_job.has_never_run assert not spark_job.has_timed_out @@ -265,6 +267,7 @@ def test_has_timed_out_ran_and_terminated(has_timed_out_factory): spark_job, timeout_delta = has_timed_out_factory() spark_job.latest_run.scheduled_date = spark_job.start_date + timedelta(minutes=10) spark_job.latest_run.status = Cluster.STATUS_TERMINATED + assert not spark_job.is_active assert spark_job.is_runnable assert not spark_job.has_never_run assert not spark_job.has_timed_out diff --git a/tests/test_templatetags.py b/tests/test_templatetags.py --- a/tests/test_templatetags.py +++ b/tests/test_templatetags.py @@ -1,8 +1,10 @@ # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, you can obtain one at http://mozilla.org/MPL/2.0/. +from atmo.clusters.models import Cluster from atmo.jobs.templatetags.notebook import is_notebook -from atmo.templatetags import url_update, full_url +from atmo.jobs.templatetags.status import status_color, status_icon +from atmo.templatetags import full_url, url_update def test_is_notebook(): @@ -19,3 +21,21 @@ def test_url_update(): def test_get_full_url(): assert full_url('/test/') == 'http://localhost:8000/test/' + + +def test_status_icon(): + for status in Cluster.ACTIVE_STATUS_LIST: + assert status_icon(status) == 'glyphicon-play' + for status in Cluster.TERMINATED_STATUS_LIST: + assert status_icon(status) == 'glyphicon-stop' + for status in Cluster.FAILED_STATUS_LIST: + assert status_icon(status) == 'glyphicon-exclamation-sign' + + +def test_status_color(): + for status in Cluster.ACTIVE_STATUS_LIST: + assert status_color(status) == 'status-running' + for status in Cluster.TERMINATED_STATUS_LIST: + assert status_color(status) is None + for status in Cluster.FAILED_STATUS_LIST: + assert status_color(status) == 'status-errors'
Add a status indicator that shows if a scheduled job is currently running
This is somewhat related to #271 which will show the job runs in a new tab of the job detail page and the "latest run" of a job in the dashboard. I can amend that feature to also show the current state of the "latest run". My plan here is to simply add a new column to the jobs list. For those with the added permission they'd get a good view of all jobs. The value of that column could either be text based of the latest run's status, possibly color coded (green for running, red for terminated with error, etc).
2017-05-01T21:33:02
mozilla/telemetry-analysis-service
413
mozilla__telemetry-analysis-service-413
[ "408" ]
0ea7a6f178732a51ca311062d492cf5debee73de
diff --git a/atmo/clusters/management/commands/update_clusters.py b/atmo/clusters/management/commands/update_clusters.py --- a/atmo/clusters/management/commands/update_clusters.py +++ b/atmo/clusters/management/commands/update_clusters.py @@ -3,7 +3,7 @@ # file, you can obtain one at http://mozilla.org/MPL/2.0/. from django.core.management.base import BaseCommand -from ...jobs import update_clusters +from ...tasks import update_clusters class Command(BaseCommand):
ImportError: No module named 'atmo.clusters.jobs' ``` app@a898b116953a:~$ ./manage.py update_clusters Traceback (most recent call last): File "./manage.py", line 11, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.5/site-packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.5/site-packages/django/core/management/__init__.py", line 195, in fetch_command klass = load_command_class(app_name, subcommand) File "/usr/local/lib/python3.5/site-packages/django/core/management/__init__.py", line 39, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "/usr/local/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 673, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/app/atmo/clusters/management/commands/update_clusters.py", line 6, in <module> from ...jobs import update_clusters ImportError: No module named 'atmo.clusters.jobs' ```
Nice, just goes to show that nobody ever used this management command ;D This is a simple fix, the clusters app was previously using RQ whose pattern is to use `jobs.py` files for the async jobs (not related to *Spark* jobs). The management command just needs a correct import: ```python from ...tasks import update_clusters # ... ```
2017-05-03T09:30:21
mozilla/telemetry-analysis-service
421
mozilla__telemetry-analysis-service-421
[ "417" ]
2e4891d972d08194edaa8741451f443251830646
diff --git a/atmo/celery.py b/atmo/celery.py --- a/atmo/celery.py +++ b/atmo/celery.py @@ -8,8 +8,6 @@ from celery.five import string_t from celery.task import current from celery.utils.time import maybe_iso8601 -from redbeat.schedulers import add_defaults -from redis.client import StrictRedis # set the default Django settings module for the 'celery' program. @@ -96,11 +94,5 @@ def wrapper(*args, **kwargs): # should have a `CELERY_` prefix. celery.config_from_object('django.conf:settings', namespace='CELERY') -# Add RedBeat defaults -add_defaults(celery) - -celery.redbeat_redis = StrictRedis.from_url(celery.conf.REDBEAT_REDIS_URL, - decode_responses=True) - # Load task modules from all registered Django celery configs. celery.autodiscover_tasks() diff --git a/atmo/settings.py b/atmo/settings.py --- a/atmo/settings.py +++ b/atmo/settings.py @@ -55,9 +55,9 @@ class Celery: # Maximum time to sleep between re-checking the schedule CELERY_BEAT_MAX_LOOP_INTERVAL = 5 # redbeat likes fast loops # Unless refreshed the lock will expire after this time - REDBEAT_LOCK_TIMEOUT = CELERY_BEAT_MAX_LOOP_INTERVAL * 5 + CELERY_REDBEAT_LOCK_TIMEOUT = CELERY_BEAT_MAX_LOOP_INTERVAL * 5 # The default/initial schedule to use. - CELERYBEAT_SCHEDULE = CELERY_BEAT_SCHEDULE = { + CELERY_BEAT_SCHEDULE = { 'expire_jobs': { 'schedule': crontab(minute='*'), 'task': 'atmo.jobs.tasks.expire_jobs', @@ -448,7 +448,7 @@ class Base(Core): environ_name='REDIS_URL', ) # Use redis as the Celery broker. - REDBEAT_REDIS_URL = CELERY_BROKER_URL = os.environ.get('REDIS_URL', REDIS_URL_DEFAULT) + CELERY_BROKER_URL = os.environ.get('REDIS_URL', REDIS_URL_DEFAULT) LOGGING_USE_JSON = values.BooleanValue(False)
Job kicked off twice yesterday I got a failure email last night for my txp-install-uninstall-events job but looking at the cluster/job list it looks like it's because the job was queued twice (and both ran at the same time.)
@sunahsuh Yeah, it seems as if the celerybeat isn't behaving correctly, even though it has a distributed lock to prevent duplicated tasks to spawn. I'm investigating this right now as well for stage where the the new scheduling code landed. I think this is related and possibly a dupe of #353. I've opened https://github.com/sibson/redbeat/issues/50 to fix this issue, in which the config code of RedBeat incorrectly read the "max_loop_interval" setting due to [a drastic change of setting names in Celery 4.0](http://docs.celeryproject.org/en/latest/whatsnew-4.0.html#v400-upgrade-settings) and essentially returns 0. The problem is that this value is used for the [timeout of the distributed lock](https://github.com/sibson/redbeat/blob/3f7e97c81411656ed52e2863d4de34983fdd3925/redbeat/schedulers.py#L42) that prevents the beat process to schedule multiple times instead of just once per cluster. Given our way of deployment on AWS we're running the scheduler in multiple containers to not create a bottleneck. Jezdez++ for mad debugging skills, damn
2017-05-05T13:04:25
mozilla/telemetry-analysis-service
441
mozilla__telemetry-analysis-service-441
[ "434" ]
aa4f738dad053e7a709d06890821bb2f9663ce82
diff --git a/atmo/clusters/tasks.py b/atmo/clusters/tasks.py --- a/atmo/clusters/tasks.py +++ b/atmo/clusters/tasks.py @@ -37,22 +37,23 @@ def deactivate_clusters(): @celery.task def send_expiration_mails(): deadline = timezone.now() + timedelta(hours=1) - soon_expired = Cluster.objects.active().filter( - end_date__lte=deadline, - expiration_mail_sent=False, - ) - for cluster in soon_expired: - with transaction.atomic(): - message = mail_builder.build_message( - 'atmo/clusters/mails/expiration.mail', { - 'cluster': cluster, - 'deadline': deadline, - 'settings': settings, - }, - ) - message.send() - cluster.expiration_mail_sent = True - cluster.save() + with transaction.atomic(): + soon_expired = Cluster.objects.select_for_update().active().filter( + end_date__lte=deadline, + expiration_mail_sent=False, + ) + for cluster in soon_expired: + with transaction.atomic(): + message = mail_builder.build_message( + 'atmo/clusters/mails/expiration.mail', { + 'cluster': cluster, + 'deadline': deadline, + 'settings': settings, + }, + ) + message.send() + cluster.expiration_mail_sent = True + cluster.save() @celery.task(max_retries=3)
Use `select_for_update` in cluster expiration email task There's a bit of a race condition [here](https://github.com/mozilla/telemetry-analysis-service/blob/e6fecbe12d09b2e2338ae62f5276b3b2f39b0b65/atmo/clusters/tasks.py#L38) where two tasks could ask for expiring clusters at the same time and start sending emails before they can be marked as sent. We should 1. wrap the whole task in a transaction and 2. use `select_for_update` on the query for active clusters to lock those rows.
Yay!
2017-05-11T13:17:09
mozilla/telemetry-analysis-service
467
mozilla__telemetry-analysis-service-467
[ "420" ]
4e018732e233ade07daf5edf3b9e1f61d04196af
diff --git a/atmo/settings.py b/atmo/settings.py --- a/atmo/settings.py +++ b/atmo/settings.py @@ -13,6 +13,7 @@ import logging import os import subprocess +from collections import OrderedDict from datetime import timedelta from celery.schedules import crontab @@ -117,20 +118,73 @@ class Constance: CONSTANCE_REDIS_CONNECTION_CLASS = 'django_redis.get_redis_connection' - CONSTANCE_CONFIG = { - 'AWS_USE_SPOT_INSTANCES': ( + CONSTANCE_ADDITIONAL_FIELDS = { + 'announcement_styles': ['django.forms.fields.ChoiceField', { + 'widget': 'django.forms.Select', + 'choices': ( + ('success', 'success (green)'), + ('info', 'info (blue)'), + ('warning', 'warning (yellow)'), + ('danger', 'danger (red)'), + ) + }], + 'announcement_title': ['django.forms.fields.CharField', { + 'widget': 'django.forms.TextInput', + }], + } + + CONSTANCE_CONFIG = OrderedDict([ + ('ANNOUNCEMENT_ENABLED', ( + False, + 'Whether to show the announcement on every page.', + )), + ('ANNOUNCMENT_STYLE', ( + 'info', + 'The style of the announcement.', + 'announcement_styles', + )), + ('ANNOUNCEMENT_TITLE', ( + 'Announcement', + 'The announcement title.', + 'announcement_title', + )), + ('ANNOUNCEMENT_CONTENT_MARKDOWN', ( + False, + 'Whether the announcement content should be ' + 'rendered as CommonMark (Markdown).', + )), + ('ANNOUNCEMENT_CONTENT', ( + '', + 'The announcement content.', + )), + ('AWS_USE_SPOT_INSTANCES', ( True, 'Whether to use spot instances on AWS', - ), - 'AWS_SPOT_BID_CORE': ( + )), + ('AWS_SPOT_BID_CORE', ( 0.84, 'The spot instance bid price for the cluster workers', - ), - 'AWS_EFS_DNS': ( + )), + ('AWS_EFS_DNS', ( 'fs-616ca0c8.efs.us-west-2.amazonaws.com', # the current dev instance of EFS 'The DNS name of the EFS mount for EMR clusters' - ) - } + )), + ]) + + CONSTANCE_CONFIG_FIELDSETS = OrderedDict([ + ('Announcements', ( + 'ANNOUNCEMENT_ENABLED', + 'ANNOUNCMENT_STYLE', + 'ANNOUNCEMENT_TITLE', + 'ANNOUNCEMENT_CONTENT', + 'ANNOUNCEMENT_CONTENT_MARKDOWN', + )), + ('AWS', ( + 'AWS_USE_SPOT_INSTANCES', + 'AWS_SPOT_BID_CORE', + 'AWS_EFS_DNS', + )), + ]) class AWS: @@ -414,6 +468,7 @@ def DJANGO_AMAZON_SES_REGION(self): 'atmo.context_processors.settings', 'atmo.context_processors.version', 'atmo.context_processors.alerts', + 'constance.context_processors.config', ], 'loaders': [ 'django.template.loaders.filesystem.Loader', diff --git a/atmo/templatetags.py b/atmo/templatetags.py --- a/atmo/templatetags.py +++ b/atmo/templatetags.py @@ -6,6 +6,7 @@ from django import template from django.conf import settings +import CommonMark from furl import furl @@ -25,3 +26,8 @@ def url_update(url, **kwargs): @register.filter def full_url(url): return urljoin(settings.SITE_URL, url) + + [email protected] +def markdown(content): + return CommonMark.commonmark(content)
Add ability to notify users of current events in the web UI
2017-05-16T13:29:34
mozilla/telemetry-analysis-service
474
mozilla__telemetry-analysis-service-474
[ "271" ]
db02ed488465c3f87e36c1dbb00393f767457986
diff --git a/atmo/jobs/models.py b/atmo/jobs/models.py --- a/atmo/jobs/models.py +++ b/atmo/jobs/models.py @@ -345,6 +345,7 @@ class SparkJobRun(EditedAtModel): class Meta: get_latest_by = 'created_at' + ordering = ['-created_at'] __str__ = autostr('{self.jobflow_id}')
Create view with jobs histories There have been several jobs failing silently. Those jobs will soon generate alerts (#201) but it would still be convenient to have a master view in the dashboard that shows the history, and their status, of all scheduled jobs. Furthermore, every user should be able to see the history for their own jobs.
@vitillo Yep, another tab on the job detail page makes sense for the list of runs and their status. In fact the work on #201 is providing much of this and I'm far with the implementation so that we should finish that first and then extend that work to implement this feature request. Would you consider showing the scheduled jobs of *all users* for admins in the dashboard useful? We have the permission system in place to enable the ability to do that. > Would you consider showing the scheduled jobs of all users for admins in the dashboard useful? We have the permission system in place to enable the ability to do that. Yes, in fact this is the view I was referring to in my comment. @vitillo Cool, I've opened #283 to track this separate issue then and leave this open for showing the history on the job detail page.
2017-05-18T00:07:58
mozilla/telemetry-analysis-service
482
mozilla__telemetry-analysis-service-482
[ "478" ]
044e99166c759b2e8e736ac380bf016a64c9d623
diff --git a/atmo/jobs/migrations/0026_sparkjobrun_size.py b/atmo/jobs/migrations/0026_sparkjobrun_size.py new file mode 100644 --- /dev/null +++ b/atmo/jobs/migrations/0026_sparkjobrun_size.py @@ -0,0 +1,20 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.11.1 on 2017-05-19 18:26 +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('jobs', '0025_populate_job_schedule'), + ] + + operations = [ + migrations.AddField( + model_name='sparkjobrun', + name='size', + field=models.IntegerField(blank=True, help_text='Number of computers used to run the job.', null=True), + ), + ] diff --git a/atmo/jobs/models.py b/atmo/jobs/models.py --- a/atmo/jobs/models.py +++ b/atmo/jobs/models.py @@ -239,6 +239,7 @@ def run(self): jobflow_id=jobflow_id, scheduled_date=timezone.now(), emr_release_version=self.emr_release.version, + size=self.size, ) # Remove the cached latest run to this objects will requery it. try: @@ -314,6 +315,11 @@ class SparkJobRun(EditedAtModel): blank=True, null=True, ) + size = models.IntegerField( + help_text="Number of computers used to run the job.", + blank=True, + null=True, + ) status = models.CharField( max_length=50, blank=True, @@ -346,7 +352,7 @@ def spark_job_identifier(self): return self.spark_job.identifier __repr__ = autorepr( - ['jobflow_id', 'spark_job_identifier'], + ['jobflow_id', 'spark_job_identifier', 'emr_release_version', 'size'], spark_job_identifier=spark_job_identifier, )
Record cluster size when running jobs for historical log
2017-05-19T18:33:05
mozilla/telemetry-analysis-service
551
mozilla__telemetry-analysis-service-551
[ "550" ]
66d1c8f8db53f8cb8fffd5ab7a579322ef516914
diff --git a/atmo/clusters/forms.py b/atmo/clusters/forms.py --- a/atmo/clusters/forms.py +++ b/atmo/clusters/forms.py @@ -4,6 +4,7 @@ from django import forms from django.conf import settings from django.core.urlresolvers import reverse +from django.utils.safestring import mark_safe from . import models from ..forms.mixins import AutoClassFormMixin, CreatedByModelFormMixin @@ -14,7 +15,7 @@ class EMRReleaseChoiceField(forms.ModelChoiceField): def __init__(self, *args, **kwargs): super().__init__( label='EMR release', - queryset=models.EMRRelease.objects.all(), + queryset=models.EMRRelease.objects.active(), required=True, empty_label=None, widget=forms.RadioSelect(attrs={ @@ -28,11 +29,11 @@ def label_from_instance(self, obj): label = obj.version extra = [] if obj.is_experimental: - extra.append('experimental') + extra.append('<span class="label label-info">experimental</span>') elif obj.is_deprecated: - extra.append('deprecated') + extra.append('<span class="label label-warning">deprecated</span>') if extra: - label = '%s (%s)' % (label, ', '.join(extra)) + label = mark_safe('%s %s' % (label, ''.join(extra))) return label diff --git a/atmo/clusters/queries.py b/atmo/clusters/queries.py --- a/atmo/clusters/queries.py +++ b/atmo/clusters/queries.py @@ -6,6 +6,11 @@ class EMRReleaseQuerySet(models.QuerySet): + def active(self): + return self.filter( + is_active=True, + ) + def stable(self): return self.filter( is_experimental=False,
diff --git a/tests/clusters/test_forms.py b/tests/clusters/test_forms.py --- a/tests/clusters/test_forms.py +++ b/tests/clusters/test_forms.py @@ -5,12 +5,22 @@ def test_emr_release_choice_field(emr_release_factory): + + def make_label(label, text): + return '<span class="label label-%s">%s</span>' % (label, text) + regular = emr_release_factory() + inactive = emr_release_factory(is_active=False) deprecated = emr_release_factory(is_deprecated=True) experimental = emr_release_factory(is_experimental=True) choice_field = EMRReleaseChoiceField() result = choice_field.widget.render('test', regular.pk) + assert inactive.version not in result assert '%s</label>' % regular.version in result - assert '%s (experimental)</label>' % experimental.version in result - assert '%s (deprecated)</label>' % deprecated.version in result + assert ('%s %s</label>' % (deprecated.version, + make_label('warning', 'deprecated')) + in result) + assert ('%s %s</label>' % (experimental.version, + make_label('info', 'experimental')) + in result)
EMR release form shows inactive records The EMR release model has a column for `is_active`, but it's not being considered when querying the list of EMR releases in the form.
2017-06-15T21:56:14
mozilla/telemetry-analysis-service
587
mozilla__telemetry-analysis-service-587
[ "584" ]
85ec3a55222ddf7a833840d7e18485454c77fa36
diff --git a/atmo/settings.py b/atmo/settings.py --- a/atmo/settings.py +++ b/atmo/settings.py @@ -216,7 +216,9 @@ class AWS: ), 'SPARK_INSTANCE_PROFILE': 'telemetry-spark-cloudformation-' 'TelemetrySparkInstanceProfile-1SATUBVEXG7E3', - 'SPARK_EMR_BUCKET': 'telemetry-spark-emr-2', + 'SPARK_EMR_BUCKET': values.Value(default='telemetry-spark-emr-2', + environ_prefix=None, + environ_name='AWS_SPARK_EMR_BUCKET'), 'INSTANCE_APP_TAG': 'telemetry-analysis-worker-instance', 'EMAIL_SOURCE': '[email protected]', 'MAX_CLUSTER_SIZE': 30,
Separate EMR bootstrap deploy for staging and production This will allow us to make changes to the bootstrap scripts and test them on ATMO staging easily before pushing to production. This involves updating the ansible playbook to deploy the bootstrap scripts to either a staging or production location on S3. And setting up a configuration variable to point ATMO to the staging or production buckets.
2017-06-30T21:02:11
mozilla/telemetry-analysis-service
605
mozilla__telemetry-analysis-service-605
[ "584" ]
4f576889aae89d753c9ad7f254a9a42fe2d4dbff
diff --git a/atmo/settings.py b/atmo/settings.py --- a/atmo/settings.py +++ b/atmo/settings.py @@ -209,11 +209,16 @@ class AWS: 'MASTER_INSTANCE_TYPE': 'c3.4xlarge', 'WORKER_INSTANCE_TYPE': 'c3.4xlarge', - 'SPARK_INSTANCE_PROFILE': 'telemetry-spark-cloudformation-' - 'TelemetrySparkInstanceProfile-1SATUBVEXG7E3', - 'SPARK_EMR_BUCKET': values.Value(default='telemetry-spark-emr-2', - environ_prefix=None, - environ_name='AWS_SPARK_EMR_BUCKET'), + 'SPARK_INSTANCE_PROFILE': values.Value( + default='telemetry-spark-cloudformation-' + 'TelemetrySparkInstanceProfile-1SATUBVEXG7E3', + environ_prefix=None, + environ_name='AWS_SPARK_INSTANCE_PROFILE' + ), + 'SPARK_EMR_BUCKET': values.Value( + default='telemetry-spark-emr-2', + environ_prefix=None, + environ_name='AWS_SPARK_EMR_BUCKET'), 'INSTANCE_APP_TAG': 'telemetry-analysis-worker-instance', 'EMAIL_SOURCE': '[email protected]', 'MAX_CLUSTER_SIZE': 30,
Separate EMR bootstrap deploy for staging and production This will allow us to make changes to the bootstrap scripts and test them on ATMO staging easily before pushing to production. This involves updating the ansible playbook to deploy the bootstrap scripts to either a staging or production location on S3. And setting up a configuration variable to point ATMO to the staging or production buckets.
2017-07-11T22:45:51
mozilla/telemetry-analysis-service
684
mozilla__telemetry-analysis-service-684
[ "549" ]
f427c32d509e72b7381de4f8161a0cbf4bcf7df9
diff --git a/atmo/jobs/views.py b/atmo/jobs/views.py --- a/atmo/jobs/views.py +++ b/atmo/jobs/views.py @@ -14,12 +14,10 @@ from django.utils.safestring import mark_safe from django.utils.text import get_valid_filename -from .. import names from ..clusters.models import EMRRelease from ..decorators import (change_permission_required, delete_permission_required, modified_date, view_permission_required) -from ..models import next_field_value from .forms import EditSparkJobForm, NewSparkJobForm, SparkJobAvailableForm from .models import SparkJob @@ -48,10 +46,8 @@ def new_spark_job(request): """ View to schedule a new Spark job to run on AWS EMR. """ - identifier = names.random_scientist() - next_identifier = next_field_value(SparkJob, 'identifier', identifier) initial = { - 'identifier': next_identifier, + 'identifier': '', 'size': 1, 'interval_in_hours': SparkJob.INTERVAL_WEEKLY, 'job_timeout': 24,
diff --git a/tests/jobs/test_views.py b/tests/jobs/test_views.py --- a/tests/jobs/test_views.py +++ b/tests/jobs/test_views.py @@ -17,6 +17,10 @@ def test_new_spark_job(client): response = client.get(reverse('jobs-new')) assert response.status_code == 200 assert 'form' in response.context + f = response.context['form'] + assert f.initial['identifier'] == '' + assert f.initial['size'] == 1 + assert f.initial['job_timeout'] == 24 @pytest.mark.usefixtures('transactional_db')
Better naming for scheduled jobs In #459 identifiers for adhoc clusters and scheduled jobs were changed to be randomly generated. This is fine for a single-use cluster, but makes notifications for scheduled jobs meaningless. For example, I received a notification today that job "fervent-snyder-2799" has failed. It is owned by someone else, but emails are cc'd to telemetry-alerts as well (general audience to monitor for important failures). I would prefer that the name for a scheduled job be reflective of what is being done in the job. Alternatively, we could ensure that the "description" field has been filled in and include that information in the notification emails.
2017-08-18T20:08:51
mozilla/telemetry-analysis-service
812
mozilla__telemetry-analysis-service-812
[ "802" ]
de3f90e5c6deebe4bed2fe4beba119774cb1353d
diff --git a/atmo/jobs/models.py b/atmo/jobs/models.py --- a/atmo/jobs/models.py +++ b/atmo/jobs/models.py @@ -461,8 +461,10 @@ def sync(self, info=None): } ) + if self.finished_at and self.ready_at: # When job is finished, record time in seconds it took the - # scheduled job to run. + # scheduled job to run. Sometimes `ready_at` won't be + # available if the cluster terminated with errors. run_time = (self.finished_at - self.ready_at).seconds Metric.record( 'sparkjob-run-time', run_time,
diff --git a/tests/jobs/test_models.py b/tests/jobs/test_models.py --- a/tests/jobs/test_models.py +++ b/tests/jobs/test_models.py @@ -227,9 +227,9 @@ def test_sync_terminated_with_errors(request, mocker, mocker.patch( 'atmo.clusters.provisioners.ClusterProvisioner.info', return_value={ - 'creation_datetime': now, + 'creation_datetime': one_hour_ago, 'ready_datetime': None, - 'end_datetime': None, + 'end_datetime': now, 'state': Cluster.STATUS_TERMINATED_WITH_ERRORS, 'state_change_reason_code': Cluster.STATE_CHANGE_REASON_BOOTSTRAP_FAILURE, 'state_change_reason_message': 'Bootstrapping steps failed.', @@ -243,6 +243,19 @@ def test_sync_terminated_with_errors(request, mocker, assert alert.mail_sent_date is None assert spark_job.latest_run.status == Cluster.STATUS_TERMINATED_WITH_ERRORS + metrics = Metric.objects.filter(key='sparkjob-normalized-instance-hours') + assert metrics.count() == 1 + metric = metrics.first() + assert metric.value == 5 + assert metric.data == { + 'identifier': spark_job.identifier, + 'size': spark_job.size, + 'jobflow_id': spark_job.latest_run.jobflow_id, + } + + assert Metric.objects.filter(key='sparkjob-time-to-ready').count() == 0 + assert Metric.objects.filter(key='sparkjob-run-time').count() == 0 + def test_first_run_without_run(mocker, spark_job): apply_async = mocker.patch('atmo.jobs.tasks.run_job.apply_async')
When a job terminates early a metrics recording error is thrown There might be more than one issue here... Recently a few jobs terminated early b/c of EBS volume limits. When that happened the status failed to update correctly and an error was reported to sentry when we try to calculate one of the metrics which is missing the `ready_at` timestamp. If a job terminates with errors I think it best to not attempt to record the usual metrics.
Decided it best to continue to record the metrics if we have the data for them. So this issue requires adding more data checking. The code assumes incorrectly that the `ready_at` datetime will exist if the `finished_at` datetime is set -- this is true when the job completes successfully but not true if the job terminates with errors during bootstrapping.
2017-10-23T15:55:49
mozilla/telemetry-analysis-service
831
mozilla__telemetry-analysis-service-831
[ "830" ]
4fe251a32b8a30a47c53637e6113a4e7cd7d7c36
diff --git a/atmo/settings.py b/atmo/settings.py --- a/atmo/settings.py +++ b/atmo/settings.py @@ -17,7 +17,7 @@ from datetime import timedelta from celery.schedules import crontab -from configurations import Configuration, values +from configurations import Configuration, pristinemethod, values from django.contrib.messages import constants as messages from django.core.urlresolvers import reverse_lazy from dockerflow.version import get_version @@ -376,9 +376,21 @@ def DJANGO_AMAZON_SES_REGION(self): LOGIN_URL = reverse_lazy('users-login') LOGOUT_URL = reverse_lazy('oidc_logout') LOGIN_REDIRECT_URL = reverse_lazy('dashboard') - LOGIN_REDIRECT_URL_FAILURE = '/' + LOGOUT_REDIRECT_URL = reverse_lazy('dashboard') + LOGIN_REDIRECT_URL_FAILURE = reverse_lazy('dashboard') OIDC_STORE_ACCESS_TOKEN = True - OIDC_USERNAME_ALGO = 'atmo.users.utils.generate_username_from_email' + + @pristinemethod + def OIDC_USERNAME_ALGO(self, email): + """ + Use the unique part of the email as the username for mozilla.com + and the full email address for all other users. + """ + if '@' in email and email.endswith('@mozilla.com'): + return email.split('@')[0] + else: + return email + OIDC_EXEMPT_URLS = [ 'users-login', ] diff --git a/atmo/urls.py b/atmo/urls.py --- a/atmo/urls.py +++ b/atmo/urls.py @@ -23,7 +23,7 @@ url(r'keys/', include('atmo.keys.urls')), url(r'news/', include('atmo.news.urls')), url(r'users/', include('atmo.users.urls')), - url(r'^oidc/', include('mozilla_django_oidc.urls')), + url(r'oidc/', include('mozilla_django_oidc.urls')), # contribute.json url url(r'^(?P<path>contribute\.json)$', static.serve, {'document_root': settings.BASE_DIR}), diff --git a/atmo/users/utils.py b/atmo/users/utils.py deleted file mode 100644 --- a/atmo/users/utils.py +++ /dev/null @@ -1,14 +0,0 @@ -# This Source Code Form is subject to the terms of the Mozilla Public -# License, v. 2.0. If a copy of the MPL was not distributed with this -# file, you can obtain one at http://mozilla.org/MPL/2.0/. - - -def generate_username_from_email(email): - """ - Use the unique part of the email as the username for mozilla.com - and the full email address for all other users. - """ - if '@' in email and email.endswith('@mozilla.com'): - return email.split('@')[0] - else: - return email
Logout doesn't work as GET request With the new mozilla-django-oidc implementation the logout view requires using POST to affect the logout (which is a common pattern, although not necessarily a good one). We need to update the logout link to submit a form against the logout view.
2017-11-01T16:08:44
mozilla/telemetry-analysis-service
975
mozilla__telemetry-analysis-service-975
[ "918" ]
ea5f736fca00d65562cc046a145efe60d1d1ed4e
diff --git a/atmo/forms/mixins.py b/atmo/forms/mixins.py --- a/atmo/forms/mixins.py +++ b/atmo/forms/mixins.py @@ -5,6 +5,7 @@ from collections import OrderedDict from django import forms +from django.contrib.auth.models import User from .cache import CachedFileCache from .fields import CachedFileField @@ -52,7 +53,10 @@ def save(self, commit=True): obj = super().save(commit=False) # set the field to the user that created the object - obj.created_by = self.created_by + try: + obj.created_by + except User.DoesNotExist: + obj.created_by = self.created_by if commit: # actually start the real object, and return the model object
Don't overwrite creator when saving jobs Since we can provide view and editing permissions to other users (e.g. admins) with row-level permissions we should stop overwriting the creator on every save of a scheduled Spark job since it would prevent an effective trail of ownership and has in the past led to inconsistencies when updating jobs by an admin.
2018-01-17T15:36:40
mozilla/telemetry-analysis-service
982
mozilla__telemetry-analysis-service-982
[ "978" ]
1598ce170adcfadbcdb0e9844da135d08c081b7d
diff --git a/atmo/settings.py b/atmo/settings.py --- a/atmo/settings.py +++ b/atmo/settings.py @@ -369,7 +369,7 @@ def AWS_DEFAULT_REGION(self): AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', - 'mozilla_django_oidc.auth.OIDCAuthenticationBackend', + 'atmo.users.backends.AtmoOIDCAuthenticationBackend', 'guardian.backends.ObjectPermissionBackend', ) @@ -383,6 +383,11 @@ def AWS_DEFAULT_REGION(self): OIDC_EXEMPT_URLS = [ 'users-login', ] + # When enabled this will match the remote groups provided via the OIDC + # claims with configured list of allowed user groups using UNIX shell-style + # wildcards such as * and ?. + REMOTE_GROUPS_ENABLED = values.BooleanValue(default=False) + REMOTE_GROUPS_ALLOWED = values.SetValue(set(), separator=',') MESSAGE_TAGS = { messages.ERROR: 'danger' diff --git a/atmo/users/backends.py b/atmo/users/backends.py new file mode 100644 --- /dev/null +++ b/atmo/users/backends.py @@ -0,0 +1,22 @@ +from django.conf import settings + +from mozilla_django_oidc.auth import OIDCAuthenticationBackend + + +class AtmoOIDCAuthenticationBackend(OIDCAuthenticationBackend): + + def verify_claims(self, claims): + """ + See if the claims contain a list of user groups (in various forms) + and then check it against a configured list of allowed groups. + """ + # shortcut in case remote groups aren't enabled + if not settings.REMOTE_GROUPS_ENABLED: + return True + remote_groups = set( + claims.get('groups') or + claims.get('https://sso.mozilla.com/claim/groups') or + [] + ) + allowed_groups = settings.REMOTE_GROUPS_ALLOWED + return bool(allowed_groups.intersection(remote_groups))
Add OIDC claim verification for LDAP groups
2018-01-24T21:54:17
mozilla/telemetry-analysis-service
989
mozilla__telemetry-analysis-service-989
[ "969" ]
bb49760251d1d5686b2660f34f9c971f68e4744b
diff --git a/atmo/clusters/forms.py b/atmo/clusters/forms.py --- a/atmo/clusters/forms.py +++ b/atmo/clusters/forms.py @@ -21,7 +21,7 @@ class EMRReleaseChoiceField(forms.ModelChoiceField): def __init__(self, *args, **kwargs): super().__init__( label='EMR release', - queryset=models.EMRRelease.objects.active(), + queryset=models.EMRRelease.objects.active().natural_sort_by_version(), required=True, empty_label=None, widget=forms.RadioSelect(attrs={ diff --git a/atmo/clusters/queries.py b/atmo/clusters/queries.py --- a/atmo/clusters/queries.py +++ b/atmo/clusters/queries.py @@ -8,6 +8,15 @@ class EMRReleaseQuerySet(models.QuerySet): """ A Django queryset for the :class:`~atmo.clusters.models.EMRRelease` model. """ + def natural_sort_by_version(self): + """ + Sorts this queryset by the EMR version naturally (human-readable). + """ + return self.extra( + select={ + 'natural_version': "string_to_array(version, '.')::int[]", + }, + ).order_by('-natural_version') def active(self): return self.filter(
diff --git a/tests/clusters/test_models.py b/tests/clusters/test_models.py --- a/tests/clusters/test_models.py +++ b/tests/clusters/test_models.py @@ -89,3 +89,25 @@ def test_metric_records_emr_version(cluster_provisioner_mocks, cluster_factory): assert (Metric.objects.get(key='cluster-emr-version').data == {'version': str(cluster.emr_release.version)}) + + +def test_natural_sorting(emr_release_factory): + # create EMR releases out of order to force PKs to be not consecutive + third = emr_release_factory(version='5.9.0') + second = emr_release_factory(version='5.8.0') + first = emr_release_factory(version='5.2.1') + fourth = emr_release_factory(version='5.11.0') + + expected = [fourth.version, third.version, second.version, first.version] + + versions = models.EMRRelease.objects.all().values_list( + 'version', flat=True + ) + + assert list(versions) != expected + + versions = models.EMRRelease.objects.natural_sort_by_version().values_list( + 'version', flat=True + ) + assert versions.ordered + assert list(versions) == expected
Sort EMR versions naturally The EMR versions are currently not sorted naturally but by alphabet, which breaks for example with EMR 5.11.0.
2018-02-19T21:57:29
mozilla/telemetry-analysis-service
1,257
mozilla__telemetry-analysis-service-1257
[ "1128" ]
450587d8df0b1b68688c1b6aadca138dc2b4cb68
diff --git a/atmo/settings.py b/atmo/settings.py --- a/atmo/settings.py +++ b/atmo/settings.py @@ -339,6 +339,7 @@ class Core(AWS, Celery, Constance, CSP, Configuration): ] MIDDLEWARE = ( + 'django_cookies_samesite.middleware.CookiesSameSite', 'django.middleware.security.SecurityMiddleware', 'dockerflow.django.middleware.DockerflowMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', @@ -452,6 +453,9 @@ def AWS_DEFAULT_REGION(self): WHITENOISE_ALLOW_ALL_ORIGINS = False SESSION_ENGINE = 'django.contrib.sessions.backends.cache' SESSION_CACHE_ALIAS = 'default' + SESSION_COOKIE_SAMESITE = 'Lax' + # in addition to sessionid and csrftoken cookies we use this cookie: + SESSION_COOKIE_SAMESITE_KEYS = ['news_current'] SILENCED_SYSTEM_CHECKS = [ 'security.W003', # We're using django-session-csrf @@ -672,6 +676,7 @@ class Stage(Base): # Mark session and CSRF cookies as being HTTPS-only. CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True + SESSION_COOKIE_SAMESITE = 'Strict' SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_BROWSER_XSS_FILTER = True SECURE_CONTENT_TYPE_NOSNIFF = True
Support SameSite cookie attribute on sessionid Firefox 60 introduces support for the SameSite cookie attribute: https://blog.mozilla.org/security/2018/04/24/same-site-cookies-in-firefox-60/ This provides significant protection against CSRF vulnerabilities and so it should be applied to the sessionid cookie. It looks like its been added to Django https://code.djangoproject.com/ticket/27863 but the fix doesnt appear the be in the latest release or on older streams. We have various other services that are also on django 1.11.x so I'll look into whether we can get the fix back-ported to that stream.
Unfortunately 1.11 is only receiving data loss and security fixes: https://code.djangoproject.com/ticket/29409 :( Django 2.1 is [out in August](https://code.djangoproject.com/wiki/Version2.1Roadmap), which fits well the timeframe to work on ATMO again. I don't think this should be tried to be implemented as a 3rd party app right now given the non-trivial [implementation of the patch](https://github.com/django/django/pull/9860/files). @psiinon Just saw a bunch of Django sites have been asked to do this, please make sure we use the same solution in the interim to 2.1. @jezdez yes, pontoon are looking to support this via middleware: https://github.com/mozilla/pontoon/pull/964 I'm hoping this will be a common solution that other apps can use as well. I talked with at IRC @psiinon the plan is to create a small Django package with this middleware and push it to Pypi today. @jotes Thanks for releasing this as an app!
2018-08-15T13:53:55
mozilla/telemetry-analysis-service
1,493
mozilla__telemetry-analysis-service-1493
[ "1101" ]
aa4fe07bf58600a9ba78f32a551f0862e4bc4f85
diff --git a/atmo/clusters/models.py b/atmo/clusters/models.py --- a/atmo/clusters/models.py +++ b/atmo/clusters/models.py @@ -360,6 +360,7 @@ def extend(self, hours): """Extend the cluster lifetime by the given number of hours.""" self.expires_at = models.F('expires_at') + timedelta(hours=hours) self.lifetime_extension_count = models.F('lifetime_extension_count') + 1 + self.expiration_mail_sent = False self.save() with transaction.atomic():
diff --git a/requirements/tests.txt b/requirements/tests.txt --- a/requirements/tests.txt +++ b/requirements/tests.txt @@ -61,10 +61,9 @@ pytest-django==3.4.4 \ pytest-mock==1.10.0 \ --hash=sha256:53801e621223d34724926a5c98bd90e8e417ce35264365d39d6c896388dcc928 \ --hash=sha256:d89a8209d722b8307b5e351496830d5cc5e192336003a485443ae9adeb7dd4c0 -pycodestyle==2.4.0 \ - --hash=sha256:74abc4e221d393ea5ce1f129ea6903209940c1ecd29e002e8c6933c2b21026e0 \ - --hash=sha256:cbc619d09254895b0d12c2c691e237b2e91e9b2ecf5e84c26b35400f93dcfb83 \ - --hash=sha256:cbfca99bd594a10f674d0cd97a3d802a1fdef635d4361e1a2658de47ed261e3a # pyup: <2.4.0,>=2.0.0 +pycodestyle==2.3.1 \ + --hash=sha256:682256a5b318149ca0d2a9185d365d8864a768a28db66a84a2ea946bcc426766 \ + --hash=sha256:6c4245ade1edfad79c3446fadfc96b0de2759662dc29d07d80a6f27ad1ca6ba9 # pyup: <2.4.0,>=2.0.0 freezegun==0.3.10 \ --hash=sha256:94c59d69bb99c9ec3ca5a3adb41930d3ea09d2a9756c23a02d89fa75646e78dd \ --hash=sha256:703caac155dcaad61f78de4cb0666dca778d854dfb90b3699930adee0559a622 diff --git a/tests/clusters/test_tasks.py b/tests/clusters/test_tasks.py --- a/tests/clusters/test_tasks.py +++ b/tests/clusters/test_tasks.py @@ -200,3 +200,42 @@ def test_update_clusters(mocker, now, user, cluster_factory): 'size': cluster3.size }) ] + + +def test_extended_cluster_resends_expiration_mail(mailoutbox, mocker, one_hour_ago, cluster_factory): + cluster = cluster_factory( + expires_at=one_hour_ago, + most_recent_status=models.Cluster.STATUS_WAITING, + ) + + # Send first expiration email + assert len(mailoutbox) == 0 + tasks.send_expiration_mails() + assert len(mailoutbox) == 1 + message = mailoutbox[0] + assert message.subject == ( + '%sCluster %s is expiring soon!' % + (settings.EMAIL_SUBJECT_PREFIX, cluster.identifier) + ) + assert message.from_email == settings.DEFAULT_FROM_EMAIL + assert list(message.to) == [cluster.created_by.email] + cluster.refresh_from_db() + assert cluster.expiration_mail_sent + + # Extend cluster lifetime + cluster.extend(1) + cluster.refresh_from_db() + assert cluster.expiration_mail_sent is False + + # Send second expiration email + tasks.send_expiration_mails() + assert len(mailoutbox) == 2 + message = mailoutbox[1] + assert message.subject == ( + '%sCluster %s is expiring soon!' % + (settings.EMAIL_SUBJECT_PREFIX, cluster.identifier) + ) + assert message.from_email == settings.DEFAULT_FROM_EMAIL + assert list(message.to) == [cluster.created_by.email] + cluster.refresh_from_db() + assert cluster.expiration_mail_sent
Email server shutdown warning again after extending cluster Hey, would it be possible to send another hour warning email if a user extends the cluster life?
cc: @jezdez This seems like a good idea but I'm afraid ATMO feature development is on hold while Redash and STMO take the majority of our time. Rest assured when we get back to ATMO we'll schedule working on this.
2018-11-26T21:04:56
OpenMined/PySyft
113
OpenMined__PySyft-113
[ "19" ]
4080f70cd4e54f92f05e1dd6b8a111ef1f4dfac3
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -10,8 +10,6 @@ def read(fname): requirements = read('requirements.txt').split() - - setup( name = "syft", version = "0.1.0", @@ -29,4 +27,6 @@ def read(fname): ], scripts=['bin/syft_cmd'], install_requires=requirements, + setup_requires=['pytest-runner'], + tests_require=['pytest'] ) diff --git a/syft/__init__.py b/syft/__init__.py --- a/syft/__init__.py +++ b/syft/__init__.py @@ -1,26 +1 @@ -import importlib -import pkgutil - -ignore_packages = set(['test']) - -def import_submodules(package, recursive=True): - """ Import all submodules of a module, recursively, including subpackages - - :param package: package (name or actual module) - :type package: str | module - :rtype: dict[str, types.ModuleType] - """ - if isinstance(package, str): - package = importlib.import_module(package) - results = {} - for loader, name, is_pkg in pkgutil.walk_packages(package.__path__): - # test submodule names are 'syft.test.*', so this matches the 'ignore_packages' above - if 'test' not in str(name): - full_name = package.__name__ + '.' + name - results[full_name] = importlib.import_module(full_name) - if recursive and is_pkg: - results.update(import_submodules(full_name)) - return results - -# import submodules recursively -import_submodules(__name__) +from .tensor import TensorBase diff --git a/syft/tensor.py b/syft/tensor.py new file mode 100644 --- /dev/null +++ b/syft/tensor.py @@ -0,0 +1,85 @@ +import numpy as np + +def _ensure_ndarray(arr): + if not isinstance(arr, np.ndarray): + arr = np.array(arr) + + return arr + +class TensorBase(object): + """ + A base tensor class that perform basic element-wise operation such as + addition, subtraction, multiplication and division + """ + + def __init__(self, arr_like, encrypted=False): + self.data = _ensure_ndarray(arr_like) + self.encrypted = encrypted + + def __add__(self, arr_like): + """Performs element-wise addition between two array like objects""" + if self.encrypted: + return NotImplemented + + arr_like = _ensure_ndarray(arr_like) + return self.data + arr_like + + def __iadd__(self, arr_like): + """Performs in place element-wise addition between two array like objects""" + if self.encrypted: + return NotImplemented + + arr_like = _ensure_ndarray(arr_like) + self.data = self.data + arr_like + return self.data + + def __sub__(self, arr_like): + """Performs element-wise subtraction between two array like objects""" + if self.encrypted: + return NotImplemented + + arr_like = _ensure_ndarray(arr_like) + return self.data - arr_like + + def __isub__(self, arr_like): + """Performs in place element-wise subtraction between two array like objects""" + if self.encrypted: + return NotImplemented + + arr_like = _ensure_ndarray(arr_like) + self.data = self.data - arr_like + return self.data + + def __mul__(self, arr_like): + """Performs element-wise multiplication between two array like objects""" + if self.encrypted: + return NotImplemented + + arr_like = _ensure_ndarray(arr_like) + return self.data * arr_like + + def __imul__(self, arr_like): + """Performs in place element-wise multiplication between two array like objects""" + if self.encrypted: + return NotImplemented + + arr_like = _ensure_ndarray(arr_like) + self.data = self.data * arr_like + return self.data + + def __truediv__(self, arr_like): + """Performs element-wise division between two array like objects""" + if self.encrypted: + return NotImplemented + + arr_like = _ensure_ndarray(arr_like) + return self.data / arr_like + + def __itruediv__(self, arr_like): + """Performs in place element-wise subtraction between two array like objects""" + if self.encrypted: + return NotImplemented + + arr_like = _ensure_ndarray(arr_like) + self.data = self.data / arr_like + return self.data
diff --git a/syft/test/__init__.py b/syft/test/__init__.py deleted file mode 100644 diff --git a/tests/test_tensor.py b/tests/test_tensor.py new file mode 100644 --- /dev/null +++ b/tests/test_tensor.py @@ -0,0 +1,66 @@ +from syft import TensorBase +import unittest +import numpy as np + +# Here's our "unit tests". +class AddTests(unittest.TestCase): + def testSimple(self): + t = TensorBase(np.array([1,2,3])) + self.assertTrue(np.array_equal(t + np.array([1,2,3]), [2,4,6])) + + def testInplace(self): + t = TensorBase(np.array([1,2,3])) + t += np.array([1,2,3]) + self.assertTrue(np.array_equal(t.data, [2,4,6])) + + def testScalar(self): + t = TensorBase(np.array([1,2,3])) + self.assertTrue(np.array_equal(t + 2, [3, 4, 5])) + +class SubTests(unittest.TestCase): + def testSimple(self): + t = TensorBase(np.array([1,2,3])) + self.assertTrue(np.array_equal(t - np.array([1,2,3]), [0,0,0])) + + def testInplace(self): + t = TensorBase(np.array([1,2,3])) + t -= np.array([1,2,3]) + self.assertTrue(np.array_equal(t.data, [0,0,0])) + + def testScalar(self): + t = TensorBase(np.array([1,2,3])) + self.assertTrue(np.array_equal(t - 1, [0, 1, 2])) + +class MultTests(unittest.TestCase): + def testSimple(self): + t = TensorBase(np.array([1,2,3])) + self.assertTrue(np.array_equal(t * np.array([1,2,3]), [1,4,9])) + + def testInplace(self): + t = TensorBase(np.array([1,2,3])) + t *= np.array([1,2,3]) + self.assertTrue(np.array_equal(t.data, [1,4,9])) + + def testScalar(self): + t = TensorBase(np.array([1,2,3])) + self.assertTrue(np.array_equal(t * 2, [2, 4, 6])) + +class DivTests(unittest.TestCase): + def testSimple(self): + t = TensorBase(np.array([2,4,8])) + self.assertTrue(np.array_equal(t / np.array([2,2,2]), [1,2,4])) + + def testInplace(self): + t = TensorBase(np.array([1,2,3])) + t *= np.array([1,2,3]) + self.assertTrue(np.array_equal(t.data, [1,4,9])) + + def testScalar(self): + t = TensorBase(np.array([2,4,6])) + self.assertTrue(np.array_equal(t / 2, [1, 2, 3])) + +def main(): + unittest.main() + +if __name__ == '__main__': + main() \ No newline at end of file
Implement Base Tensor Object In this ticket, we want to create a new basic type called a "Tensor". A Tensor is a nested list of numbers with an arbitrary number of dimensions. With one dimension, it's a list of numbers known as a "vector". With two dimensions, it's a list of lists of numbers known as a "matrix". In this ticket, we want to build our implementation of Tensor with inspiration from PyTorch's [Tensor](https://github.com/pytorch/pytorch/blob/master/torch/tensor.py) object ([Tensor Docs](http://pytorch.org/docs/master/tensors.html)). So, in this ticket, you should build a basic tensor class. You should be able to pass in as an argument an arbitrary shape (number of rows, columns, etc.) when you create it. Furthermore, we want this basic class to support elementwise addition, subtraction, multiplication, and division. Acceptance Criteria: - __init__ supports initializing a tensor with an arbitrary number of dimensions and arbitrary scalar type (test with float and int) - elementwise operators for +-/* and their inline operators should be overridden - elementwise operations should check to make sure both tensors are of identical dimension - elementwise operators should also support (and automatically detect!) the input of a single number, which should be applied to the entire tensor (aka... multiply every number by "5").
Does this depend on #10? Do we wanna extend this Tensor class off of the generic Tensor that will be created? Ah1 I need to put this in the Contributor Quickstart Guide. Install the ZenHub plugin. zenhub.com That will show you that this ticket is a subset of #10 and in fact the first stepping stone to achieving #10
2017-08-10T23:42:41
OpenMined/PySyft
122
OpenMined__PySyft-122
[ "102" ]
16dae46b154dd755c18e941409b4ec771f5e2ca5
diff --git a/syft/tensor.py b/syft/tensor.py --- a/syft/tensor.py +++ b/syft/tensor.py @@ -8,7 +8,7 @@ def _ensure_ndarray(arr): class TensorBase(object): """ - A base tensor class that perform basic element-wise operation such as + A base tensor class that perform basic element-wise operation such as addition, subtraction, multiplication and division """ @@ -83,3 +83,20 @@ def __itruediv__(self, arr_like): arr_like = _ensure_ndarray(arr_like) self.data = self.data / arr_like return self.data + + def shape(self): + """Returns a tuple of input array dimensions.""" + if self.encrypted: + return NotImplemented + + return self.data.shape + + def sum(self, dim=None): + """Returns the sum of all elements in the input array.""" + if self.encrypted: + return NotImplemented + + if dim is None: + return self.data.sum() + else: + return self.data.sum(axis=dim)
diff --git a/tests/test_tensor.py b/tests/test_tensor.py --- a/tests/test_tensor.py +++ b/tests/test_tensor.py @@ -7,7 +7,7 @@ class AddTests(unittest.TestCase): def testSimple(self): t = TensorBase(np.array([1,2,3])) self.assertTrue(np.array_equal(t + np.array([1,2,3]), [2,4,6])) - + def testInplace(self): t = TensorBase(np.array([1,2,3])) t += np.array([1,2,3]) @@ -21,7 +21,7 @@ class SubTests(unittest.TestCase): def testSimple(self): t = TensorBase(np.array([1,2,3])) self.assertTrue(np.array_equal(t - np.array([1,2,3]), [0,0,0])) - + def testInplace(self): t = TensorBase(np.array([1,2,3])) t -= np.array([1,2,3]) @@ -58,9 +58,23 @@ def testInplace(self): def testScalar(self): t = TensorBase(np.array([2,4,6])) self.assertTrue(np.array_equal(t / 2, [1, 2, 3])) - + +class ShapeTests(unittest.TestCase): + def testShape(self): + t = TensorBase(np.array([[0, 1], [0, 5]])) + self.assertTrue(np.array_equal(t.shape(), (2, 2))) + +class SumTests(unittest.TestCase): + def testDimNoneInt(self): + t = TensorBase(np.array([1,2,3])) + self.assertTrue(np.array_equal(t.sum(), 6)) + + def testDimIsNotNoneInt(self): + t = TensorBase(np.array([[0, 1], [0, 5]])) + self.assertTrue(np.array_equal(t.sum(dim=1), [1, 5])) + def main(): unittest.main() if __name__ == '__main__': - main() \ No newline at end of file + main()
Implement Default sum Functionality for Base Tensor Type **User Story A:** As a Data Scientist using Syft's Base Tensor type, I want to leverage a default method for computing operations on a Tensor of arbitrary type. For this ticket to be complete, sum() should return a new tensor. For a reference on the operation this performs check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation. **Acceptance Criteria:** - If the Base Tensor type's attribute "encrypted" is set to True, it should return a NotImplemented error. - a unit test demonstrating the correct operation on the Base Tensor type implemented over int and float Tensors. - inline documentation in the python code. For inspiration on inline documentation, please check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation for this operator.
2017-08-12T11:07:35
OpenMined/PySyft
124
OpenMined__PySyft-124
[ "20", "24" ]
bde42bc82a49bd636c9e0d63bb845aa4bcb1e288
diff --git a/syft/tensor.py b/syft/tensor.py --- a/syft/tensor.py +++ b/syft/tensor.py @@ -84,6 +84,19 @@ def __itruediv__(self, arr_like): self.data = self.data / arr_like return self.data + def abs(self): + """Returns absolute value of tensor as a new tensor""" + if self.encrypted: + return NotImplemented + return np.absolute(self.data) + + def abs_(self): + """Replaces tensor values with its absolute value""" + if self.encrypted: + return NotImplemented + self.data=np.absolute(self.data) + return self.data + def shape(self): """Returns a tuple of input array dimensions.""" if self.encrypted: @@ -100,3 +113,33 @@ def sum(self, dim=None): return self.data.sum() else: return self.data.sum(axis=dim) + + def addmm(self,tensor2,mat,beta=1,alpha=1): + """Performs ((Mat*Beta)+((Tensor1.Tensor2)*Alpha)) and returns the result as a Tensor + Tensor1.Tensor2 is performed as Matrix product of two array The behavior depends on the arguments in the following way. + *If both tensors are 1-dimensional, their dot product is returned. + *If both arguments are 2-D they are multiplied like conventional matrices. + *If either argument is N-D, N > 2, it is treated as a stack of matrices residing in the last two indexes and broadcast accordingly. + *If the first argument is 1-D, it is promoted to a matrix by prepending a 1 to its dimensions. After matrix multiplication the prepended 1 is removed. + *If the second argument is 1-D, it is promoted to a matrix by appending a 1 to its dimensions. After matrix multiplication the appended 1 is removed. + """ + if self.encrypted or tensor2.encrypted or mat.encrypted: + return NotImplemented + else: + return TensorBase(np.array((mat*beta)+((np.matmul(self.data,tensor2.data))*alpha))) + + def addmm_(self,tensor2,mat,beta=1,alpha=1): + """Performs ((Mat*Beta)+((Tensor1.Tensor2)*Alpha)) and updates Tensor1 with result and reurns it + Tensor1.Tensor2 is performed as Matrix product of two array The behavior depends on the arguments in the following way. + *If both tensors are 1-dimensional, their dot product is returned. + *If both arguments are 2-D they are multiplied like conventional matrices. + *If either argument is N-D, N > 2, it is treated as a stack of matrices residing in the last two indexes and broadcast accordingly. + *If the first argument is 1-D, it is promoted to a matrix by prepending a 1 to its dimensions. After matrix multiplication the prepended 1 is removed. + *If the second argument is 1-D, it is promoted to a matrix by appending a 1 to its dimensions. After matrix multiplication the appended 1 is removed. + """ + if self.encrypted is True or tensor2.encrypted is True or mat.encrypted is True: + return NotImplemented + else: + self.data=np.array((mat*beta)+((np.matmul(self.data,tensor2.data))*alpha)) + return self +
diff --git a/tests/test_tensor.py b/tests/test_tensor.py --- a/tests/test_tensor.py +++ b/tests/test_tensor.py @@ -59,6 +59,15 @@ def testScalar(self): t = TensorBase(np.array([2,4,6])) self.assertTrue(np.array_equal(t / 2, [1, 2, 3])) +class AbsTests(unittest.TestCase): + + def testabs(self): + t = TensorBase(np.array([-1,-2,3])) + self.assertTrue(np.array_equal(t.abs(),[1,2,3])) + def testabs_(self): + t = TensorBase(np.array([-1,-2,3])) + self.assertTrue(np.array_equal(t.abs_(),t.data)) + class ShapeTests(unittest.TestCase): def testShape(self): t = TensorBase(np.array([[0, 1], [0, 5]])) @@ -73,6 +82,35 @@ def testDimIsNotNoneInt(self): t = TensorBase(np.array([[0, 1], [0, 5]])) self.assertTrue(np.array_equal(t.sum(dim=1), [1, 5])) +class addmm(unittest.TestCase): + def testaddmm1d(self): + t1=TensorBase(np.array([1,2,3])) + t2=TensorBase(np.array([2,3,4])) + mat=TensorBase(np.array([5])) + out=t1.addmm(t2,mat,beta=2,alpha=2) + self.assertTrue(np.array_equal(out.data,[50])) + + def testaddmm2d(self): + t1=TensorBase(np.array([[1,2],[1,2]])) + t2=TensorBase(np.array([[1,2],[1,2]])) + mat=TensorBase(np.array([[2,3],[3,4]])) + out=t1.addmm(t2,mat,beta=2,alpha=2) + self.assertTrue(np.array_equal(out.data,[[10,18],[12,20]])) + + def testaddmm_1d(self): + t1=TensorBase(np.array([1,2,3])) + t2=TensorBase(np.array([2,3,4])) + mat=TensorBase(np.array([5])) + t1.addmm_(t2,mat,beta=2,alpha=2) + self.assertTrue(np.array_equal(t1.data,[50])) + + def testaddmm_2d(self): + t1=TensorBase(np.array([[1,2],[1,2]])) + t2=TensorBase(np.array([[1,2],[1,2]])) + mat=TensorBase(np.array([[2,3],[3,4]])) + t1.addmm_(t2,mat,beta=2,alpha=2) + self.assertTrue(np.array_equal(t1.data,[[10,18],[12,20]])) + def main(): unittest.main()
Implement Default Absolute Value Functions in Base Tensor Type **User Story A:** As a Data Scientist using Syft's Base Tensor type, we want to implement a default method for computing the elementwise absolute value of a Tensor of arbitrary type. abs() should return a new tensor and abs_ should perform the operation inline. For a great reference on how **Acceptance Criteria:** - If the Base Tensor type's attribute "encrypted" is set to True, it should return a NotImplemented error. - a unit test demonstrating the correct operation of abs() and abs_() on the Base Tensor type implemented over int and float Tensors. - inline documentation in the python code. For inspiration on inline documentation, please check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation for this operator. Implement Default addmm Functionality in Base Tensor Type **User Story A:** As a Data Scientist using Syft's Base Tensor type, we want to implement a default method for computing each operation on a Tensor of arbitrary type. addmm_() should return a new tensor and addmm_() should perform the operation inline. For a reference on the operation this performs check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation. **Acceptance Criteria:** - If the Base Tensor type's attribute "encrypted" is set to True, it should return a NotImplemented error. - a unit test demonstrating the correct operation of addmm() and addmm_() on the Base Tensor type implemented over int and float Tensors. - inline documentation in the python code. For inspiration on inline documentation, please check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation for this operator.
2017-08-12T21:15:08
OpenMined/PySyft
139
OpenMined__PySyft-139
[ "138" ]
bb1e78015a51de36f58ce5beb74b8f0c120aa131
diff --git a/syft/tensor.py b/syft/tensor.py --- a/syft/tensor.py +++ b/syft/tensor.py @@ -63,7 +63,7 @@ def __iadd__(self, tensor): return NotImplemented tensor = _ensure_tensorbase(tensor) - self.data = self.data + tensor.data + self.data += tensor.data return self def __sub__(self, tensor): @@ -80,7 +80,7 @@ def __isub__(self, tensor): return NotImplemented tensor = _ensure_tensorbase(tensor) - self.data = self.data - tensor.data + self.data -= tensor.data return self def __eq__(self, tensor): @@ -118,7 +118,7 @@ def __imul__(self, tensor): return NotImplemented tensor = _ensure_tensorbase(tensor) - self.data = self.data * tensor.data + self.data *= tensor.data return self def __truediv__(self, tensor): @@ -135,7 +135,7 @@ def __itruediv__(self, tensor): return NotImplemented tensor = _ensure_tensorbase(tensor) - self.data = self.data / tensor.data + self.data /= tensor.data return self def abs(self):
Inplace methods in TensorBase class not inplace Some of our inplace methods in the TensorBase class are not inplace. **Example** For addition, Inplace: `self.data += tensor.data` Not inplace: `self.data = self.data + tensor.data` **Task** Modify `__iadd__`, `__isub__`, `__imul__`, `__itruediv__` to be inplace operations following the above example.
2017-08-15T07:41:19
OpenMined/PySyft
147
OpenMined__PySyft-147
[ "128" ]
82678acdba4a91316a95f526c88d983ace02f19a
diff --git a/syft/tensor.py b/syft/tensor.py --- a/syft/tensor.py +++ b/syft/tensor.py @@ -138,6 +138,13 @@ def __itruediv__(self, tensor): self.data /= tensor.data return self + def __getitem__(self, position): + """Get value at a specific index.""" + if self.encrypted: + return NotImplemented + + return TensorBase(self.data[position], self.encrypted) + def abs(self): """Returns absolute value of tensor as a new tensor""" if self.encrypted:
diff --git a/tests/test_tensor.py b/tests/test_tensor.py --- a/tests/test_tensor.py +++ b/tests/test_tensor.py @@ -118,6 +118,13 @@ def testIneqOp(self): self.assertTrue(t1 != t2) +class IndexTests(unittest.TestCase): + def testIndexing(self): + t1 = TensorBase(np.array([1.2, 2, 3])) + self.assertEqual(1.2, t1[0].data) + self.assertEqual(3, t1[-1].data) + + class addmm(unittest.TestCase): def testaddmm1d(self): t1=TensorBase(np.array([1,2,3]))
Support indexing of TensorBase objects Indexing in Python is an extremely useful operation supported by major libraries like Numpy and Pandas. Therefore, we would like our TensorBase objects to support this operation as well. This [StackOverflow answer](https://stackoverflow.com/a/509295) contains a good explanation of how it works. Since we are wrapping `numpy`'s `ndarray` in our TensorBase classes, a way of implementing it would be to pipe the operations through to `numpy`'s implementation. **Acceptance criteria** * Must support reverse indexing (e.g. `[-1]`). * Contains unit tests demonstrating indexing behavior.
2017-08-16T14:18:15
OpenMined/PySyft
155
OpenMined__PySyft-155
[ "119" ]
0a47930661009b8f78a0a806971ebb5a12ea1e0f
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -28,5 +28,5 @@ def read(fname): scripts=['bin/syft_cmd'], install_requires=requirements, setup_requires=['pytest-runner'], - tests_require=['pytest'] + tests_require=['pytest', 'pytest-flake8'] )
Set up CI for automated testing and style checks Now that our codebase is growing (hooray!), we should set up CI for automated testing and style checks (PEP8, PEP257). Choices include [CircleCI](https://circleci.com) and [TravisCI](https://travis-ci.org). These can be integrated into our repo such that every pull request will be checked before review.
I have used Travis before and could set it up to run tests and check for any style guide violations tomorrow. Assign it to me if nobody else is already working on it. Quick question: Should the build fail if something violates PEP8/PEP257? > Quick question: Should the build fail if something violates PEP8/PEP257? Yes! I would recommend using https://pypi.python.org/pypi/flake8
2017-08-17T19:41:09
OpenMined/PySyft
156
OpenMined__PySyft-156
[ "142" ]
a2c92f8f432281cec1df14a7dd1f7b920411d0c6
diff --git a/syft/math.py b/syft/math.py --- a/syft/math.py +++ b/syft/math.py @@ -101,7 +101,7 @@ def cumprod(tensor,dim=0): return TensorBase(np.cumprod(tensor.data,dim)) -ef addmm(tensor1, tensor2, mat, beta=1, alpha=1): +def addmm(tensor1, tensor2, mat, beta=1, alpha=1): """Performs ((Mat*Beta)+((Tensor1.Tensor2)*Alpha)) and returns the result as a Tensor Tensor1.Tensor2 is performed as Matrix product of two array The behavior depends on the arguments in the following way. *If both tensors are 1-dimensional, their dot product is returned.
addmm tests failing As of bb1e78015a51de36f58ce5beb74b8f0c120aa131 : ``` $ pytest ===================================================================== test session starts ===================================================================== platform darwin -- Python 3.6.2, pytest-3.2.1, py-1.4.34, pluggy-0.4.0 rootdir: /Users/swaroop/personal/openmined/PySyft, inifile: collected 33 items tests/test_math.py ....... tests/test_tensor.py ......................FFFF ========================================================================== FAILURES =========================================================================== ______________________________________________________________________ addmm.testaddmm1d ______________________________________________________________________ self = <PySyft.tests.test_tensor.addmm testMethod=testaddmm1d> def testaddmm1d(self): t1=TensorBase(np.array([1,2,3])) t2=TensorBase(np.array([2,3,4])) mat=TensorBase(np.array([5])) out=t1.addmm(t2,mat,beta=2,alpha=2) > self.assertTrue(np.array_equal(out.data,[50])) E AssertionError: False is not true tests/test_tensor.py:127: AssertionError ______________________________________________________________________ addmm.testaddmm2d ______________________________________________________________________ self = <PySyft.tests.test_tensor.addmm testMethod=testaddmm2d> def testaddmm2d(self): t1=TensorBase(np.array([[1,2],[1,2]])) t2=TensorBase(np.array([[1,2],[1,2]])) mat=TensorBase(np.array([[2,3],[3,4]])) out=t1.addmm(t2,mat,beta=2,alpha=2) > self.assertTrue(np.array_equal(out.data,[[10,18],[12,20]])) E AssertionError: False is not true tests/test_tensor.py:134: AssertionError _____________________________________________________________________ addmm.testaddmm_1d ______________________________________________________________________ self = <PySyft.tests.test_tensor.addmm testMethod=testaddmm_1d> def testaddmm_1d(self): t1=TensorBase(np.array([1,2,3])) t2=TensorBase(np.array([2,3,4])) mat=TensorBase(np.array([5])) t1.addmm_(t2,mat,beta=2,alpha=2) > self.assertTrue(np.array_equal(t1.data,[50])) E AssertionError: False is not true tests/test_tensor.py:141: AssertionError _____________________________________________________________________ addmm.testaddmm_2d ______________________________________________________________________ self = <PySyft.tests.test_tensor.addmm testMethod=testaddmm_2d> def testaddmm_2d(self): t1=TensorBase(np.array([[1,2],[1,2]])) t2=TensorBase(np.array([[1,2],[1,2]])) mat=TensorBase(np.array([[2,3],[3,4]])) t1.addmm_(t2,mat,beta=2,alpha=2) > self.assertTrue(np.array_equal(t1.data,[[10,18],[12,20]])) E AssertionError: False is not true tests/test_tensor.py:148: AssertionError ============================================================= 4 failed, 29 passed in 0.24 seconds ============================================================= ```
The error is coming due to the new inplace implementations of +. I will make the changes with the newer implementation of addmm as disscussed with @samsontmr Done More tests are failing after those were fixed: ![image](https://user-images.githubusercontent.com/6272414/29462390-cdb14a52-83f4-11e7-8782-f1daaa145c12.png) okay there is a d missing in def will change it
2017-08-18T15:15:41
OpenMined/PySyft
168
OpenMined__PySyft-168
[ "47" ]
804ecf0b4b992e95d100666a7a2c4a3b5d3df33c
diff --git a/syft/tensor.py b/syft/tensor.py --- a/syft/tensor.py +++ b/syft/tensor.py @@ -410,6 +410,34 @@ def baddbmm_(self, tensor2, mat, beta=1, alpha=1): self.data += (mat.data * beta) return self + def exp(self): + """Computes the exponential of each element in tensor.""" + if self.encrypted: + return NotImplemented + out = np.exp(self.data) + return TensorBase(out) + + def exp_(self): + """Computes the exponential of each element inplace.""" + if self.encrypted: + return NotImplemented + self.data = np.exp(self.data) + return self + + def frac(self): + """"Computes the fractional portion of each element in tensor.""" + if self.encrypted: + return NotImplemented + out = np.modf(self.data)[0] + return TensorBase(out) + + def frac_(self): + """"Computes the fractional portion of each element inplace.""" + if self.encrypted: + return NotImplemented + self.data = np.modf(self.data)[0] + return self + def sigmoid_(self): """ Performs inline sigmoid function on the Tensor elementwise
diff --git a/tests/test_tensor.py b/tests/test_tensor.py --- a/tests/test_tensor.py +++ b/tests/test_tensor.py @@ -289,3 +289,31 @@ def testbaddbmm_(self): t1.baddbmm_(t2, mat, beta=2, alpha=2) self.assertTrue(np.array_equal(t1.data, [[[62, 92], [96, 142]], [[122, 184], [28, 42]]])) + + +class expTests(unittest.TestCase): + def testexp(self): + t3 = TensorBase(np.array([[[1, 3], [3, 5]], + [[5, 7], [9, 1]]])) + out = t3.exp() + self.assertTrue(np.allclose(out.data, [[[2.71828183e+00, 2.00855369e+01], [2.00855369e+01, 1.48413159e+02]], + [[1.48413159e+02, 1.09663316e+03], [8.10308393e+03, 2.71828183e+00]]])) + + def testexp_(self): + t3 = TensorBase(np.array([[[1, 3], [3, 5]], + [[5, 7], [9, 1]]])) + t3.exp_() + self.assertTrue(np.allclose(t3.data, [[[2.71828183e+00, 2.00855369e+01], [2.00855369e+01, 1.48413159e+02]], + [[1.48413159e+02, 1.09663316e+03], [8.10308393e+03, 2.71828183e+00]]])) + + +class fracTests(unittest.TestCase): + def testfrac(self): + t3 = TensorBase(np.array([1.23, 4.56, 7.89])) + out = t3.frac() + self.assertTrue(np.allclose(out.data, [0.23, 0.56, 0.89])) + + def testfrac_(self): + t3 = TensorBase(np.array([1.23, 4.56, 7.89])) + t3.frac_() + self.assertTrue(np.allclose(t3.data, [0.23, 0.56, 0.89]))
Implement Default frac Functionality for Base Tensor Type **User Story A:** As a Data Scientist using Syft's Base Tensor type, we want to implement a default method for computing operations on a Tensor of arbitrary type. For this ticket to be complete, frac() should return a new tensor and frac_() should perform the operation inline. For a reference on the operation this performs check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation. **Acceptance Criteria:** - If the Base Tensor type's attribute "encrypted" is set to True, it should return a NotImplemented error. - a unit test demonstrating the correct operation on the Base Tensor type implemented over int and float Tensors. - inline documentation in the python code. For inspiration on inline documentation, please check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation for this operator.
2017-08-21T11:00:27
OpenMined/PySyft
188
OpenMined__PySyft-188
[ "58" ]
a81fde47c4593a787f9bb61dd655af58497bef4a
diff --git a/syft/tensor.py b/syft/tensor.py --- a/syft/tensor.py +++ b/syft/tensor.py @@ -518,3 +518,41 @@ def reciprocal_(self): if self.encrypted: return NotImplemented self.data = 1 / np.array(self.data) + + def log(self): + """performs elementwise logarithm operation + and returns a new Tensor""" + if self.encrypted: + return NotImplemented + out = np.log(self.data) + return TensorBase(out) + + def log_(self): + """performs elementwise logarithm operation inplace""" + if self.encrypted: + return NotImplemented + self.data = np.log(self.data) + return self + + def log1p(self): + """performs elementwise log(1+x) operation + and returns new tensor""" + if self.encrypted: + return NotImplemented + out = np.log1p(self.data) + return TensorBase(out) + + def log1p_(self): + """performs elementwise log(1+x) operation inplace""" + if self.encrypted: + return NotImplemented + self.data = np.log1p(self.data) + return self + + def log_normal_(self, mean=0, stdev=1.0): + """Fills give tensor with samples from a lognormal distribution + with given mean and stdev""" + if self.encrypted: + return NotImplemented + self.data = np.random.lognormal(mean, stdev, self.shape()) + return self
diff --git a/tests/test_tensor.py b/tests/test_tensor.py --- a/tests/test_tensor.py +++ b/tests/test_tensor.py @@ -2,6 +2,7 @@ import syft import unittest import numpy as np +import math # Here's our "unit tests". @@ -374,3 +375,21 @@ def testrsqrt_(self): t1 = TensorBase(np.array([2, 3, 4])) t1.reciprocal_() self.assertTrue(np.allclose(t1.data, [0.5, 0.33333333, 0.25])) + + +class logTests(unittest.TestCase): + def testLog(self): + t1 = TensorBase(np.array([math.exp(1), math.exp(2), math.exp(3)])) + self.assertTrue(np.array_equal((t1.log()).data, [1., 2., 3.])) + + def testLog_(self): + t1 = TensorBase(np.array([math.exp(1), math.exp(2), math.exp(3)])) + self.assertTrue(np.array_equal((t1.log_()).data, [1., 2., 3.])) + + def testLog1p(self): + t1 = TensorBase(np.array([1, 2, 3])) + self.assertTrue(np.allclose((t1.log1p()).data, [0.69314718, 1.09861229, 1.38629436])) + + def testLog1p_(self): + t1 = TensorBase(np.array([1, 2, 3])) + self.assertTrue(np.allclose((t1.log1p_()).data, [0.69314718, 1.09861229, 1.38629436]))
Implement Default log Functionality for Base Tensor Type **User Story A:** As a Data Scientist using Syft's Base Tensor type, we want to implement a default method for computing operations on a Tensor of arbitrary type. For this ticket to be complete, log(), log1p(), and log_normal() should return a new tensor and log_(), log1p_(), and log_normal_() should perform the operation inline. For a reference on the operation this performs check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation. **Acceptance Criteria:** - If the Base Tensor type's attribute "encrypted" is set to True, it should return a NotImplemented error. - a unit test demonstrating the correct operation on the Base Tensor type implemented over int and float Tensors. - inline documentation in the python code. For inspiration on inline documentation, please check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation for this operator.
2017-08-26T08:14:00
OpenMined/PySyft
199
OpenMined__PySyft-199
[ "32" ]
c7db3beab0702390c8acd28e257dbdda53a4c9ca
diff --git a/syft/tensor.py b/syft/tensor.py --- a/syft/tensor.py +++ b/syft/tensor.py @@ -621,6 +621,19 @@ def log_normal_(self, mean=0, stdev=1.0): self.data = np.random.lognormal(mean, stdev, self.shape()) return self + def clamp(self, minimum=None, maximum=None): + """Returns a clamped tensor into the range [min, max], elementwise""" + if self.encrypted: + return NotImplemented + return TensorBase(np.clip(self.data, a_min=minimum, a_max=maximum)) + + def clamp_(self, minimum=None, maximum=None): + """Clamp the tensor, in-place, elementwise into the range [min, max]""" + if self.encrypted: + return NotImplemented + self.data = np.clip(self.data, a_min=minimum, a_max=maximum) + return self + def uniform_(self, low=0, high=1): """Fills the tensor in-place with numbers sampled unifromly over the half-open interval [low,high) or from the uniform distribution"""
diff --git a/tests/test_tensor.py b/tests/test_tensor.py --- a/tests/test_tensor.py +++ b/tests/test_tensor.py @@ -469,6 +469,32 @@ def testLog1p_(self): self.assertTrue(np.allclose((t1.log1p_()).data, [0.69314718, 1.09861229, 1.38629436])) +class clampTests(unittest.TestCase): + def testClampInt(self): + t1 = TensorBase(np.arange(10)) + t2 = t1.clamp(minimum=2, maximum=7) + expected_tensor = TensorBase(np.array([2, 2, 2, 3, 4, 5, 6, 7, 7, 7])) + self.assertEqual(t2, expected_tensor) + + def testClampFloat(self): + t1 = TensorBase(np.arange(1, step=0.1)) + t2 = t1.clamp(minimum=0.2, maximum=0.7) + expected_tensor = TensorBase(np.array([0.2, 0.2, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.7, 0.7])) + self.assertEqual(t2, expected_tensor) + + def testClampIntInPlace(self): + t1 = TensorBase(np.arange(10)) + t1.clamp_(minimum=2, maximum=7) + expected_tensor = TensorBase(np.array([2, 2, 2, 3, 4, 5, 6, 7, 7, 7])) + self.assertEqual(t1, expected_tensor) + + def testClampFloatInPlace(self): + t1 = TensorBase(np.arange(1, step=0.1)) + t1.clamp_(minimum=0.2, maximum=0.7) + expected_tensor = TensorBase(np.array([0.2, 0.2, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.7, 0.7])) + self.assertEqual(t1, expected_tensor) + + class uniformTests(unittest.TestCase): def testUniform(self): t1 = TensorBase(np.zeros(4))
Implement Default clamp Functionality for Base Tensor Type **User Story A:** As a Data Scientist using Syft's Base Tensor type, we want to implement a default method for computing operations on a Tensor of arbitrary type. For this ticket to be complete, clamp() should return a new tensor and clamp_() should perform the operation inline. For a reference on the operation this performs check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation. **Acceptance Criteria:** - If the Base Tensor type's attribute "encrypted" is set to True, it should return a NotImplemented error. - a unit test demonstrating the correct operation on the Base Tensor type implemented over int and float Tensors. - inline documentation in the python code. For inspiration on inline documentation, please check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation for this operator.
2017-09-01T03:39:50
OpenMined/PySyft
216
OpenMined__PySyft-216
[ "34" ]
02ba82e94de28b2dca463f06c22c7f4df4f78dd3
diff --git a/syft/tensor.py b/syft/tensor.py --- a/syft/tensor.py +++ b/syft/tensor.py @@ -858,6 +858,19 @@ def size(self): else: return self.data.size + def cumprod(self, dim=0): + """Returns the cumulative product of elements in the dimension dim.""" + if self.encrypted: + return NotImplemented + return syft.math.cumprod(self, dim) + + def cumprod_(self, dim=0): + """calculate in-place the cumulative product of elements in the dimension dim.""" + if self.encrypted: + return NotImplemented + self.data = syft.math.cumprod(self, dim).data + return self + def split(self, split_size, dim=0): """Returns tuple of tensors of equally sized tensor/chunks (if possible)""" if self.encrypted:
diff --git a/tests/test_tensor.py b/tests/test_tensor.py --- a/tests/test_tensor.py +++ b/tests/test_tensor.py @@ -647,6 +647,23 @@ def testNonZero(self): self.assertTrue(np.array_equal(t2.data, np.array([[0, 1, 1], [0, 1, 2]]))) +class cumprodTest(unittest.TestCase): + def testCumprod(self): + t1 = TensorBase(np.array([[1, 2, 3], [4, 5, 6]])) + t2 = TensorBase(np.array([[1.0, 2.0, 3.0], [4.0, 10.0, 18.0]])) + t3 = TensorBase(np.array([[1, 2, 6], [4, 20, 120]])) + self.assertTrue(np.equal(t1.cumprod(dim=0), t2).all()) + self.assertTrue(np.equal(t1.cumprod(dim=1), t3).all()) + + def testCumprod_(self): + t1 = TensorBase(np.array([[1, 2, 3], [4, 5, 6]])) + t2 = TensorBase(np.array([[1.0, 2.0, 3.0], [4.0, 10.0, 18.0]])) + t3 = TensorBase(np.array([[1, 2, 6], [4, 20, 120]])) + self.assertTrue(np.equal(t1.cumprod_(dim=0), t2).all()) + t1 = TensorBase(np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])) + self.assertTrue(np.equal(t1.cumprod_(dim=1), t3).all()) + + class splitTests(unittest.TestCase): def testSplit(self): t1 = TensorBase(np.arange(8.0))
Implement Default cumprod Functionality for Base Tensor Type **User Story A:** As a Data Scientist using Syft's Base Tensor type, we want to implement a default method for computing operations on a Tensor of arbitrary type. For this ticket to be complete, cumprod() should return a new tensor. For a reference on the operation this performs check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation. **Acceptance Criteria:** - If the Base Tensor type's attribute "encrypted" is set to True, it should return a NotImplemented error. - a unit test demonstrating the correct operation on the Base Tensor type implemented over int and float Tensors. - inline documentation in the python code. For inspiration on inline documentation, please check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation for this operator.
I'll take this if no one is working on it.
2017-09-05T05:27:42
OpenMined/PySyft
232
OpenMined__PySyft-232
[ "91" ]
6c049ac8c4c2e9598bbd495d9a5fd716d3e46126
diff --git a/syft/tensor.py b/syft/tensor.py --- a/syft/tensor.py +++ b/syft/tensor.py @@ -1034,6 +1034,67 @@ def histc(self, bins=10, min=0, max=0): hist, edges = np.histogram(np.array(self.data), bins=bins, range=(min, max)) return TensorBase(hist) + def scatter_(self, dim, index, src): + """ + Writes all values from the Tensor src into self at the indices specified in the index Tensor. + The indices are specified with respect to the given dimension, dim, in the manner described in gather(). + + :param dim: The axis along which to index + :param index: The indices of elements to scatter + :param src: The source element(s) to scatter + :return: self + """ + index = _ensure_tensorbase(index) + if self.encrypted or index.encrypted: + return NotImplemented + if index.data.dtype != np.dtype('int_'): + raise TypeError("The values of index must be integers") + if self.data.ndim != index.data.ndim: + raise ValueError("Index should have the same number of dimensions as output") + if dim >= self.data.ndim or dim < -self.data.ndim: + raise IndexError("dim is out of range") + if dim < 0: + # Not sure why scatter should accept dim < 0, but that is the behavior in PyTorch's scatter + dim = self.data.ndim + dim + idx_xsection_shape = index.data.shape[:dim] + index.data.shape[dim + 1:] + self_xsection_shape = self.data.shape[:dim] + self.data.shape[dim + 1:] + if idx_xsection_shape != self_xsection_shape: + raise ValueError("Except for dimension " + str(dim) + + ", all dimensions of index and output should be the same size") + if (index.data >= self.data.shape[dim]).any() or (index.data < 0).any(): + raise IndexError("The values of index must be between 0 and (self.data.shape[dim] -1)") + + def make_slice(arr, dim, i): + slc = [slice(None)] * arr.ndim + slc[dim] = i + return slc + + # We use index and dim parameters to create idx + # idx is in a form that can be used as a NumPy advanced index for scattering of src param. in self.data + idx = [[*np.indices(idx_xsection_shape).reshape(index.data.ndim - 1, -1), + index.data[make_slice(index.data, dim, i)].reshape(1, -1)[0]] for i in range(index.data.shape[dim])] + idx = list(np.concatenate(idx, axis=1)) + idx.insert(dim, idx.pop()) + + if not np.isscalar(src): + src = _ensure_tensorbase(src) + if index.data.shape[dim] > src.data.shape[dim]: + raise IndexError("Dimension " + str(dim) + "of index can not be bigger than that of src ") + src_shape = src.data.shape[:dim] + src.data.shape[dim + 1:] + if idx_xsection_shape != src_shape: + raise ValueError("Except for dimension " + + str(dim) + ", all dimensions of index and src should be the same size") + # src_idx is a NumPy advanced index for indexing of elements in the src + src_idx = list(idx) + src_idx.pop(dim) + src_idx.insert(dim, np.repeat(np.arange(index.data.shape[dim]), np.prod(idx_xsection_shape))) + self.data[idx] = src.data[src_idx] + + else: + self.data[idx] = src + + return self + def serialize(self): return pickle.dumps(self)
diff --git a/tests/test_tensor.py b/tests/test_tensor.py --- a/tests/test_tensor.py +++ b/tests/test_tensor.py @@ -726,5 +726,100 @@ def testNe_(self): self.assertTrue(syft.equal(t1, TensorBase([1, 1, 1, 0]))) +class scatterTests(unittest.TestCase): + def testScatter_Numerical0(self): + t = TensorBase(np.zeros((3, 5))) + idx = TensorBase(np.array([[0, 0, 0, 0, 0]])) + src = 1.0 + dim = 0 + t.scatter_(dim=dim, index=idx, src=src) + self.assertTrue(np.array_equal(t.data, np.array([[1, 1, 1, 1, 1], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]))) + + def testScatter_Numerical1(self): + t = TensorBase(np.zeros((3, 5))) + idx = TensorBase(np.array([[0], [0], [0]])) + src = 1.0 + dim = 1 + t.scatter_(dim=dim, index=idx, src=src) + self.assertTrue(np.array_equal(t.data, np.array([[1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0]]))) + + def testScatter_Numerical2(self): + t = TensorBase(np.zeros((3, 5))) + idx = TensorBase(np.array([[0], [0], [0]])) + src = 1.0 + dim = -1 + t.scatter_(dim=dim, index=idx, src=src) + self.assertTrue(np.array_equal(t.data, np.array([[1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0]]))) + + def testScatter_Numerical3(self): + t = TensorBase(np.zeros((3, 5))) + idx = TensorBase(np.array([[0, 0, 0, 0, 0]])) + src = TensorBase(np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])) + dim = 0 + t.scatter_(dim=dim, index=idx, src=src) + self.assertTrue(np.array_equal(t.data, np.array([[1, 2, 3, 4, 5], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]))) + + def testScatter_Numerical4(self): + t = TensorBase(np.zeros((3, 5))) + idx = TensorBase(np.array([[0, 0, 0, 0, 0]])) + src = TensorBase(np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])) + dim = -2 + t.scatter_(dim=dim, index=idx, src=src) + self.assertTrue(np.array_equal(t.data, np.array([[1, 2, 3, 4, 5], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]))) + + def testScatter_Numerical5(self): + t = TensorBase(np.zeros((3, 5))) + idx = TensorBase(np.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])) + src = TensorBase(np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])) + dim = 0 + t.scatter_(dim=dim, index=idx, src=src) + self.assertTrue(np.array_equal(t.data, np.array([[6, 7, 8, 9, 10], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]))) + + def testScatter_Numerical6(self): + t = TensorBase(np.zeros((3, 4, 5))) + idx = [[[3, 0, 1, 1, 2], [0, 3, 3, 3, 3]], [[2, 0, 0, 0, 0], [2, 1, 0, 2, 0]], + [[0, 0, 1, 0, 2], [1, 3, 2, 2, 2]]] + src = [[[7, 84, 99, 71, 44], [79, 57, 2, 37, 62]], [[31, 44, 43, 54, 56], [72, 52, 21, 89, 95]], + [[5, 3, 99, 4, 52], [32, 88, 58, 62, 9]]] + dim = 1 + t.scatter_(dim=dim, index=idx, src=src) + expected = [[[79, 84, 0, 0, 0], [0, 0, 99, 71, 0], [0, 0, 0, 0, 44], [7, 57, 2, 37, 62]], + [[0, 44, 21, 54, 95], [0, 52, 0, 0, 0], [72, 0, 0, 89, 0], [0, 0, 0, 0, 0]], + [[5, 3, 0, 4, 0], [32, 0, 99, 0, 0], [0, 0, 58, 62, 9], [0, 88, 0, 0, 0]]] + self.assertTrue(np.array_equal(t.data, np.array(expected))) + + def testScatter_IndexType(self): + t = TensorBase(np.zeros((3, 5))) + idx = TensorBase(np.array([[0.0, 0.0, 0.0, 0.0, 0.0]])) + src = TensorBase(np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])) + dim = 0 + with self.assertRaises(Exception): + t.scatter_(dim=dim, index=idx, src=src) + + def testScatter_IndexOutOfRange(self): + t = TensorBase(np.zeros((3, 5))) + idx = TensorBase(np.array([[5, 0, 0, 0, 0]])) + src = TensorBase(np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])) + dim = 0 + with self.assertRaises(Exception): + t.scatter_(dim=dim, index=idx, src=src) + + def testScatter_DimOutOfRange(self): + t = TensorBase(np.zeros((3, 5))) + idx = TensorBase(np.array([[0, 0, 0, 0, 0]])) + src = TensorBase(np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])) + dim = 4 + with self.assertRaises(Exception): + t.scatter_(dim=dim, index=idx, src=src) + + def testScatter_index_src_dimension_mismatch(self): + t = TensorBase(np.zeros((3, 5))) + idx = TensorBase(np.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])) + src = TensorBase(np.array([[1, 2, 3, 4, 5]])) + dim = 1 + with self.assertRaises(Exception): + t.scatter_(dim=dim, index=idx, src=src) + + if __name__ == "__main__": unittest.main()
Implement Default scatter Functionality for Base Tensor Type **User Story A:** As a Data Scientist using Syft's Base Tensor type, I want to leverage a default method for computing operations on a Tensor of arbitrary type. For this ticket to be complete, scatter_() should operate inline. For a reference on the operation this performs check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation. **Acceptance Criteria:** - If the Base Tensor type's attribute "encrypted" is set to True, it should return a NotImplemented error. - a unit test demonstrating the correct operation on the Base Tensor type implemented over int and float Tensors. - inline documentation in the python code. For inspiration on inline documentation, please check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation for this operator.
I'm gonna go for this
2017-09-12T20:03:09
OpenMined/PySyft
233
OpenMined__PySyft-233
[ "48" ]
57cb74b0ec8a69c285a002e0a190d4c6603a06bc
diff --git a/syft/tensor.py b/syft/tensor.py --- a/syft/tensor.py +++ b/syft/tensor.py @@ -1051,9 +1051,8 @@ def histc(self, bins=10, min=0, max=0): def scatter_(self, dim, index, src): """ - Writes all values from the Tensor src into self at the indices specified in the index Tensor. - The indices are specified with respect to the given dimension, dim, in the manner described in gather(). - + Writes all values from the Tensor ``src`` into ``self`` at the indices specified in the ``index`` Tensor. + The indices are specified with respect to the given dimension, ``dim``, in the manner described in gather(). :param dim: The axis along which to index :param index: The indices of elements to scatter :param src: The source element(s) to scatter @@ -1110,6 +1109,32 @@ def make_slice(arr, dim, i): return self + def gather(self, dim, index): + """ + Gathers values along an axis specified by ``dim``. + For a 3-D tensor the output is specified by: + out[i][j][k] = input[index[i][j][k]][j][k] # if dim == 0 + out[i][j][k] = input[i][index[i][j][k]][k] # if dim == 1 + out[i][j][k] = input[i][j][index[i][j][k]] # if dim == 2 + :param dim: The axis along which to index + :param index: A tensor of indices of elements to gather + :return: tensor of gathered values + """ + index = _ensure_tensorbase(index) + if self.encrypted or index.encrypted: + return NotImplemented + idx_xsection_shape = index.data.shape[:dim] + index.data.shape[dim + 1:] + self_xsection_shape = self.data.shape[:dim] + self.data.shape[dim + 1:] + if idx_xsection_shape != self_xsection_shape: + raise ValueError("Except for dimension " + str(dim) + + ", all dimensions of index and self should be the same size") + if index.data.dtype != np.dtype('int_'): + raise TypeError("The values of index must be integers") + data_swaped = np.swapaxes(self.data, 0, dim) + index_swaped = np.swapaxes(index, 0, dim) + gathered = np.choose(index_swaped, data_swaped) + return TensorBase(np.swapaxes(gathered, 0, dim)) + def serialize(self): return pickle.dumps(self)
diff --git a/tests/test_tensor.py b/tests/test_tensor.py --- a/tests/test_tensor.py +++ b/tests/test_tensor.py @@ -750,6 +750,23 @@ def testNe_(self): self.assertTrue(syft.equal(t1, TensorBase([1, 1, 1, 0]))) +class gatherTests(unittest.TestCase): + def testGatherNumerical1(self): + t = TensorBase(np.array([[65, 17], [14, 25], [76, 22]])) + idx = TensorBase(np.array([[0], [1], [0]])) + dim = 1 + result = t.gather(dim=dim, index=idx) + self.assertTrue(np.array_equal(result.data, np.array([[65], [25], [76]]))) + + def testGatherNumerical2(self): + t = TensorBase(np.array([[47, 74, 44], [56, 9, 37]])) + idx = TensorBase(np.array([[0, 0, 1], [1, 1, 0], [0, 1, 0]])) + dim = 0 + result = t.gather(dim=dim, index=idx) + expexted = [[47, 74, 37], [56, 9, 44.], [47, 9, 44]] + self.assertTrue(np.array_equal(result.data, np.array(expexted))) + + class scatterTests(unittest.TestCase): def testScatter_Numerical0(self): t = TensorBase(np.zeros((3, 5)))
Implement Default gather Functionality for Base Tensor Type **User Story A:** As a Data Scientist using Syft's Base Tensor type, we want to implement a default method for computing operations on a Tensor of arbitrary type. For this ticket to be complete, gather() should return a new tensor. For a reference on the operation this performs check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation. **Acceptance Criteria:** - If the Base Tensor type's attribute "encrypted" is set to True, it should return a NotImplemented error. - a unit test demonstrating the correct operation on the Base Tensor type implemented over int and float Tensors. - inline documentation in the python code. For inspiration on inline documentation, please check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation for this operator.
I'm gonna do this.
2017-09-13T02:59:10
OpenMined/PySyft
237
OpenMined__PySyft-237
[ "92" ]
1df96853cc9f1e97f7b106eae3de5a6f62284809
diff --git a/syft/tensor.py b/syft/tensor.py --- a/syft/tensor.py +++ b/syft/tensor.py @@ -1160,6 +1160,22 @@ def serialize(self): def deserialize(b): return pickle.loads(b) + def index_select(self, dim, index): + """ + Returns a new Tensor which indexes the ``input`` Tensor along + dimension ``dim`` using the entries in ``index``. + + :param dim: dimension in which to index + :param index: 1D tensor containing the indices to index + :return: Tensor of selected indices + """ + index = _ensure_tensorbase(index) + if self.encrypted or index.encrypted: + return NotImplemented + if index.data.ndim > 1: + raise ValueError("Index is supposed to be 1D") + return TensorBase(self.data.take(index, axis=dim)) + def mv(self, tensorvector): if self.encrypted: raise NotImplemented
diff --git a/tests/test_tensor.py b/tests/test_tensor.py --- a/tests/test_tensor.py +++ b/tests/test_tensor.py @@ -751,6 +751,16 @@ def testNe_(self): self.assertTrue(syft.equal(t1, TensorBase([1, 1, 1, 0]))) +class index_selectTests(unittest.TestCase): + def testIndex_select(self): + t = TensorBase(np.reshape(np.arange(0, 2 * 3 * 4), (2, 3, 4))) + idx = np.array([1, 0]) + dim = 2 + result = t.index_select(dim=dim, index=idx) + expected = np.array([[[1, 0], [5, 4], [9, 8]], [[13, 12], [17, 16], [21, 20]]]) + self.assertTrue(np.array_equal(result.data, expected)) + + class gatherTests(unittest.TestCase): def testGatherNumerical1(self): t = TensorBase(np.array([[65, 17], [14, 25], [76, 22]]))
Implement Default select Functionality for Base Tensor Type **User Story A:** As a Data Scientist using Syft's Base Tensor type, I want to leverage a default method for computing operations on a Tensor of arbitrary type. For this ticket to be complete, select() should return a new tensor. For a reference on the operation this performs check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation. **Acceptance Criteria:** - If the Base Tensor type's attribute "encrypted" is set to True, it should return a NotImplemented error. - a unit test demonstrating the correct operation on the Base Tensor type implemented over int and float Tensors. - inline documentation in the python code. For inspiration on inline documentation, please check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation for this operator.
I'm gonna go for this @iamtrask PyTorch has a `index_select` [method](http://pytorch.org/docs/master/torch.html#torch.index_select). It has no `select` method. Is `index_select` what should be implemented? If yes, should I called it `select` or call it `index_select`? ah... index_select
2017-09-13T22:12:37
OpenMined/PySyft
240
OpenMined__PySyft-240
[ "85" ]
50c50da091ae6734237302efa5324d7dbed59164
diff --git a/syft/tensor.py b/syft/tensor.py --- a/syft/tensor.py +++ b/syft/tensor.py @@ -1160,6 +1160,37 @@ def serialize(self): def deserialize(b): return pickle.loads(b) + def remainder(self, divisor): + """ + Computes the element-wise remainder of division. + The divisor and dividend may contain both for integer and floating point numbers. + The remainder has the same sign as the divisor. + When ``divisor`` is a Tensor, the shapes of ``self`` and ``divisor`` must be broadcastable. + :param divisor: The divisor. This may be either a number or a tensor. + :return: result tensor + """ + if self.encrypted: + return NotImplemented + if not np.isscalar(divisor): + divisor = _ensure_tensorbase(divisor) + return TensorBase(np.remainder(self.data, divisor)) + + def remainder_(self, divisor): + """ + Computes the element-wise remainder of division. + The divisor and dividend may contain both for integer and floating point numbers. + The remainder has the same sign as the divisor. + When ``divisor`` is a Tensor, the shapes of ``self`` and ``divisor`` must be broadcastable. + :param divisor: The divisor. This may be either a number or a tensor. + :return: self + """ + if self.encrypted: + return NotImplemented + if not np.isscalar(divisor): + divisor = _ensure_tensorbase(divisor) + self.data = np.remainder(self.data, divisor) + return self + def index_select(self, dim, index): """ Returns a new Tensor which indexes the ``input`` Tensor along
diff --git a/tests/test_tensor.py b/tests/test_tensor.py --- a/tests/test_tensor.py +++ b/tests/test_tensor.py @@ -873,6 +873,23 @@ def testScatter_index_src_dimension_mismatch(self): t.scatter_(dim=dim, index=idx, src=src) +class remainderTests(unittest.TestCase): + def testRemainder(self): + t = TensorBase([[-2, -3], [4, 1]]) + result = t.remainder(1.5) + self.assertTrue(np.array_equal(result.data, np.array([[1, 0], [1, 1]]))) + + def testRemainder_broadcasting(self): + t = TensorBase([[-2, -3], [4, 1]]) + result = t.remainder([2, -3]) + self.assertTrue(np.array_equal(result.data, np.array([[0, 0], [0, -2]]))) + + def testRemainder_(self): + t = TensorBase([[-2, -3], [4, 1]]) + t.remainder_(2) + self.assertTrue(np.array_equal(t.data, np.array([[0, 1], [0, 1]]))) + + class testMv(unittest.TestCase): def mvTest(self): mat = TensorBase([[1, 2, 3], [2, 3, 4], [4, 5, 6]])
Implement Default remainder Functionality for Base Tensor Type **User Story A:** As a Data Scientist using Syft's Base Tensor type, I want to leverage a default method for computing operations on a Tensor of arbitrary type. For this ticket to be complete, remainder() should return a new tensor, but remainder_() should operate inline. For a reference on the operation this performs check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation. **Acceptance Criteria:** - If the Base Tensor type's attribute "encrypted" is set to True, it should return a NotImplemented error. - a unit test demonstrating the correct operation on the Base Tensor type implemented over int and float Tensors. - inline documentation in the python code. For inspiration on inline documentation, please check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation for this operator.
I take this
2017-09-18T20:25:43
OpenMined/PySyft
250
OpenMined__PySyft-250
[ "39" ]
6d94259b46fb6516ab20773cbbb9bb6ddac3d3cd
diff --git a/syft/tensor.py b/syft/tensor.py --- a/syft/tensor.py +++ b/syft/tensor.py @@ -1200,6 +1200,21 @@ def masked_scatter_(self, mask, source): out_flat = [s if m == 0 else source_iter.__next__().item() for m, s in mask_self_iter] self.data = np.reshape(out_flat, self.data.shape) + def eq(self, t): + """Returns a new Tensor having boolean True values where an element of the calling tensor is equal to the second Tensor, False otherwise. + The second Tensor can be a number or a tensor whose shape is broadcastable with the calling Tensor.""" + if self.encrypted: + return NotImplemented + return TensorBase(np.equal(self.data, _ensure_tensorbase(t).data)) + + def eq_(self, t): + """Writes in-place, boolean True values where an element of the calling tensor is equal to the second Tensor, False otherwise. + The second Tensor can be a number or a tensor whose shape is broadcastable with the calling Tensor.""" + if self.encrypted: + return NotImplemented + self.data = np.equal(self.data, _ensure_tensorbase(t).data) + return self + def mv(tensormat, tensorvector): """ matrix and vector multiplication """
diff --git a/tests/test_tensor.py b/tests/test_tensor.py --- a/tests/test_tensor.py +++ b/tests/test_tensor.py @@ -908,5 +908,29 @@ def testMasked_scatter_braodcasting2(self): self.assertTrue(np.array_equal(t, TensorBase([[1, 2, 3], [1, 1, 1]]))) +class eqTests(unittest.TestCase): + def testEqWithTensor(self): + t1 = TensorBase(np.arange(5)) + t2 = TensorBase(np.arange(5)[-1::-1]) + truth_values = t1.eq(t2) + self.assertEqual(truth_values, [False, False, True, False, False]) + + def testEqWithNumber(self): + t1 = TensorBase(np.arange(5)) + truth_values = t1.eq(1) + self.assertEqual(truth_values, [False, True, False, False, False]) + + def testEqInPlaceWithTensor(self): + t1 = TensorBase(np.arange(5)) + t2 = TensorBase(np.arange(5)[-1::-1]) + t1.eq_(t2) + self.assertEqual(t1, [False, False, True, False, False]) + + def testEqInPlaceWithNumber(self): + t1 = TensorBase(np.arange(5)) + t1.eq_(1) + self.assertEqual(t1, [False, True, False, False, False]) + + if __name__ == "__main__": unittest.main()
Implement Default eq Functionality for Base Tensor Type **User Story A:** As a Data Scientist using Syft's Base Tensor type, we want to implement a default method for computing operations on a Tensor of arbitrary type. For this ticket to be complete, eq() should return a new tensor and eq_() should perform the operation inline. For a reference on the operation this performs check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation. **Acceptance Criteria:** - If the Base Tensor type's attribute "encrypted" is set to True, it should return a NotImplemented error. - a unit test demonstrating the correct operation on the Base Tensor type implemented over int and float Tensors. - inline documentation in the python code. For inspiration on inline documentation, please check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation for this operator.
2017-09-23T09:32:13
OpenMined/PySyft
254
OpenMined__PySyft-254
[ "49", "59" ]
6c84afb0d4d541039bdcad4357cc7b62a3d24084
diff --git a/syft/tensor.py b/syft/tensor.py --- a/syft/tensor.py +++ b/syft/tensor.py @@ -725,19 +725,72 @@ def chunk(self, n, dim=0, same_size=False): else: return [TensorBase(x) for x in np.array_split(self.data, n, dim)] - def gt(self, t): + def gt(self, other): """Returns a new Tensor having boolean True values where an element of the calling tensor is greater than the second Tensor, False otherwise. The second Tensor can be a number or a tensor whose shape is broadcastable with the calling Tensor.""" - if self.encrypted: + other = _ensure_tensorbase(other) + if self.encrypted or other.encrypted: return NotImplemented - return TensorBase(np.greater(self.data, _ensure_tensorbase(t).data)) + return TensorBase(np.greater(self.data, other.data)) - def gt_(self, t): + def gt_(self, other): """Writes in-place, boolean True values where an element of the calling tensor is greater than the second Tensor, False otherwise. The second Tensor can be a number or a tensor whose shape is broadcastable with the calling Tensor.""" - if self.encrypted: + other = _ensure_tensorbase(other) + if self.encrypted or other.encrypted: + return NotImplemented + self.data = np.greater(self.data, other.data) + return self + + def lt(self, other): + """Returns a new Tensor having boolean True values where an element of the calling tensor is less than the second Tensor, False otherwise. + The second Tensor can be a number or a tensor whose shape is broadcastable with the calling Tensor.""" + other = _ensure_tensorbase(other) + if self.encrypted or other.encrypted: + return NotImplemented + return TensorBase(np.less(self.data, other.data)) + + def lt_(self, other): + """Writes in-place, boolean True values where an element of the calling tensor is less than the second Tensor, False otherwise. + The second Tensor can be a number or a tensor whose shape is broadcastable with the calling Tensor.""" + other = _ensure_tensorbase(other) + if self.encrypted or other.encrypted: + return NotImplemented + self.data = np.less(self.data, other.data) + return self + + def ge(self, other): + """Returns a new Tensor having boolean True values where an element of the calling tensor is greater or equal than the second Tensor, False otherwise. + The second Tensor can be a number or a tensor whose shape is broadcastable with the calling Tensor.""" + other = _ensure_tensorbase(other) + if self.encrypted or other.encrypted: + return NotImplemented + return TensorBase(np.greater_equal(self.data, other.data)) + + def ge_(self, other): + """Writes in-place, boolean True values where an element of the calling tensor is greater or equal than the second Tensor, False otherwise. + The second Tensor can be a number or a tensor whose shape is broadcastable with the calling Tensor.""" + other = _ensure_tensorbase(other) + if self.encrypted or other.encrypted: + return NotImplemented + self.data = np.greater_equal(self.data, other.data) + return self + + def le(self, other): + """Returns a new Tensor having boolean True values where an element of the calling tensor is less or equal than the second Tensor, False otherwise. + The second Tensor can be a number or a tensor whose shape is broadcastable with the calling Tensor.""" + other = _ensure_tensorbase(other) + if self.encrypted or other.encrypted: + return NotImplemented + return TensorBase(np.less_equal(self.data, other.data)) + + def le_(self, other): + """Writes in-place, boolean True values where an element of the calling tensor is less or equal than the second Tensor, False otherwise. + The second Tensor can be a number or a tensor whose shape is broadcastable with the calling Tensor.""" + other = _ensure_tensorbase(other) + if self.encrypted or other.encrypted: return NotImplemented - self.data = np.greater(self.data, _ensure_tensorbase(t).data) + self.data = np.less_equal(self.data, other.data) return self def bernoulli(self, p):
diff --git a/tests/test_tensor.py b/tests/test_tensor.py --- a/tests/test_tensor.py +++ b/tests/test_tensor.py @@ -560,28 +560,107 @@ def testChunkSameSize(self): self.assertEqual(t2.shape(), t3.shape()) -class gtTests(unittest.TestCase): +class inequalityTest(unittest.TestCase): + def setUp(self): + self.a1 = np.array([-2, -1, 0, 1, 2]) + self.a2 = np.array([-4, -1, 5, 2, 2]) + + self.t1 = TensorBase(self.a1) + self.t2 = TensorBase(self.a2) + + self.enc = TensorBase(self.a1, encrypted=True) + + +class gtTests(inequalityTest): def testGtWithTensor(self): - t1 = TensorBase(np.arange(10)) - t2 = TensorBase(np.arange(10)[-1::-1]) - truth_values = t1.gt(t2) - self.assertEqual(truth_values, [False, False, False, False, False, True, True, True, True, True]) + self.assertEqual(self.t1.gt(self.t2), self.a1 > self.a2) def testGtWithNumber(self): - t1 = TensorBase(np.arange(10)) - truth_values = t1.gt(-1) - self.assertEqual(truth_values, [True] * 10) + self.assertEqual(self.t1.gt(1), self.a1 > 1) def testGtInPlaceWithTensor(self): - t1 = TensorBase(np.arange(10)) - t2 = TensorBase(np.arange(10)[-1::-1]) - t1.gt_(t2) - self.assertEqual(t1, [False, False, False, False, False, True, True, True, True, True]) + self.t1.gt_(self.t2) + self.assertEqual(self.t1, self.a1 > self.a2) def testGtInPlaceWithNumber(self): - t1 = TensorBase(np.arange(10)) - t1.gt_(-1) - self.assertEqual(t1, [True] * 10) + self.t1.gt_(1) + self.assertEqual(self.t1, self.a1 > 1) + + def testWithEncrypted(self): + res = self.t1.gt(self.enc) + self.assertEqual(res, NotImplemented) + + res = self.enc.gt(self.t1) + self.assertEqual(res, NotImplemented) + + +class geTests(inequalityTest): + def testGeWithTensor(self): + self.assertEqual(self.t1.ge(self.t2), self.a1 >= self.a2) + + def testGeWithNumber(self): + self.assertEqual(self.t1.ge(1), self.a1 >= 1) + + def testGeInPlaceWithTensor(self): + self.t1.ge_(self.t2) + self.assertEqual(self.t1, self.a1 >= self.a2) + + def testGeInPlaceWithNumber(self): + self.t1.ge_(1) + self.assertEqual(self.t1, self.a1 >= 1) + + def testWithEncrypted(self): + res = self.t1.ge(self.enc) + self.assertEqual(res, NotImplemented) + + res = self.enc.ge(self.t1) + self.assertEqual(res, NotImplemented) + + +class ltTests(inequalityTest): + def testLtWithTensor(self): + self.assertEqual(self.t1.lt(self.t2), self.a1 < self.a2) + + def testLtWithNumber(self): + self.assertEqual(self.t1.lt(1), self.a1 < 1) + + def testLtInPlaceWithTensor(self): + self.t1.lt_(self.t2) + self.assertEqual(self.t1, self.a1 < self.a2) + + def testLtInPlaceWithNumber(self): + self.t1.lt_(1) + self.assertEqual(self.t1, self.a1 < 1) + + def testWithEncrypted(self): + res = self.t1.lt(self.enc) + self.assertEqual(res, NotImplemented) + + res = self.enc.lt(self.t1) + self.assertEqual(res, NotImplemented) + + +class leTests(inequalityTest): + def testLeWithTensor(self): + self.assertEqual(self.t1.le(self.t2), self.a1 <= self.a2) + + def testLeWithNumber(self): + self.assertEqual(self.t1.le(1), self.a1 <= 1) + + def testLeInPlaceWithTensor(self): + self.t1.le_(self.t2) + self.assertEqual(self.t1, self.a1 <= self.a2) + + def testLeInPlaceWithNumber(self): + self.t1.le_(1) + self.assertEqual(self.t1, self.a1 <= 1) + + def testWithEncrypted(self): + res = self.t1.le(self.enc) + self.assertEqual(res, NotImplemented) + + res = self.enc.le(self.t1) + self.assertEqual(res, NotImplemented) class bernoulliTests(unittest.TestCase):
Implement Default ge Functionality for Base Tensor Type **User Story A:** As a Data Scientist using Syft's Base Tensor type, we want to implement a default method for computing operations on a Tensor of arbitrary type. For this ticket to be complete, ge() should return a new tensor and ge_() should perform the operation inline. For a reference on the operation this performs check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation. **Acceptance Criteria:** - If the Base Tensor type's attribute "encrypted" is set to True, it should return a NotImplemented error. - a unit test demonstrating the correct operation on the Base Tensor type implemented over int and float Tensors. - inline documentation in the python code. For inspiration on inline documentation, please check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation for this operator. Implement Default lt Functionality for Base Tensor Type **User Story A:** As a Data Scientist using Syft's Base Tensor type, we want to implement a default method for computing operations on a Tensor of arbitrary type. For this ticket to be complete, lt() should return a new tensor and lt_() should perform the operation inline. For a reference on the operation this performs check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation. **Acceptance Criteria:** - If the Base Tensor type's attribute "encrypted" is set to True, it should return a NotImplemented error. - a unit test demonstrating the correct operation on the Base Tensor type implemented over int and float Tensors. - inline documentation in the python code. For inspiration on inline documentation, please check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation for this operator.
2017-09-26T21:01:03
OpenMined/PySyft
257
OpenMined__PySyft-257
[ "66" ]
b0d646922b7529f5198dcc21fc856c7e9e598976
diff --git a/syft/__init__.py b/syft/__init__.py --- a/syft/__init__.py +++ b/syft/__init__.py @@ -6,7 +6,7 @@ from syft.tensor import equal, TensorBase from syft.math import cumprod, cumsum, ceil, dot, matmul, addmm, addcmul from syft.math import addcdiv, addmv, addbmm, baddbmm, transpose -from syft.math import unsqueeze, zeros, ones, rand, randn +from syft.math import unsqueeze, zeros, ones, rand, randn, mm s = str(he) s += str(nn) @@ -17,3 +17,4 @@ s += str(addmv) + str(addbmm) + str(baddbmm) s += str(transpose) + str(rand) + str(randn) + str(ones) + str(zeros) s += str(unsqueeze) +s += str(mm) diff --git a/syft/math.py b/syft/math.py --- a/syft/math.py +++ b/syft/math.py @@ -9,7 +9,7 @@ __all__ = [ 'cumprod', 'cumsum', 'ceil', 'dot', 'floor', 'matmul', 'addmm', 'addcmul', 'addcdiv', 'addmv', 'addbmm', 'baddbmm', 'sigmoid', 'unsqueeze', 'tanh', 'relu', - 'zeros', 'ones', 'rand', 'randn' + 'zeros', 'ones', 'rand', 'randn', 'mm' ] @@ -341,3 +341,23 @@ def unsqueeze(tensor1, dim): raise NotImplemented else: return TensorBase(np.expand_dims(tensor1.data, dim)) + + +def mm(tensor1, tensor2): + """ + Performs a matrix multiplication of :attr:`tensor1` and :attr:`tensor2`. + + If :attr:`tensor1` is a `n x m` Tensor, :attr:`tensor2` is a `m x p` Tensor, + output will be a `n x p` Tensor. + + Args: + tensor1 (Tensor): First Tensor to be multiplied + tensor2 (Tensor): Second Tensor to be multiplied""" + + _ensure_tensorbase(tensor1) + _ensure_tensorbase(tensor2) + + if tensor1.encrypted or tensor2.encrypted: + return NotImplemented + else: + return TensorBase(np.array(np.matmul(tensor1.data, tensor2.data))) diff --git a/syft/tensor.py b/syft/tensor.py --- a/syft/tensor.py +++ b/syft/tensor.py @@ -1067,11 +1067,13 @@ def ne(self, tensor): else: if tensor.shape() == self.shape(): - tensor2 = np.array([1 if x else 0 for x in np.equal(tensor.data.flatten(), self.data.flatten()).tolist()]) + tensor2 = np.array([1 if x else 0 for x in np.equal( + tensor.data.flatten(), self.data.flatten()).tolist()]) result = tensor2.reshape(self.data.shape) return TensorBase(result) else: - raise ValueError('inconsistent dimensions {} and {}'.format(self.shape(), tensor.shape())) + raise ValueError('inconsistent dimensions {} and {}'.format( + self.shape(), tensor.shape())) def ne_(self, tensor): """ @@ -1118,7 +1120,8 @@ def histc(self, bins=10, min=0, max=0): """Computes the histogram of a tensor and Returns it""" if self.encrypted: return NotImplemented - hist, edges = np.histogram(np.array(self.data), bins=bins, range=(min, max)) + hist, edges = np.histogram( + np.array(self.data), bins=bins, range=(min, max)) return TensorBase(hist) def scatter_(self, dim, index, src): @@ -1136,19 +1139,22 @@ def scatter_(self, dim, index, src): if index.data.dtype != np.dtype('int_'): raise TypeError("The values of index must be integers") if self.data.ndim != index.data.ndim: - raise ValueError("Index should have the same number of dimensions as output") + raise ValueError( + "Index should have the same number of dimensions as output") if dim >= self.data.ndim or dim < -self.data.ndim: raise IndexError("dim is out of range") if dim < 0: # Not sure why scatter should accept dim < 0, but that is the behavior in PyTorch's scatter dim = self.data.ndim + dim - idx_xsection_shape = index.data.shape[:dim] + index.data.shape[dim + 1:] + idx_xsection_shape = index.data.shape[:dim] + \ + index.data.shape[dim + 1:] self_xsection_shape = self.data.shape[:dim] + self.data.shape[dim + 1:] if idx_xsection_shape != self_xsection_shape: raise ValueError("Except for dimension " + str(dim) + ", all dimensions of index and output should be the same size") if (index.data >= self.data.shape[dim]).any() or (index.data < 0).any(): - raise IndexError("The values of index must be between 0 and (self.data.shape[dim] -1)") + raise IndexError( + "The values of index must be between 0 and (self.data.shape[dim] -1)") def make_slice(arr, dim, i): slc = [slice(None)] * arr.ndim @@ -1165,7 +1171,8 @@ def make_slice(arr, dim, i): if not np.isscalar(src): src = _ensure_tensorbase(src) if index.data.shape[dim] > src.data.shape[dim]: - raise IndexError("Dimension " + str(dim) + "of index can not be bigger than that of src ") + raise IndexError("Dimension " + str(dim) + + "of index can not be bigger than that of src ") src_shape = src.data.shape[:dim] + src.data.shape[dim + 1:] if idx_xsection_shape != src_shape: raise ValueError("Except for dimension " + @@ -1173,7 +1180,8 @@ def make_slice(arr, dim, i): # src_idx is a NumPy advanced index for indexing of elements in the src src_idx = list(idx) src_idx.pop(dim) - src_idx.insert(dim, np.repeat(np.arange(index.data.shape[dim]), np.prod(idx_xsection_shape))) + src_idx.insert(dim, np.repeat( + np.arange(index.data.shape[dim]), np.prod(idx_xsection_shape))) self.data[idx] = src.data[src_idx] else: @@ -1195,7 +1203,8 @@ def gather(self, dim, index): index = _ensure_tensorbase(index) if self.encrypted or index.encrypted: return NotImplemented - idx_xsection_shape = index.data.shape[:dim] + index.data.shape[dim + 1:] + idx_xsection_shape = index.data.shape[:dim] + \ + index.data.shape[dim + 1:] self_xsection_shape = self.data.shape[:dim] + self.data.shape[dim + 1:] if idx_xsection_shape != self_xsection_shape: raise ValueError("Except for dimension " + str(dim) + @@ -1281,7 +1290,8 @@ def masked_scatter_(self, mask, source): return NotImplemented mask_self_iter = np.nditer([mask.data, self.data]) source_iter = np.nditer(source.data) - out_flat = [s if m == 0 else source_iter.__next__().item() for m, s in mask_self_iter] + out_flat = [s if m == 0 else source_iter.__next__().item() + for m, s in mask_self_iter] self.data = np.reshape(out_flat, self.data.shape) return self @@ -1325,13 +1335,26 @@ def eq_(self, t): self.data = np.equal(self.data, _ensure_tensorbase(t).data) return self + def mm(self, tensor2): + """Performs a matrix multiplication of :attr:`tensor1` and :attr:`tensor2`. + + If :attr:`tensor1` is a `n x m` Tensor, :attr:`tensor2` is a `m x p` Tensor, + output will be a `n x p` Tensor. + + Args: + tensor1 (Tensor): First Tensor to be multiplied + tensor2 (Tensor): Second Tensor to be multiplied""" + + return syft.mm(self, tensor2) + def mv(tensormat, tensorvector): """ matrix and vector multiplication """ if tensormat.encrypted or tensorvector.encrypted: raise NotImplemented elif not len(tensorvector.data.shape) == 1: - raise ValueError('Vector dimensions not correct {}'.format(tensorvector.data.shape)) + raise ValueError('Vector dimensions not correct {}'.format( + tensorvector.data.shape)) elif tensorvector.data.shape[0] != tensormat.data.shape[1]: raise ValueError('vector dimensions {} not \ compatible with matrix {} '.format(tensorvector.data.shape, tensormat.data.shape)) @@ -1352,6 +1375,7 @@ def masked_select(tensor, mask): tensor = _ensure_tensorbase(tensor) if tensor.encrypted or mask.encrypted: raise NotImplemented - mask_broadcasted, data_broadcasted = np.broadcast_arrays(mask.data, tensor.data) + mask_broadcasted, data_broadcasted = np.broadcast_arrays( + mask.data, tensor.data) indices = np.where(mask_broadcasted) return TensorBase(data_broadcasted[indices])
diff --git a/tests/test_math.py b/tests/test_math.py --- a/tests/test_math.py +++ b/tests/test_math.py @@ -207,3 +207,23 @@ def testUnsqueeze(self): expected_shape.insert(i, 1) self.assertTrue(np.array_equal(out.data.shape, expected_shape)) + + +class mmtest(unittest.TestCase): + def testmm1d(self): + t1 = TensorBase(np.array([2, 3, 4])) + t2 = TensorBase(np.array([3, 4, 5])) + out = syft.mm(t1, t2) + self.assertTrue(np.alltrue(out.data == [38])) + + def testmm2d(self): + t1 = TensorBase(np.array([[1, 2], [1, 2]])) + t2 = TensorBase(np.array([[2, 3], [2, 3]])) + out = syft.mm(t1, t2) + self.assertTrue(np.alltrue(out.data == [[6, 9], [6, 9]])) + + def testmm3d(self): + t1 = TensorBase(np.array([[1, 2], [2, 3], [3, 4]])) + t2 = TensorBase(np.array([[1, 2, 3], [2, 3, 4]])) + out = syft.mm(t1, t2) + self.assertTrue(np.alltrue(out.data == [[5, 8, 11], [8, 13, 18], [11, 18, 25]])) diff --git a/tests/test_tensor.py b/tests/test_tensor.py --- a/tests/test_tensor.py +++ b/tests/test_tensor.py @@ -1066,5 +1066,25 @@ def testEqInPlaceWithNumber(self): self.assertEqual(t1, [False, True, False, False, False]) +class mm_test(unittest.TestCase): + def testmm1d(self): + t1 = TensorBase(np.array([2, 3, 4])) + t2 = TensorBase(np.array([3, 4, 5])) + out = t1.mm(t2) + self.assertTrue(np.alltrue(out.data == [38])) + + def testmm2d(self): + t1 = TensorBase(np.array([[1, 2], [1, 2]])) + t2 = TensorBase(np.array([[2, 3], [2, 3]])) + out = t1.mm(t2) + self.assertTrue(np.alltrue(out.data == [[6, 9], [6, 9]])) + + def testmm3d(self): + t1 = TensorBase(np.array([[1, 2], [2, 3], [3, 4]])) + t2 = TensorBase(np.array([[1, 2, 3], [2, 3, 4]])) + out = t1.mm(t2) + self.assertTrue(np.alltrue(out.data == [[5, 8, 11], [8, 13, 18], [11, 18, 25]])) + + if __name__ == "__main__": unittest.main()
Implement Default mm Functionality for Base Tensor Type **User Story A:** As a Data Scientist using Syft's Base Tensor type, we want to implement a default method for computing operations on a Tensor of arbitrary type. For this ticket to be complete, mm() should return a new tensor. For a reference on the operation this performs check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation. **Acceptance Criteria:** - If the Base Tensor type's attribute "encrypted" is set to True, it should return a NotImplemented error. - a unit test demonstrating the correct operation on the Base Tensor type implemented over int and float Tensors. - inline documentation in the python code. For inspiration on inline documentation, please check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation for this operator.
2017-09-28T06:36:51
OpenMined/PySyft
285
OpenMined__PySyft-285
[ "50" ]
28ee3b4ade61bbbf0cce1c745a0b9fac310841e9
diff --git a/syft/tensor.py b/syft/tensor.py --- a/syft/tensor.py +++ b/syft/tensor.py @@ -862,6 +862,25 @@ def uniform(self, low=0, high=1): out = np.random.uniform(low=low, high=high, size=self.shape()) return TensorBase(out) + def geometric_(self, p): + """Fills the given tensor in-place with samples from a geometric distribution + with given probability of success of an individual trial. + + Parameters + ---------- + p: float + Probability of success of an individual trial + + Returns + ------- + TensorBase + Caller with values in-place + """ + if self.encrypted: + return NotImplemented + self.data = np.random.geometric(p, size=self.shape()) + return self + def cauchy_(self, median=0, sigma=1): """Fills the tensor in-place with numbers drawn from the Cauchy distribution:
diff --git a/tests/test_tensor.py b/tests/test_tensor.py --- a/tests/test_tensor.py +++ b/tests/test_tensor.py @@ -716,6 +716,14 @@ def test_uniform_(self): self.assertTrue(np.all(t1.data > 0) and np.all(t1.data < 3)) +class geometricTests(unittest.TestCase): + def test_geometric_(self): + t1 = TensorBase(np.zeros((4, 4))) + out = t1.geometric_(p=0.5) + self.assertTupleEqual(t1.data.shape, out.data.shape) + self.assertTrue(np.all(out.data > 0)) + + class fillTests(unittest.TestCase): def test_fill_(self): t1 = TensorBase(np.array([1, 2, 3, 4]))
Implement Default geometric Functionality for Base Tensor Type **User Story A:** As a Data Scientist using Syft's Base Tensor type, we want to implement a default method for computing operations on a Tensor of arbitrary type. For this ticket to be complete, geometric_() should perform the operation inline. For a reference on the operation this performs check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation. **Acceptance Criteria:** - If the Base Tensor type's attribute "encrypted" is set to True, it should return a NotImplemented error. - a unit test demonstrating the correct operation on the Base Tensor type implemented over int and float Tensors. - inline documentation in the python code. For inspiration on inline documentation, please check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation for this operator.
I'd like to take this up.
2017-10-03T13:06:22
OpenMined/PySyft
286
OpenMined__PySyft-286
[ "75" ]
40261aab99e6857e0ed2e34c26a315f16d9500f7
diff --git a/syft/tensor.py b/syft/tensor.py --- a/syft/tensor.py +++ b/syft/tensor.py @@ -109,6 +109,30 @@ def __init__(self, arr_like, encrypted=False): self.data = _ensure_ndarray(arr_like) self.encrypted = encrypted + def new(self, *args, **kwargs): + """Constructs a new tensor instance of the same data type. + + Parameters + ---------- + *args + Variable length argument list used to instantiate + new TensorBase object. + **kwargs + Arbitrary keyword arguments used to instantiate + new TensorBase object. + + Returns + ------- + TensorBase class instance if parent TensorBase + has self.encrypted = False, otherwise return NotImplemented + error. + + """ + if self.encrypted: + return NotImplemented + + return self.__class__(*args, **kwargs) + def _calc_mul_depth(self, tensor1, tensor2): if isinstance(tensor1, TensorBase) and isinstance(tensor2, TensorBase): self._mul_depth = max(tensor1._mul_depth, tensor2._mul_depth) + 1
diff --git a/tests/test_tensor.py b/tests/test_tensor.py --- a/tests/test_tensor.py +++ b/tests/test_tensor.py @@ -1119,6 +1119,29 @@ def test_mm_3d(self): self.assertTrue(np.alltrue(out.data == [[5, 8, 11], [8, 13, 18], [11, 18, 25]])) +class newTensorTests(unittest.TestCase): + def test_encrypted_error(self): + + t1 = TensorBase(np.array([1, 1, 1]), encrypted=True) + t2 = t1.new([1, 1, 2], encrypted=True) + + self.assertEqual(t2, NotImplemented) + + def test_return_new_float_tensor(self): + + t1 = TensorBase(np.array([1, 1, 1])) + t2 = t1.new(np.array([1., 1., 2.])) + + self.assertTrue(t2.data.dtype == np.float64) + + def test_return_new_int_tensor(self): + + t1 = TensorBase(np.array([1, 1, 1])) + t2 = t1.new(np.array([1, 1, 2])) + + self.assertTrue(t2.data.dtype == np.int64) + + class half(unittest.TestCase): def half_test_1(self): t1 = TensorBase(np.array([2, 3, 4]))
Implement Default new Functionality for Base Tensor Type **User Story A:** As a Data Scientist using Syft's Base Tensor type, I want to leverage a default method for computing operations on a Tensor of arbitrary type. For this ticket to be complete, new() should return a new tensor. For a reference on the operation this performs check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation. **Acceptance Criteria:** - If the Base Tensor type's attribute "encrypted" is set to True, it should return a NotImplemented error. - a unit test demonstrating the correct operation on the Base Tensor type implemented over int and float Tensors. - inline documentation in the python code. For inspiration on inline documentation, please check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation for this operator.
Hey, I want to help. How do I get started? I'll pick this one up!
2017-10-03T19:11:06
OpenMined/PySyft
296
OpenMined__PySyft-296
[ "54" ]
65b9352e9e349c7f932f52904d6f913a09f9a025
diff --git a/syft/tensor.py b/syft/tensor.py --- a/syft/tensor.py +++ b/syft/tensor.py @@ -2848,6 +2848,97 @@ def remainder_(self, divisor): self.data = np.remainder(self.data, divisor) return self + def index(self, m): + """ + Returns a new Tensor with the element selected by position + + :param m: integer index or slice + :return: tensor of selected indices + """ + if self.encrypted: + return NotImplemented + if not isinstance(m, int) and not isinstance(m, slice): + raise ValueError("The value of index must be integer") + return TensorBase(self.data[m], self.encrypted) + + def index_add_(self, dim, index, tensor): + """ + Add the value of 'tensor' selecting the elements and ordered + by index. In-place operation. + + :param dim: dimension along which to index + :param index: 1D tensor containing the indices to select + :param tensor: tensor containing the values to add + """ + index = _ensure_tensorbase(index) + tensor = _ensure_tensorbase(tensor) + + if self.encrypted: + return NotImplemented + if index.data.dtype != np.dtype('int_'): + raise TypeError("The value of index must be integer") + if self.data.shape != tensor.data.shape: + raise IndexError("Tensor has different shape") + if self.data.shape[dim] != index.data.size: + raise ValueError("Index should have the same number of elements as dimension") + if np.argmax(index.data > self.data.shape[dim]) != 0: + raise ValueError("Index contains a value which is out of range") + if dim >= self.data.ndim or dim < -self.data.ndim: + raise IndexError("Dimension out of range") + + self.data += tensor.data.take(index, dim) + + def index_copy_(self, dim, index, tensor): + """ + Copy the values of 'tensor' selecting the elements and ordered + by index. In-place operation. + + :para dim: dimension along which to index + :param index: 1D tensor containing the indices to select + :param tensor: tensor containing the values to add + """ + index = _ensure_tensorbase(index) + tensor = _ensure_tensorbase(tensor) + + if self.encrypted: + return NotImplemented + if index.data.dtype != np.dtype('int_'): + raise TypeError("The value of index must be integer") + if self.data.shape != tensor.data.shape: + raise IndexError("Tensor has different shape") + if self.data.shape[dim] != index.data.size: + raise ValueError("Index should have the same number of elements as dimension") + if np.argmax(index.data > self.data.shape[dim]) != 0: + raise ValueError("Index contains a value which is out of range") + if dim >= self.data.ndim or dim < -self.data.ndim: + raise IndexError("Dimension out of range") + + np.copyto(self.data, tensor.data.take(index, dim)) + + def index_fill_(self, dim, index, value): + """ + Fill the original tensor with the values of 'tensor' selecting + the elements and ordered by index. In-place operation. + + :param dim: dimension along which to inde + :param index: 1D tensor containing the indices to select + :param value: value to fill + """ + index = _ensure_tensorbase(index) + + if self.encrypted: + return NotImplemented + if index.data.dtype != np.dtype('int_'): + raise TypeError("The value of index must be integer") + if np.argmax(index.data > self.data.shape[dim]) != 0: + raise ValueError("Index contains a value which is out of range") + if dim >= self.data.ndim or dim < -self.data.ndim: + raise IndexError("Dimension out of range") + + idx = [slice(None)] * self.data.ndim + idx[dim] = index + self.data[tuple(idx)] = value + def index_select(self, dim, index): """ Returns a new Tensor which indexes the ``input`` Tensor along
diff --git a/tests/test_tensor.py b/tests/test_tensor.py --- a/tests/test_tensor.py +++ b/tests/test_tensor.py @@ -4,6 +4,7 @@ from syft import tensor import numpy as np import math +import pytest # Here's our "unit tests". @@ -250,13 +251,6 @@ def test_inequality_operation(self): self.assertTrue(t1 != t2) -class IndexTests(unittest.TestCase): - def test_indexing(self): - t1 = TensorBase(np.array([1.2, 2, 3])) - self.assertEqual(1.2, t1[0]) - self.assertEqual(3, t1[-1]) - - class sigmoidTests(unittest.TestCase): def test_sigmoid(self): t1 = TensorBase(np.array([1.2, 3.3, 4])) @@ -954,7 +948,90 @@ def test_ne_(self): self.assertTrue(syft.equal(t1, TensorBase([1, 1, 1, 0]))) -class index_selectTests(unittest.TestCase): +class IndexTests(unittest.TestCase): + def test_indexing(self): + t1 = TensorBase(np.array([1.2, 2, 3])) + self.assertEqual(1.2, t1[0]) + self.assertEqual(3, t1[-1]) + + def test_index(self): + t = TensorBase(np.array([1, 2, 3.5, 4, 5, 6, 3.5])) + expected1 = TensorBase(np.array(2)) + expected2 = TensorBase(np.array(3.5)) + expected3 = TensorBase(np.array([4, 5, 6])) + + self.assertEqual(expected1, t.index(1)) + self.assertEqual(expected2, t.index(2)) + self.assertEqual(expected2, t.index(-1)) + self.assertEqual(expected3, t.index(slice(3, 6))) + with pytest.raises(ValueError): + t.index(3.5) + + def test_index_add_(self): + t1 = TensorBase(np.array([[0, 0, 0], [1, 1, 1], [1, 1, 1]])) + t2 = TensorBase(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])) + + expected_0 = TensorBase(np.array([[1, 2, 3], [8, 9, 10], [5, 6, 7]])) + t1.index_add_(0, [0, 2, 1], t2) + self.assertEqual(expected_0, t1) + + t1 = TensorBase(np.array([[0, 0, 0], [1, 1, 1], [1, 1, 1]])) + expected_1 = TensorBase(np.array([[1, 3, 2], [5, 7, 6], [8, 10, 9]])) + t1.index_add_(1, [0, 2, 1], t2) + self.assertEqual(expected_1, t1) + + with pytest.raises(TypeError): + t1.index_add_(0, [1.0, 2, 2], t2) + with pytest.raises(IndexError): + t1.index_add_(0, [0, 1, 2], TensorBase([1, 2])) + with pytest.raises(ValueError): + t1.index_add_(0, [0, 1], t2) + with pytest.raises(ValueError): + t1.index_add_(0, [0, 1, 5], t2) + with pytest.raises(IndexError): + t1.index_add_(4, [0, 1, 2], t2) + + def test_index_copy_(self): + t1 = TensorBase(np.array([[0, 0, 0], [1, 1, 1], [1, 1, 1]])) + t2 = TensorBase(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])) + expected_0 = TensorBase(np.array([[1, 2, 3], [7, 8, 9], [4, 5, 6]])) + t1.index_copy_(0, [0, 2, 1], t2) + self.assertEqual(expected_0, t1) + + t1 = TensorBase(np.array([[0, 0, 0], [1, 1, 1], [1, 1, 1]])) + expected_1 = TensorBase(np.array([[3, 1, 2], [6, 4, 5], [9, 7, 8]])) + t1.index_copy_(1, [2, 0, 1], t2) + self.assertEqual(expected_1, t1) + + with pytest.raises(TypeError): + t1.index_copy_(0, [1.0, 2, 2], t2) + with pytest.raises(IndexError): + t1.index_copy_(0, [0, 1, 2], TensorBase([1, 2])) + with pytest.raises(ValueError): + t1.index_copy_(0, [0, 1], t2) + with pytest.raises(ValueError): + t1.index_copy_(0, [0, 1, 5], t2) + with pytest.raises(IndexError): + t1.index_copy_(4, [0, 1, 2], t2) + + def test_index_fill_(self): + t1 = TensorBase(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])) + expected_0 = TensorBase(np.array([[1, 1, 1], [1, 1, 1], [7, 8, 9]])) + t1.index_fill_(0, [0, 1], 1) + self.assertEqual(expected_0, t1) + + t1 = TensorBase(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])) + expected_1 = TensorBase(np.array([[-2, 2, -2], [-2, 5, -2], [-2, 8, -2]])) + t1.index_fill_(1, [0, 2], -2) + self.assertEqual(expected_1, t1) + + with pytest.raises(TypeError): + t1.index_fill_(0, [1.0, 2, 2], 1) + with pytest.raises(ValueError): + t1.index_fill_(0, [0, 1, 5], 1) + with pytest.raises(IndexError): + t1.index_fill_(4, [0, 1, 2], 1) + def test_index_select(self): t = TensorBase(np.reshape(np.arange(0, 2 * 3 * 4), (2, 3, 4))) idx = np.array([1, 0])
Implement Default index Functionality for Base Tensor Type **User Story A:** As a Data Scientist using Syft's Base Tensor type, we want to implement a default method for computing operations on a Tensor of arbitrary type. For this ticket to be complete, index() and index_select() should return a new tensor and index_add_(), index_copy_(), and index_fill_() should perform the operation inline. For a reference on the operation this performs check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation. **Acceptance Criteria:** - If the Base Tensor type's attribute "encrypted" is set to True, it should return a NotImplemented error. - a unit test demonstrating the correct operation on the Base Tensor type implemented over int and float Tensors. - inline documentation in the python code. For inspiration on inline documentation, please check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation for this operator.
Hi, I'd like to dig into this issue. It seems like `index_select()` is already implemented in tensor.py?
2017-10-06T15:20:15
OpenMined/PySyft
314
OpenMined__PySyft-314
[ "311" ]
543a66153c17d6e2885d6b7d571749fe02629ba5
diff --git a/syft/tensor.py b/syft/tensor.py --- a/syft/tensor.py +++ b/syft/tensor.py @@ -449,7 +449,7 @@ def __getitem__(self, position): return NotImplemented else: out = self.data[position] - if (len(self.shape()) == 1): + if (len(self.shape()) == 1) and (type(position) != slice): return out else: return TensorBase(self.data[position], self.encrypted)
diff --git a/tests/test_tensor.py b/tests/test_tensor.py --- a/tests/test_tensor.py +++ b/tests/test_tensor.py @@ -957,6 +957,17 @@ def test_index(self): with pytest.raises(ValueError): t.index(3.5) + def test_index_slice_notation(self): + t1 = TensorBase(np.array([1, 2, 3, 4])) + expected1 = TensorBase(np.array([2, 3, 4])) + expected2 = type(t1[1:]) + expected3 = 1 + + # Do not use "t.index" form in following test + self.assertEqual(expected1, t1[1:]) + self.assertEqual(expected2, TensorBase) + self.assertEqual(expected3, t1[0]) + def test_index_add_(self): t1 = TensorBase(np.array([[0, 0, 0], [1, 1, 1], [1, 1, 1]])) t2 = TensorBase(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
1dim TensorBase slice returns ndarray instead of TensorBase Currently a slice of TensorBase returns an ndarray if `dim() == 1`. This is not the behavior expected in PyTorch Example pytorch session: ```python t1 = Tensor([1,2,3,4]) t1[1:] 2 3 4 [torch.FloatTensor of size 3] ``` Same with TensorBase ```python t2 = TensorBase([1,2,3,4]) t2[1:] array([2, 3, 4]) ``` see https://github.com/OpenMined/PySyft/commit/7fb592dcd4ede5b0d0cc6bdc50b98a0445ad77c0#diff-796d7f13fb1460eef9cffdccebd38faeR148 Is this a bug or expected ?
2017-10-10T10:13:12
OpenMined/PySyft
391
OpenMined__PySyft-391
[ "383" ]
f1f230c45e29abce37f83a2ed4606c8a6512d3fa
diff --git a/syft/math.py b/syft/math.py --- a/syft/math.py +++ b/syft/math.py @@ -968,3 +968,43 @@ def zeros(dim): Output Tensor """ return TensorBase(np.zeros(dim)) + + +def split(tensor, split_size, axis=0): + """ + Splits the tensor into multiple equally sized chunks (if possible). + + Last chunk will be smaller if the tensor size along a given axis + is not divisible by `split_size`. + + Returns a list of the split tensors + + Parameters + ---------- + tensor: TensorBase + array to be divided into sub-arrays. + + split_size: int + size of single chunk + + axis: int, optional + The axis along which to split, default is 0. + + Returns + ------- + list: list of divided arrays + """ + if axis < 0: + axis += len(tensor.shape()) + + length_along_axis = tensor.shape()[axis] + + # calculate number of splits! + num_splits = (length_along_axis + split_size - 1) // split_size + + # make array to pass to numpy array_split function + split_according = [split_size * i for i in range(1, num_splits)] + + list_ = np.array_split(tensor.data, split_according, axis) + + return list(map(lambda x: TensorBase(x), list_)) diff --git a/syft/tensor.py b/syft/tensor.py --- a/syft/tensor.py +++ b/syft/tensor.py @@ -3038,29 +3038,6 @@ def size(self): else: return self.data.shape - def split(self, split_size, dim=0): - """ - Returns tuple of tensors of equally sized tensor/chunks (if possible) - - Parameters - ---------- - split_size: - - dim: - - Returns - ------- - Tuple of Tensors - """ - if self.encrypted: - return NotImplemented - splits = np.array_split(self.data, split_size, axis=0) - tensors = list() - for s in splits: - tensors.append(TensorBase(s)) - tensors_tuple = tuple(tensors) - return tensors_tuple - def stride(self, dim=None): """ Returns the jump necessary to go from one element to the next one in the specified dimension dim. @@ -3601,3 +3578,30 @@ def zero_(self): self.data.fill(0) return self + + def split(self, split_size, axis=0): + """ + Splits the tensor into multiple equally sized chunks (if possible). + + Last chunk will be smaller if the tensor size along a given axis + is not divisible by `split_size`. + + Returns a list of the split tensors + + Parameters + ---------- + + split_size: int + size of single chunk + + axis: int, optional + The axis along which to split, default is 0. + + Returns + ------- + list: list of divided arrays + """ + if self.encrypted: + return NotImplemented + + return syft.math.split(self, split_size, axis)
diff --git a/tests/test_math.py b/tests/test_math.py --- a/tests/test_math.py +++ b/tests/test_math.py @@ -427,3 +427,17 @@ def test_multinomial(self): t2 = syft.math.multinomial(t1, len(t1)) self.assertTupleEqual((len(t1),), t2.shape()) self.assertTrue(np.all(t2.data >= 0) and np.all(t2.data <= len(t1))) + + +class SplitTests(unittest.TestCase): + def test_split(self): + t = TensorBase(np.random.rand(7, 4)) + split_size = 3 + axis = 0 + target_shapes = [(3, 4), (3, 4), (1, 4)] + splits = syft.math.split(t, split_size, axis) + start = 0 + for target_shape, split in zip(target_shapes, splits): + self.assertTrue(syft.equal(split.shape(), target_shape)) + self.assertTrue(syft.equal(t.narrow(axis, start, target_shape[axis]), split)) + start += target_shape[axis] diff --git a/tests/test_tensor.py b/tests/test_tensor.py --- a/tests/test_tensor.py +++ b/tests/test_tensor.py @@ -974,13 +974,6 @@ def test_cumprod_(self): self.assertTrue(np.equal(t1.cumprod_(dim=1), t3).all()) -class SplitTests(unittest.TestCase): - def test_split(self): - t1 = TensorBase(np.arange(8.0)) - t2 = t1.split(4) - self.assertTrue(np.array_equal(t2, tuple((np.array([0., 1.]), np.array([2., 3.]), np.array([4., 5.]), np.array([6., 7.]))))) - - class SqueezeTests(unittest.TestCase): def test_squeeze(self): t1 = TensorBase(np.zeros((2, 1, 2, 1, 2))) @@ -1628,6 +1621,20 @@ def test_unfold_big(self): t1_unfolded_actual_2)) +class SplitTests(unittest.TestCase): + def test_split(self): + t = TensorBase(np.random.rand(10, 5)) + split_size = 3 + axis = 0 + target_shapes = [(3, 5), (3, 5), (3, 5), (1, 5)] + splits = t.split(split_size, axis) + start = 0 + for target_shape, split in zip(target_shapes, splits): + self.assertTrue(syft.equal(split.shape(), target_shape)) + self.assertTrue(syft.equal(t.narrow(axis, start, target_shape[axis]), split)) + start += target_shape[axis] + + if __name__ == "__main__": unittest.main()
Implement Default split Functionality for Base Tensor Type. <!-- Please make sure that you review this: https://github.com/OpenMined/Docs/blob/master/contributing/guidelines.md --> <!-- If you are looking to file a bug make sure to look at the .github/BUG_ISSUE_TEMPLATE.md --> #### User story: As a Data Scientist using Syft's Base Tensor type, I want to leverage a default method for computing operations on a Tensor of arbitrary type. For this ticket to be complete `split` should return a new tensor. For a reference on the operation these perform check out [PyTorch's](http://pytorch.org/docs/master/torch.html#torch.split) documentation. <!-- Provide a detailed explaination about the proposed feature, you can draw inspiration from something like this: https://github.com/OpenMined/PySyft/issues/227 or https://github.com/OpenMined/PySyft/issues/12 --> #### Acceptance Criteria: <!-- Provide an outline af all the things that needs to be addressed in order to close this Issue, be as descriptive as possible --> - [x] If the Base Tensor type's attribute "encrypted" is set to True, it should return a NotImplemented error. - [ ] corresponding unit tests demonstrating the correct operation on the Base Tensor type implemented over int and float Tensors. - [ ] inline documentation as described over [here](https://github.com/OpenMined/PySyft/blob/85bc68e81a2f4bfc0f0bf6c4252b88d6d7b54004/syft/math.py#L5). <!-- Thanks for your contributions! -->
I'll take this!
2017-10-31T09:08:36
OpenMined/PySyft
392
OpenMined__PySyft-392
[ "382" ]
34af4f778c2b2f1a16a5a8aa505c37b7d9b18009
diff --git a/syft/__init__.py b/syft/__init__.py --- a/syft/__init__.py +++ b/syft/__init__.py @@ -7,7 +7,8 @@ from syft.tensor import equal, TensorBase from syft.math import cumprod, cumsum, ceil, dot, matmul, addmm, addcmul from syft.math import addcdiv, addmv, bmm, addbmm, baddbmm, transpose -from syft.math import unsqueeze, zeros, ones, rand, randn, mm, fmod, diag, lerp, renorm, numel +from syft.math import unsqueeze, zeros, ones, rand, randn, mm, fmod, diag +from syft.math import lerp, renorm, numel, cross s = str(he) s += str(nn) @@ -26,3 +27,4 @@ s += str(lerp) s += str(numel) s += str(renorm) +s += str(cross) diff --git a/syft/math.py b/syft/math.py --- a/syft/math.py +++ b/syft/math.py @@ -20,7 +20,7 @@ 'cumprod', 'cumsum', 'ceil', 'dot', 'floor', 'matmul', 'addmm', 'addcmul', 'addcdiv', 'addmv', 'bmm', 'addbmm', 'baddbmm', 'sigmoid', 'unsqueeze', 'sin', 'sinh', 'cos', 'cosh', 'tan', 'tanh', 'zeros', 'ones', 'rand', - 'randn', 'mm', 'fmod', 'diag', 'lerp', 'renorm', 'numel' + 'randn', 'mm', 'fmod', 'diag', 'lerp', 'renorm', 'numel', 'cross' ] @@ -1008,3 +1008,49 @@ def split(tensor, split_size, axis=0): list_ = np.array_split(tensor.data, split_according, axis) return list(map(lambda x: TensorBase(x), list_)) + + +def cross(input, other, dim=-1): + """ + Computes cross products between two tensors in the given dimension + The two vectors must have the same size, and the size of the dim + dimension should be 3. + + Parameters + ---------- + + input: TensorBase + the first input tensor + + other: TensorBase + the second input tensor + + dim: int, optional + the dimension to take the cross-product in. Default is -1 + + Returns + ------- + TensorBase: The result Tensor + """ + input = _ensure_tensorbase(input) + other = _ensure_tensorbase(other) + + if input.encrypted or other.encrypted: + return NotImplemented + + # Verify that the shapes of both vectors are same + if input.shape() != other.shape(): + raise ValueError('inconsistent dimensions {} and {}'.format( + input.shape(), other.shape())) + + # verify that the given dim is valid + if dim < -len(input.shape()) or dim >= len(input.shape()): + raise ValueError('invalid dim. Should be between {} and {}'.format( + -len(input.shape()), len(input.shape()) - 1)) + + # verify that the size of dimension dim is 3 + if input.shape()[dim] != 3: + raise ValueError('size of dimension {}(dim) is {}. Should be 3'.format( + dim, input.shape()[-1])) + + return TensorBase(np.cross(input, other, axis=dim)) diff --git a/syft/tensor.py b/syft/tensor.py --- a/syft/tensor.py +++ b/syft/tensor.py @@ -3605,3 +3605,24 @@ def split(self, split_size, axis=0): return NotImplemented return syft.math.split(self, split_size, axis) + + def cross(self, tensor, dim=-1): + """ + Computes cross products between two tensors in the given dimension + The two vectors must have the same size, and the size of the dim + dimension should be 3. + + Parameters + ---------- + + tensor: TensorBase + the second input tensor + + dim: int, optional + the dimension to take the cross-product in. Default is -1 + + Returns + ------- + TensorBase: The result Tensor + """ + return syft.math.cross(self, tensor, dim)
diff --git a/tests/test_math.py b/tests/test_math.py --- a/tests/test_math.py +++ b/tests/test_math.py @@ -441,3 +441,31 @@ def test_split(self): self.assertTrue(syft.equal(split.shape(), target_shape)) self.assertTrue(syft.equal(t.narrow(axis, start, target_shape[axis]), split)) start += target_shape[axis] + + +class CrossTests(unittest.TestCase): + def setUp(self): + self.a = np.eye(2, 3) + self.b = np.ones((2, 3)) + + def test_cross(self): + a = TensorBase(self.a) + b = TensorBase(self.b) + + # Verify that the expected result is retuned + expected_result = np.array([0, -1, 1, 1, 0, -1]).reshape(2, 3) + self.assertTrue(np.array_equal(a.cross(b), expected_result)) + + # Verify that ValueError is thrown when dimension is out of bounds + self.assertRaises(ValueError, a.cross, b, 5) + + # Verify that ValueError is thrown when size dimension dim != 3 + self.assertRaises(ValueError, a.cross, b, 0) + + # Verify that ValueError is thrown when dimensions don't match + a = TensorBase(self.a.reshape(3, 2)) + self.assertRaises(ValueError, a.cross, b) + + # Verify that NotImplemented is returned if Tensor is encrypted + a = TensorBase(self.a, True) + self.assertEqual(a.cross(b), NotImplemented) diff --git a/tests/test_tensor.py b/tests/test_tensor.py --- a/tests/test_tensor.py +++ b/tests/test_tensor.py @@ -1635,6 +1635,20 @@ def test_split(self): start += target_shape[axis] +class CrossTests(unittest.TestCase): + def setUp(self): + self.a = np.eye(2, 3) + self.b = np.ones((2, 3)) + + def test_cross(self): + a = TensorBase(self.a) + b = TensorBase(self.b) + expected_result = np.array([0, -1, 1, 1, 0, -1]).reshape(2, 3) + + # Verify that the expected result is retuned + self.assertTrue(np.array_equal(a.cross(b), expected_result)) + + if __name__ == "__main__": unittest.main()
Implement Default cross Functionality for Base Tensor Type. <!-- Please make sure that you review this: https://github.com/OpenMined/Docs/blob/master/contributing/guidelines.md --> <!-- If you are looking to file a bug make sure to look at the .github/BUG_ISSUE_TEMPLATE.md --> #### User story: As a Data Scientist using Syft's Base Tensor type, I want to leverage a default method for computing operations on a Tensor of arbitrary type. For this ticket to be complete `cross` should return a new tensor. For a reference on the operation these perform check out [PyTorch's](http://pytorch.org/docs/master/torch.html#torch.cross) documentation. <!-- Provide a detailed explaination about the proposed feature, you can draw inspiration from something like this: https://github.com/OpenMined/PySyft/issues/227 or https://github.com/OpenMined/PySyft/issues/12 --> #### Acceptance Criteria: <!-- Provide an outline af all the things that needs to be addressed in order to close this Issue, be as descriptive as possible --> - [ ] If the Base Tensor type's attribute "encrypted" is set to True, it should return a NotImplemented error. - [ ] corresponding unit tests demonstrating the correct operation on the Base Tensor type implemented over int and float Tensors. - [ ] inline documentation as described over [here](https://github.com/OpenMined/PySyft/blob/85bc68e81a2f4bfc0f0bf6c4252b88d6d7b54004/syft/math.py#L5). <!-- Thanks for your contributions! -->
@bharathgs I'd like to take this one up. can I too work on this?
2017-11-02T19:06:29
OpenMined/PySyft
396
OpenMined__PySyft-396
[ "93", "93" ]
7222ce4e3f5ce54ab79f3039be6723a312600a32
diff --git a/syft/tensor.py b/syft/tensor.py --- a/syft/tensor.py +++ b/syft/tensor.py @@ -3095,7 +3095,7 @@ def stride(self, dim=None): return NotImplemented out = self.data.strides - output = tuple(map(lambda x: x / 8, out)) + output = tuple(map(lambda x: int(x / 8), out)) if dim is None: return output @@ -3481,6 +3481,114 @@ def unfold(self, dim, size, step): return TensorBase(np.concatenate(sub_arrays, axis=dim)) + def storage_offset(self): + """ + Returns this tensor’s offset in the underlying + storage in terms of number of storage elements (not bytes). + + Parameters + ---------- + + Returns + ------- + Offset of the underlying storage + """ + if self.encrypted: + return NotImplemented + + offset = 0 + + # Base ndarray has 0 offset + if self.data.base is None: + offset = 0 + + elif type(self.data.base) is bytes: + offset = 0 + + else: + offset_raw = len(self.data.base.tobytes()) - len(self.data.tobytes()) + offset = offset_raw / self.data.dtype.itemsize + + return offset + + def set_(self, source=None, offset=0, size=None, stride=None): + """ + Sets the source `numpy.ndarray`, offset, size, and strides. + + If only a tensor is passed in :attr:`source`, this tensor will share + the same `numpy.ndarray` and have the same size and strides as the + given tensor. Changes to elements in one tensor will be reflected + in the other. + + If :attr:`source` is `numpy.ndarray`, the method sets the underlying + `numpy.ndarray`, offset, size, and stride. + + Parameters + ---------- + + source: TensorBase or `numpy.ndarray` or None + Input Tensor or ndarray + + offset: int + The offset in the underlying `numpy.ndarray` in items not bytes. + + size: Tuple + The desired size. Defaults to the size of the source. + + stride: Tuple + The desired stride. Defaults to C-contiguous strides. + """ + + TYPE_ERROR = ''' Received invalid combination of arguments. Expected on of: + * no arguments + * (syft.TensorBase source) + * (np.ndarray storage) + * (np.ndarray storage, int offset, tuple size) + * (np.ndarray storage, int offset, tuple size, tuple stride) + ''' + + if self.encrypted or \ + (source is not None and type(source) is TensorBase and + source.encrypted): + return NotImplemented + + # Calling as _set(source=ndarray) + if source is not None and \ + type(source) is np.ndarray and \ + (offset, size, stride) == (0, None, None): + self.data = source + + # Calling as _set(source=ndarray, offset, size) + # Calling as _set(source=ndarray, offset, size, stride) + elif source is not None and type(source) is np.ndarray \ + and size is not None: + + _stride = stride + if stride is not None: + _stride = np.multiply(stride, 8) + + offset_nd = offset * self.data.dtype.itemsize + self.data = np.ndarray(shape=size, + buffer=source.data, + dtype=self.data.dtype, + offset=offset_nd, + strides=_stride) + + # Calling as _set(source=TensorBase) + elif source is not None and \ + type(source) is TensorBase and \ + (offset, size, stride) == (0, None, None): + self.data = source.data + + # Calling as _set() + elif (source, offset, size, stride) == (None, 0, None, None): + self.data = np.array(None) + + else: + raise TypeError(TYPE_ERROR) + + return self + def uniform(self, low=0, high=1): """ Returns a new tensor filled with numbers sampled uniformly
diff --git a/tests/test_tensor.py b/tests/test_tensor.py --- a/tests/test_tensor.py +++ b/tests/test_tensor.py @@ -5,6 +5,7 @@ import numpy as np import math import pytest +import struct # Here's our "unit tests". @@ -20,7 +21,6 @@ def test_view(self): def test_as_view(self): t = TensorBase(np.array([1.0, 2.0, 3.0])) t1 = t.view([-1, 1]) - print(t.data.dtype) self.assertTrue(syft.equal(t.view_as(t1), TensorBase(np.array([[1.0], [2.0], [3.0]])))) def test_resize(self): @@ -1575,6 +1575,220 @@ def testRenorm_(self): self.assertTrue(np.allclose(t, np.array([[1.0, 2.0, 3.0], [2.735054, 3.418817, 4.102581]]))) +class StorageTests(unittest.TestCase): + + def test_storage_offset(self): + # int + # create custom buffer + data = [7, 4, 5, 5, 8, 2, 1, 1, 4, 3, 9, 4, 9, 9, 3, 1] + buf = struct.pack('16i', *data) + + # Use custom buffer and ndarray tensors + t1 = TensorBase(np.ndarray(shape=(4, 4), buffer=buf, dtype=np.int32)) + t2 = TensorBase(np.array([[7, 4, 5, 5], + [8, 2, 1, 1], + [4, 3, 9, 4], + [9, 9, 3, 1]], dtype=np.int32)) + + # Test default offset = 0 + self.assertEqual(t1.storage_offset(), 0) + self.assertEqual(t2.storage_offset(), 0) + + # value of first element in first row [7,4,5,5] + self.assertEqual(t1[0][0], 7) + self.assertEqual(t2[0][0], 7) + + t1.set_(t1.data, offset=8, size=(2, 4)) + self.assertEqual(t1.storage_offset(), 8) + self.assertEqual(t1[0][0], 4) + + t2.set_(t2.data, offset=8, size=(2, 4)) + self.assertEqual(t2.storage_offset(), 8) + self.assertEqual(t2[0][0], 4) + + t1 = TensorBase(np.ndarray(shape=(4, 4), buffer=buf, dtype=np.int32)) + t1.set_(t1.data, offset=4, size=(3, 4)) + self.assertEqual(t1.storage_offset(), 4) + self.assertEqual(t1[0][0], 8) + + t2 = TensorBase(np.array([[7, 4, 5, 5], + [8, 2, 1, 1], + [4, 3, 9, 4], + [9, 9, 3, 1]], dtype=np.int32)) + t2.set_(t2.data, offset=4, size=(3, 4)) + self.assertEqual(t2.storage_offset(), 4) + self.assertEqual(t2[0][0], 8) + + def test_storage_offset_encrypted(self): + t1 = TensorBase(np.array([1, 2, 4, 4]), encrypted=True) + res = t1.storage_offset() + self.assertEqual(res, NotImplemented) + + def test_tensor_set_encrypted(self): + t1 = TensorBase(np.array([])) + t2 = TensorBase(np.array([1, 2, 3, 4]), encrypted=True) + res = t1.set_(t2) + self.assertEqual(res, NotImplemented) + + res = t2.set_(t1) + self.assertEqual(res, NotImplemented) + + def test_tensor_set_source_nd(self): + t1 = np.array([1, 2, 3, 4]) + t2 = np.array([0.1, 0.2, 0.3, 0.4]) + + tb = TensorBase([]) + tb2 = TensorBase([]) + + r1 = tb.set_(t1) + r2 = tb2.set_(t2) + + self.assertEqual(tb, t1) + self.assertEqual(tb2, t2) + + self.assertEqual(r1, t1) + self.assertEqual(r2, t2) + + def test_tensor_set_empty(self): + t1 = TensorBase([1, 2, 3, 4]) + t2 = TensorBase([0.1, 0.2, 0.3, 0.4]) + + # Tensor with none storage + tn = TensorBase([]) + tn.data = np.array(None) + + # test set_ with no argument + result = t1.set_() + result_f = t2.set_() + + self.assertEqual(result.data, tn.data) + self.assertEqual(result_f.data, tn.data) + + def test_tensor_set_(self): + t1 = TensorBase([1, 2, 3, 4]) + t2 = TensorBase([0.1, 0.2, 0.3, 0.4]) + + # test call signature + with pytest.raises(TypeError): + t1.set_(offset=2) + t1.set_(size=2) + t1.set_(stride=(1,)) + t1.set_(offset=2, size=(1,)) + t1.set_(offset=2, size=(1,), stride=(1,)) + t1.set_(t2, offset=2, size=(1,), stride=(1,)) + + # end test call signature + + # tests on ints + + # begin setting tensor + + t1 = TensorBase([]) + t2 = TensorBase(np.array([1, 2, 3, 4])) + t1.set_(t2) + + # memory location is the same + self.assertEqual(t1.data.__array_interface__['data'], + t2.data.__array_interface__['data']) + + # data is the same + self.assertTrue((t1.data == t2.data).all()) + self.assertEqual(t1.data.dtype, np.int) + + # stride and size are the same + self.assertEqual(t1.size(), t2.size()) + self.assertEqual(t1.stride(), t2.stride()) + + # end setting tensor + + # begin set offset and size + + t1 = TensorBase([1, 2, 3, 4]) + + t1.set_(t1.data, offset=1, size=(3,)) + self.assertEqual(t1[0], 2) + self.assertEqual(t1[2], 4) + + with pytest.raises(IndexError): + t1[3] + + # end set offset and size + + # begin set strides + t1 = TensorBase([]) + t2 = TensorBase(np.zeros(shape=(3, 4, 9, 10), dtype=np.int)) + + # set strides on new ndarray + strides = (10, 360, 90, 1) + size = (9, 3, 4, 10) + t1.set_(t2.data, 0, size, strides) + + self.assertEqual(t1.data.base.__array_interface__['data'], + t2.data.__array_interface__['data']) + + self.assertEqual(t1.stride(), strides) + + # set strides on underlying ndarray + t1 = TensorBase(np.zeros(shape=(3, 4, 9, 10))).uniform_() + strides = (10, 360, 90, 1) + size = (9, 3, 4, 10) + + t1.set_(t1.data, offset=0, size=size, stride=strides) + self.assertEqual(t1.stride(), strides) + + # end set strides + + # tests on floats ####### + + # begin setting the underlying ndarray + + t1 = TensorBase([]) + t2 = TensorBase(np.array([1.0, 2.0, 3.0])) + t1.set_(t2) + self.assertEqual(t1.data.__array_interface__['data'], t2.data.__array_interface__['data']) + self.assertTrue((t1.data == t2.data).all()) + self.assertEqual(t1.data.dtype, np.float) + self.assertEqual(t1.size(), t2.size()) + self.assertEqual(t1.stride(), t2.stride()) + + # end setting the underlying ndarray + + # begin set offset and size + + t2 = TensorBase(np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])) + + t2.set_(t2.data, offset=3, size=(3,)) + self.assertEqual(t2[0], 4.0) + self.assertEqual(t2[2], 6.0) + with pytest.raises(IndexError): + t2[3] + + # end set offset and size + + # begin set strides + + t1 = TensorBase([]) + shape = (3, 4, 9, 10) + t2 = TensorBase(np.zeros(shape=shape, dtype=np.float)) + + # set strides on new ndarray + strides = (10, 360, 90, 1) + size = (9, 3, 4, 10) + t1.set_(t2.data, 0, size, strides) + self.assertEqual(t1.data.base.__array_interface__['data'], + t2.data.__array_interface__['data']) + self.assertEqual(t1.stride(), strides) + + # set strides on underlying ndarray + t1 = TensorBase(np.zeros(shape=shape, dtype=np.float)) + strides = (10, 360, 90, 1) + size = (9, 3, 4, 10) + + t1.set_(t1.data, offset=0, size=size, stride=strides) + self.assertEqual(t1.stride(), strides) + # end set strides + + class SparseTests(unittest.TestCase): def test_sparse(self): matrix = TensorBase(np.array([[1, 0], [0, 0]]))
Implement Default set Functionality for Base Tensor Type **User Story A:** As a Data Scientist using Syft's Base Tensor type, I want to leverage a default method for computing operations on a Tensor of arbitrary type. For this ticket to be complete, set_() should operate inline. For a reference on the operation this performs check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation. **Acceptance Criteria:** - If the Base Tensor type's attribute "encrypted" is set to True, it should return a NotImplemented error. - a unit test demonstrating the correct operation on the Base Tensor type implemented over int and float Tensors. - inline documentation in the python code. For inspiration on inline documentation, please check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation for this operator. Implement Default set Functionality for Base Tensor Type **User Story A:** As a Data Scientist using Syft's Base Tensor type, I want to leverage a default method for computing operations on a Tensor of arbitrary type. For this ticket to be complete, set_() should operate inline. For a reference on the operation this performs check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation. **Acceptance Criteria:** - If the Base Tensor type's attribute "encrypted" is set to True, it should return a NotImplemented error. - a unit test demonstrating the correct operation on the Base Tensor type implemented over int and float Tensors. - inline documentation in the python code. For inspiration on inline documentation, please check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation for this operator.
I will work on this one. I have a few questions before moving forward. What does **should operate inline** mean ? The [pytorch signature](http://pytorch.org/docs/master/tensors.html#torch.Tensor.set_) for this function is `set_(source=None, storage_offset=0, size=None, stride=None)` and the **source** parameter can be either a Tensor, or a Storage which is custom made by an underlying C extension However since our tensor's internal storage is an ndarray the source is always going to be a Tensor right ? which means size is useless, or am I missing something ? For reference: [ndarray underlying strucutre](https://docs.scipy.org/doc/numpy/reference/arrays.interface.html#__array_interface__) @iamtrask can you give a bit more details how this method is supposed to behave ? There are many ways to implement this and I'm not sure if the signature needs to be the same as PyTorch I will work on this one. I have a few questions before moving forward. What does **should operate inline** mean ? The [pytorch signature](http://pytorch.org/docs/master/tensors.html#torch.Tensor.set_) for this function is `set_(source=None, storage_offset=0, size=None, stride=None)` and the **source** parameter can be either a Tensor, or a Storage which is custom made by an underlying C extension However since our tensor's internal storage is an ndarray the source is always going to be a Tensor right ? which means size is useless, or am I missing something ? For reference: [ndarray underlying strucutre](https://docs.scipy.org/doc/numpy/reference/arrays.interface.html#__array_interface__) @iamtrask can you give a bit more details how this method is supposed to behave ? There are many ways to implement this and I'm not sure if the signature needs to be the same as PyTorch
2017-11-10T13:35:27
OpenMined/PySyft
676
OpenMined__PySyft-676
[ "572" ]
7273b65302b6e0b68aaa65e0e99f13b50c196998
diff --git a/syft/syft.py b/syft/syft.py --- a/syft/syft.py +++ b/syft/syft.py @@ -102,6 +102,9 @@ def __imul__(self, x): def neg(self): return self.no_params_func("neg", return_response=True) + def rsqrt(self): + return self.no_params_func("rsqrt",return_response=True) + def sigmoid_(self): return self.no_params_func("sigmoid_")
Implement rsqrt Functionality in FloatTensor with CPU/GPU Backend Support ### User Story: As a Data Scientist using PySyft's FloatTensor type, I want to leverage a wide range of methods which use our new Unity backend. For this ticket to be complete, the rsqrt() should be added to our FloatTensor class with the appropriate functionality, returning a new tensor. Furthermore, the function should automatically determine which backend to use (CPU/GPU) based on where the data is located. If the data is located on the CPU, a performant CPU implementation should run but if the data for a given FloatTensor is located on a GPU, it should be run using an HLSL kernel where appropriate. Obviously, if no GPU is available, it should automatically fall back to the CPU implementation. ### Every Reference You Might Need for this Issue: - For a reference on the operation this performs check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation. - For a reference on how to program in Unity, check out [this basic tutorial](https://unity3d.com/learn/tutorials/projects/roll-ball-tutorial) - For a reference on how to write HLSL code, check out [this basic tutorial](http://kylehalladay.com/blog/tutorial/2014/06/27/Compute-Shaders-Are-Nifty.html) - For a complete tutorial on how to add functions to FloatTensor (step by step guide) see [this Google Document](https://docs.google.com/document/d/1WRd7gGLFN0Awtf86AICYIHtg3gfFWLBa5wYTthsB3i0/edit) - For a reference on how other functions like this have been implemented check out the functions in [this notebook](https://github.com/OpenMined/OpenMined/blob/master/notebooks/Syft%20Tensor%20Example%20Notebook.ipynb) as well as the corresponding files that made it possible ([SyftController](https://github.com/OpenMined/OpenMined/blob/master/Assets/OpenMined/Network/Controllers/SyftController.cs), [FloatTensor.Ops](https://github.com/OpenMined/OpenMined/blob/master/Assets/OpenMined/Syft/Tensor/FloatTensor.Ops.cs), [FloatTensor.ShaderOps](https://github.com/OpenMined/OpenMined/blob/master/Assets/OpenMined/Syft/Tensor/FloatTensor.ShaderOps.cs), [FloatTensorShaders](https://github.com/OpenMined/OpenMined/blob/master/Assets/OpenMined/Syft/Math/Shaders/FloatTensorShaders.compute), and [FloatTensorTest](https://github.com/OpenMined/OpenMined/blob/master/Assets/OpenMined.Tests/Editor/FloatTensorTest.cs)). - And of course, please consider our [Contributor Guidelines](https://github.com/OpenMined/Docs/blob/master/contributing/guidelines.md) for all contributions. ### Acceptance Criteria: - [ ] an integration test in PySyft demonstrating the correct CPU and GPU operation implemented over a FloatTensor while connected to a Unity backend - [ ] a Unit Test in OpenMined/OpenMined demonstrating the correct operation on a FloatTensor - [ ] [inline](http://pytorch.org/docs/master/tensors.html) documentation in the python code. For inspiration on inline documentation, please check out PyTorch's documentation for this operator. - [ ] Link your Pull Request back to this Issue so that it gets closed appropriately when the PR is merged.
2017-12-04T20:08:31
OpenMined/PySyft
1,280
OpenMined__PySyft-1280
[ "1246" ]
c93650ca1cea0bbecd96daa3e784967a35a69ce8
diff --git a/syft/tensor.py b/syft/tensor.py --- a/syft/tensor.py +++ b/syft/tensor.py @@ -292,6 +292,16 @@ def shape(self): """ return list(np.fromstring(self.get("shape")[:-1], sep=",").astype('int')) + def trace(self): + """ + Returns a new tensor with the sum along diagonals of a 2D tensor. + Returns + ------- + IntTensor + Output tensor + """ + return self.no_params_func("trace", return_response=True) + def __repr__(self, verbose=True): tensor_str = str(self.to_numpy())
Implement the Trace function for IntTensor on the CPU As a Data Scientist using PySyft's IntTensor type, I want to leverage a wide range of methods which use our new Unity backend. For this ticket to be complete, the trace() should be added to our IntTensor class with the appropriate functionality, returning a new tensor. If you want to take it to the next level, boost it implementing the operation on the GPU: Search for an issue titled like this but with "on the GPU" on the title! HLSL (GPU language) tutorial here: [Direct Compute Programming Guide](https://github.com/OpenMined/OpenMined/blob/master/tutorials/DirectCompute_Programming_Guide.md) Note, it is possible that when you look in the code you'll find that parts of this issue were completed on the backend while implementing another issue. This is normal as features do not live in isolation. If this is the case, just take it as a convenience that someone already built that part and press on! ### Every Reference You Might Need for this Issue: - For a reference on the operation this performs check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation. - For a reference on how to program in Unity, check out [this basic tutorial](https://unity3d.com/learn/tutorials/projects/roll-ball-tutorial) - For a reference on how to write HLSL code, check out [this basic tutorial](http://kylehalladay.com/blog/tutorial/2014/06/27/Compute-Shaders-Are-Nifty.html) - For a complete tutorial on how to add functions to FloatTensor (step by step guide) see [this Google Document](https://docs.google.com/document/d/1WRd7gGLFN0Awtf86AICYIHtg3gfFWLBa5wYTthsB3i0/edit) - For a reference on how other functions like this have been implemented check out the functions in [this notebook](https://github.com/OpenMined/OpenMined/blob/master/notebooks/Syft%20Tensor%20Example%20Notebook.ipynb) as well as the corresponding files that made it possible ([SyftController](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined/Network/Controllers/SyftController.cs), [FloatTensor.Ops](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined/Syft/Tensor/FloatTensor.Ops.cs), [FloatTensorShaders](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined/Syft/Tensor/Ops/Shaders/FloatTensorShaders.compute), [TensorOpsShaders](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined/Syft/Tensor/Ops/Shaders/TensorOpsShaders.compute), [FloatTensorTest](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined.Tests/Editor/FloatTensor/FloatTensorTest.cs) and [FloatTensorGpuTest](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined.Tests/Editor/FloatTensor/FloatTensorGpuTest.cs)). - And of course, please consider our [Contributor Guidelines](https://github.com/OpenMined/Docs/blob/master/contributing/guidelines.md) for all contributions. ### Acceptance Criteria: - [ ] comment below that you're picking up this project - [ ] an example in a notebook in our [tests folder](https://github.com/OpenMined/OpenMined/tree/master/notebooks/tests) showing how to use the functionality from PySyft - [ ] an integration test in PySyft demonstrating the correct CPU operation implemented over an IntTensor while connected to a Unity backend - [ ] a Unit Test in OpenMined/OpenMined demonstrating the correct operation on a FloatTensor - [ ] [inline](http://pytorch.org/docs/master/tensors.html) documentation in the python code. For inspiration on inline documentation, please check out PyTorch's documentation for this operator. - [ ] Link your Pull Request back to this Issue so that it gets closed appropriately when the PR is merged.
Trying this
2018-01-13T21:09:22
OpenMined/PySyft
1,283
OpenMined__PySyft-1283
[ "1075" ]
1bfa092c16e1c291bc49d012969a8a414ae2a17b
diff --git a/syft/tensor.py b/syft/tensor.py --- a/syft/tensor.py +++ b/syft/tensor.py @@ -339,6 +339,30 @@ def equal(self, x): else: return False + def neg(self): + """ + Sets negative of the elements of tensor. + Parameters + ---------- + Returns + ------- + IntTensor + Output tensor + """ + return self.no_params_func("neg", return_response=True) + + def neg_(self): + """ + Sets negative of the elements of tensor inplace. + Parameters + ---------- + Returns + ------- + IntTensor + Caller with values inplace + """ + return self.no_params_func("neg_") + def shape(self): """ Returns the size of the self tensor as a List.
Implement the Neg function for IntTensor on the CPU As a Data Scientist using PySyft's IntTensor type, I want to leverage a wide range of methods which use our new Unity backend. For this ticket to be complete, the neg() should be added to our IntTensor class with the appropriate functionality, returning a new tensor. If you want to take it to the next level, boost it implementing the operation on the GPU: Search for an issue titled like this but with "on the GPU" on the title! HLSL (GPU language) tutorial here: [Direct Compute Programming Guide](https://github.com/OpenMined/OpenMined/blob/master/tutorials/DirectCompute_Programming_Guide.md) Note, it is possible that when you look in the code you'll find that parts of this issue were completed on the backend while implementing another issue. This is normal as features do not live in isolation. If this is the case, just take it as a convenience that someone already built that part and press on! ### Every Reference You Might Need for this Issue: - For a reference on the operation this performs check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation. - For a reference on how to program in Unity, check out [this basic tutorial](https://unity3d.com/learn/tutorials/projects/roll-ball-tutorial) - For a reference on how to write HLSL code, check out [this basic tutorial](http://kylehalladay.com/blog/tutorial/2014/06/27/Compute-Shaders-Are-Nifty.html) - For a complete tutorial on how to add functions to FloatTensor (step by step guide) see [this Google Document](https://docs.google.com/document/d/1WRd7gGLFN0Awtf86AICYIHtg3gfFWLBa5wYTthsB3i0/edit) - For a reference on how other functions like this have been implemented check out the functions in [this notebook](https://github.com/OpenMined/OpenMined/blob/master/notebooks/Syft%20Tensor%20Example%20Notebook.ipynb) as well as the corresponding files that made it possible ([SyftController](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined/Network/Controllers/SyftController.cs), [FloatTensor.Ops](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined/Syft/Tensor/FloatTensor.Ops.cs), [FloatTensorShaders](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined/Syft/Tensor/Ops/Shaders/FloatTensorShaders.compute), [TensorOpsShaders](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined/Syft/Tensor/Ops/Shaders/TensorOpsShaders.compute), [FloatTensorTest](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined.Tests/Editor/FloatTensor/FloatTensorTest.cs) and [FloatTensorGpuTest](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined.Tests/Editor/FloatTensor/FloatTensorGpuTest.cs)). - And of course, please consider our [Contributor Guidelines](https://github.com/OpenMined/Docs/blob/master/contributing/guidelines.md) for all contributions. ### Acceptance Criteria: - [ ] comment below that you're picking up this project - [ ] an example in a notebook in our [tests folder](https://github.com/OpenMined/OpenMined/tree/master/notebooks/tests) showing how to use the functionality from PySyft - [ ] an integration test in PySyft demonstrating the correct CPU operation implemented over an IntTensor while connected to a Unity backend - [ ] a Unit Test in OpenMined/OpenMined demonstrating the correct operation on a FloatTensor - [ ] [inline](http://pytorch.org/docs/master/tensors.html) documentation in the python code. For inspiration on inline documentation, please check out PyTorch's documentation for this operator. - [ ] Link your Pull Request back to this Issue so that it gets closed appropriately when the PR is merged.
Okay I'll take this one
2018-01-14T00:12:35
OpenMined/PySyft
1,284
OpenMined__PySyft-1284
[ "763" ]
55de55d0c962220984f20d4d25c1e663ac443131
diff --git a/syft/tensor.py b/syft/tensor.py --- a/syft/tensor.py +++ b/syft/tensor.py @@ -281,6 +281,18 @@ def abs(self): """ return self.no_params_func("abs", return_response=True) + def abs_(self): + """ + Replaces tensor values with its absolute value + Parameters + ---------- + Returns + ------- + IntTensor + Output tensor + """ + return self.no_params_func("abs_", return_response=True) + def equal(self, x): """ Determines whether the given tensor has the same size and elements as this instance. @@ -853,6 +865,7 @@ def floor_(self): Caller with values inplace """ return self.no_params_func("floor_") + def random_(self): """ Returns a tensor filled with random numbers from a uniform distribution on the interval [0,1)
Implement the inline Abs function for IntTensor on the CPU As a Data Scientist using PySyft's IntTensor type, I want to leverage a wide range of methods which use our new Unity backend. For this ticket to be complete, the inline abs() should be added to our IntTensor class with the appropriate functionality. If you want to take it to the next level, boost it implementing the operation on the GPU: Search for an issue titled like this but with "on the GPU" on the title! HLSL (GPU language) tutorial here: [Direct Compute Programming Guide](https://github.com/OpenMined/OpenMined/blob/master/tutorials/DirectCompute_Programming_Guide.md) Note, it is possible that when you look in the code you'll find that parts of this issue were completed on the backend while implementing another issue. This is normal as features do not live in isolation. If this is the case, just take it as a convenience that someone already built that part and press on! ### Every Reference You Might Need for this Issue: - For a reference on the operation this performs check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation. - For a reference on how to program in Unity, check out [this basic tutorial](https://unity3d.com/learn/tutorials/projects/roll-ball-tutorial) - For a reference on how to write HLSL code, check out [this basic tutorial](http://kylehalladay.com/blog/tutorial/2014/06/27/Compute-Shaders-Are-Nifty.html) - For a complete tutorial on how to add functions to FloatTensor (step by step guide) see [this Google Document](https://docs.google.com/document/d/1WRd7gGLFN0Awtf86AICYIHtg3gfFWLBa5wYTthsB3i0/edit) - For a reference on how other functions like this have been implemented check out the functions in [this notebook](https://github.com/OpenMined/OpenMined/blob/master/notebooks/Syft%20Tensor%20Example%20Notebook.ipynb) as well as the corresponding files that made it possible ([SyftController](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined/Network/Controllers/SyftController.cs), [FloatTensor.Ops](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined/Syft/Tensor/FloatTensor.Ops.cs), [FloatTensorShaders](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined/Syft/Tensor/Ops/Shaders/FloatTensorShaders.compute), [TensorOpsShaders](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined/Syft/Tensor/Ops/Shaders/TensorOpsShaders.compute), [FloatTensorTest](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined.Tests/Editor/FloatTensor/FloatTensorTest.cs) and [FloatTensorGpuTest](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined.Tests/Editor/FloatTensor/FloatTensorGpuTest.cs)). - And of course, please consider our [Contributor Guidelines](https://github.com/OpenMined/Docs/blob/master/contributing/guidelines.md) for all contributions. ### Acceptance Criteria: - [ ] comment below that you're picking up this project - [ ] an example in a notebook in our [tests folder](https://github.com/OpenMined/OpenMined/tree/master/notebooks/tests) showing how to use the functionality from PySyft - [ ] an integration test in PySyft demonstrating the correct CPU operation implemented over an IntTensor while connected to a Unity backend - [ ] a Unit Test in OpenMined/OpenMined demonstrating the correct operation on a FloatTensor - [ ] [inline](http://pytorch.org/docs/master/tensors.html) documentation in the python code. For inspiration on inline documentation, please check out PyTorch's documentation for this operator. - [ ] Link your Pull Request back to this Issue so that it gets closed appropriately when the PR is merged.
I'll take that and probably do a pull request later today.
2018-01-14T00:31:20
OpenMined/PySyft
1,288
OpenMined__PySyft-1288
[ "1039" ]
e9c7a19ae766dc13bbd45dae19081e150290d537
diff --git a/syft/tensor.py b/syft/tensor.py --- a/syft/tensor.py +++ b/syft/tensor.py @@ -293,6 +293,39 @@ def abs_(self): """ return self.no_params_func("abs_", return_response=True) + def lt(self, other): + """ + Performs element-wise > comparison and returns 1 if the element + is less than a corresponding element in other Tensor, and 0 otherwise. + Returns a new Tensor with results of the comparison. + + Parameters + __________ + other: IntTensor to compare with + + Returns + _________ + IntTensor + Output tensor + """ + return self.params_func("lt", [other.id], return_response=True) + + def lt_(self, other): + """ + Performs inline element-wise > comparison and returns 1 if the element + is less than a corresponding element in other Tensor, and 0 otherwise. + + Parameters + __________ + other: IntTensor to compare with + + Returns + _________ + IntTensor + Output tensor + """ + return self.params_func("lt_", [other.id], return_response=True) + def equal(self, x): """ Determines whether the given tensor has the same size and elements as this instance.
Implement the Lt function for IntTensor on the CPU As a Data Scientist using PySyft's IntTensor type, I want to leverage a wide range of methods which use our new Unity backend. For this ticket to be complete, the lt() should be added to our IntTensor class with the appropriate functionality, returning a new tensor. If you want to take it to the next level, boost it implementing the operation on the GPU: Search for an issue titled like this but with "on the GPU" on the title! HLSL (GPU language) tutorial here: [Direct Compute Programming Guide](https://github.com/OpenMined/OpenMined/blob/master/tutorials/DirectCompute_Programming_Guide.md) Note, it is possible that when you look in the code you'll find that parts of this issue were completed on the backend while implementing another issue. This is normal as features do not live in isolation. If this is the case, just take it as a convenience that someone already built that part and press on! ### Every Reference You Might Need for this Issue: - For a reference on the operation this performs check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation. - For a reference on how to program in Unity, check out [this basic tutorial](https://unity3d.com/learn/tutorials/projects/roll-ball-tutorial) - For a reference on how to write HLSL code, check out [this basic tutorial](http://kylehalladay.com/blog/tutorial/2014/06/27/Compute-Shaders-Are-Nifty.html) - For a complete tutorial on how to add functions to FloatTensor (step by step guide) see [this Google Document](https://docs.google.com/document/d/1WRd7gGLFN0Awtf86AICYIHtg3gfFWLBa5wYTthsB3i0/edit) - For a reference on how other functions like this have been implemented check out the functions in [this notebook](https://github.com/OpenMined/OpenMined/blob/master/notebooks/Syft%20Tensor%20Example%20Notebook.ipynb) as well as the corresponding files that made it possible ([SyftController](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined/Network/Controllers/SyftController.cs), [FloatTensor.Ops](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined/Syft/Tensor/FloatTensor.Ops.cs), [FloatTensorShaders](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined/Syft/Tensor/Ops/Shaders/FloatTensorShaders.compute), [TensorOpsShaders](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined/Syft/Tensor/Ops/Shaders/TensorOpsShaders.compute), [FloatTensorTest](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined.Tests/Editor/FloatTensor/FloatTensorTest.cs) and [FloatTensorGpuTest](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined.Tests/Editor/FloatTensor/FloatTensorGpuTest.cs)). - And of course, please consider our [Contributor Guidelines](https://github.com/OpenMined/Docs/blob/master/contributing/guidelines.md) for all contributions. ### Acceptance Criteria: - [ ] comment below that you're picking up this project - [ ] an example in a notebook in our [tests folder](https://github.com/OpenMined/OpenMined/tree/master/notebooks/tests) showing how to use the functionality from PySyft - [ ] an integration test in PySyft demonstrating the correct CPU operation implemented over an IntTensor while connected to a Unity backend - [ ] a Unit Test in OpenMined/OpenMined demonstrating the correct operation on a FloatTensor - [ ] [inline](http://pytorch.org/docs/master/tensors.html) documentation in the python code. For inspiration on inline documentation, please check out PyTorch's documentation for this operator. - [ ] Link your Pull Request back to this Issue so that it gets closed appropriately when the PR is merged.
I'll take that.
2018-01-14T19:09:50
OpenMined/PySyft
1,296
OpenMined__PySyft-1296
[ "1178" ]
b9537ad181195f7afe8f2f6ae15f4a286c99ab8c
diff --git a/syft/tensor.py b/syft/tensor.py --- a/syft/tensor.py +++ b/syft/tensor.py @@ -417,6 +417,18 @@ def trace(self): Output tensor """ return self.no_params_func("trace", return_response=True) + + def sin(self): + """ + Computes sin of each element of the tensor. + Parameters + ---------- + Returns + ------- + FloatTensor + Output Tensor + """ + return self.no_params_func("sin", return_response=True, return_type='FloatTensor'); def __repr__(self, verbose=True):
Implement the Sin function for IntTensor on the CPU As a Data Scientist using PySyft's IntTensor type, I want to leverage a wide range of methods which use our new Unity backend. For this ticket to be complete, the sin() should be added to our IntTensor class with the appropriate functionality, returning a new tensor. If you want to take it to the next level, boost it implementing the operation on the GPU: Search for an issue titled like this but with "on the GPU" on the title! HLSL (GPU language) tutorial here: [Direct Compute Programming Guide](https://github.com/OpenMined/OpenMined/blob/master/tutorials/DirectCompute_Programming_Guide.md) Note, it is possible that when you look in the code you'll find that parts of this issue were completed on the backend while implementing another issue. This is normal as features do not live in isolation. If this is the case, just take it as a convenience that someone already built that part and press on! ### Every Reference You Might Need for this Issue: - For a reference on the operation this performs check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation. - For a reference on how to program in Unity, check out [this basic tutorial](https://unity3d.com/learn/tutorials/projects/roll-ball-tutorial) - For a reference on how to write HLSL code, check out [this basic tutorial](http://kylehalladay.com/blog/tutorial/2014/06/27/Compute-Shaders-Are-Nifty.html) - For a complete tutorial on how to add functions to FloatTensor (step by step guide) see [this Google Document](https://docs.google.com/document/d/1WRd7gGLFN0Awtf86AICYIHtg3gfFWLBa5wYTthsB3i0/edit) - For a reference on how other functions like this have been implemented check out the functions in [this notebook](https://github.com/OpenMined/OpenMined/blob/master/notebooks/Syft%20Tensor%20Example%20Notebook.ipynb) as well as the corresponding files that made it possible ([SyftController](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined/Network/Controllers/SyftController.cs), [FloatTensor.Ops](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined/Syft/Tensor/FloatTensor.Ops.cs), [FloatTensorShaders](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined/Syft/Tensor/Ops/Shaders/FloatTensorShaders.compute), [TensorOpsShaders](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined/Syft/Tensor/Ops/Shaders/TensorOpsShaders.compute), [FloatTensorTest](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined.Tests/Editor/FloatTensor/FloatTensorTest.cs) and [FloatTensorGpuTest](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined.Tests/Editor/FloatTensor/FloatTensorGpuTest.cs)). - And of course, please consider our [Contributor Guidelines](https://github.com/OpenMined/Docs/blob/master/contributing/guidelines.md) for all contributions. ### Acceptance Criteria: - [ ] comment below that you're picking up this project - [ ] an example in a notebook in our [tests folder](https://github.com/OpenMined/OpenMined/tree/master/notebooks/tests) showing how to use the functionality from PySyft - [ ] an integration test in PySyft demonstrating the correct CPU operation implemented over an IntTensor while connected to a Unity backend - [ ] a Unit Test in OpenMined/OpenMined demonstrating the correct operation on a FloatTensor - [ ] [inline](http://pytorch.org/docs/master/tensors.html) documentation in the python code. For inspiration on inline documentation, please check out PyTorch's documentation for this operator. - [ ] Link your Pull Request back to this Issue so that it gets closed appropriately when the PR is merged.
Working on this one.
2018-01-17T12:26:35
OpenMined/PySyft
1,297
OpenMined__PySyft-1297
[ "890" ]
cc7dfabdb9eeb6109398a4364583c1988d4c9a27
diff --git a/syft/tensor.py b/syft/tensor.py --- a/syft/tensor.py +++ b/syft/tensor.py @@ -292,6 +292,18 @@ def abs_(self): """ return self.no_params_func("abs_", return_response=True) + def cos(self): + """ + Computes cos of each element of the tensor. + Parameters + ---------- + Returns + ------- + FloatTensor + Output Tensor + """ + return self.no_params_func("cos", return_response=True, return_type='FloatTensor') + def lt(self, other): """ Performs element-wise > comparison and returns 1 if the element
Implement the Cos function for IntTensor on the CPU As a Data Scientist using PySyft's IntTensor type, I want to leverage a wide range of methods which use our new Unity backend. For this ticket to be complete, the cos() should be added to our IntTensor class with the appropriate functionality, returning a new tensor. If you want to take it to the next level, boost it implementing the operation on the GPU: Search for an issue titled like this but with "on the GPU" on the title! HLSL (GPU language) tutorial here: [Direct Compute Programming Guide](https://github.com/OpenMined/OpenMined/blob/master/tutorials/DirectCompute_Programming_Guide.md) Note, it is possible that when you look in the code you'll find that parts of this issue were completed on the backend while implementing another issue. This is normal as features do not live in isolation. If this is the case, just take it as a convenience that someone already built that part and press on! ### Every Reference You Might Need for this Issue: - For a reference on the operation this performs check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation. - For a reference on how to program in Unity, check out [this basic tutorial](https://unity3d.com/learn/tutorials/projects/roll-ball-tutorial) - For a reference on how to write HLSL code, check out [this basic tutorial](http://kylehalladay.com/blog/tutorial/2014/06/27/Compute-Shaders-Are-Nifty.html) - For a complete tutorial on how to add functions to FloatTensor (step by step guide) see [this Google Document](https://docs.google.com/document/d/1WRd7gGLFN0Awtf86AICYIHtg3gfFWLBa5wYTthsB3i0/edit) - For a reference on how other functions like this have been implemented check out the functions in [this notebook](https://github.com/OpenMined/OpenMined/blob/master/notebooks/Syft%20Tensor%20Example%20Notebook.ipynb) as well as the corresponding files that made it possible ([SyftController](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined/Network/Controllers/SyftController.cs), [FloatTensor.Ops](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined/Syft/Tensor/FloatTensor.Ops.cs), [FloatTensorShaders](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined/Syft/Tensor/Ops/Shaders/FloatTensorShaders.compute), [TensorOpsShaders](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined/Syft/Tensor/Ops/Shaders/TensorOpsShaders.compute), [FloatTensorTest](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined.Tests/Editor/FloatTensor/FloatTensorTest.cs) and [FloatTensorGpuTest](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined.Tests/Editor/FloatTensor/FloatTensorGpuTest.cs)). - And of course, please consider our [Contributor Guidelines](https://github.com/OpenMined/Docs/blob/master/contributing/guidelines.md) for all contributions. ### Acceptance Criteria: - [ ] comment below that you're picking up this project - [ ] an example in a notebook in our [tests folder](https://github.com/OpenMined/OpenMined/tree/master/notebooks/tests) showing how to use the functionality from PySyft - [ ] an integration test in PySyft demonstrating the correct CPU operation implemented over an IntTensor while connected to a Unity backend - [ ] a Unit Test in OpenMined/OpenMined demonstrating the correct operation on a FloatTensor - [ ] [inline](http://pytorch.org/docs/master/tensors.html) documentation in the python code. For inspiration on inline documentation, please check out PyTorch's documentation for this operator. - [ ] Link your Pull Request back to this Issue so that it gets closed appropriately when the PR is merged.
working on this.
2018-01-18T14:41:18
OpenMined/PySyft
1,300
OpenMined__PySyft-1300
[ "786" ]
ddaabb5163508483dc26fbc77611e278405488e7
diff --git a/syft/tensor.py b/syft/tensor.py --- a/syft/tensor.py +++ b/syft/tensor.py @@ -337,6 +337,30 @@ def lt_(self, other): """ return self.params_func("lt_", [other.id], return_response=True) + def eq(self, other): + """ + Determines whether 'other' (IntTensor) has the same elements as self (IntTensor). + + parameters: + other: IntTensor, of the same dimension as self + returns: IntTensor, with values + 1 - when the elements are equal + 0 - when the elements are not equal + """ + return self.params_func("eq", [other.id], return_response=True) + + def eq_(self, other): + """ + Determines whether 'other' (IntTensor) has the same elements as self (IntTensor). + + parameters: + other: IntTensor, of the same dimension as self + returns: IntTensor, with values + 1 - when the elements are equal + 0 - when the elements are not equal + """ + return self.params_func("eq_", [other.id], return_response=True) + def equal(self, x): """ Determines whether the given tensor has the same size and elements as this instance. @@ -361,7 +385,7 @@ def neg(self): Output tensor """ return self.no_params_func("neg", return_response=True) - + def neg_(self): """ Sets negative of the elements of tensor inplace. @@ -407,7 +431,7 @@ def reciprocal(self): Output Tensor """ return self.no_params_func("reciprocal", return_response=True) - + def reciprocal_(self): """ Computes reciprocal of input tensor with values inplace. @@ -419,7 +443,7 @@ def reciprocal_(self): Caller with values inplace """ return self.no_params_func("reciprocal_") - + def trace(self): """ Returns a new tensor with the sum along diagonals of a 2D tensor. @@ -441,7 +465,7 @@ def sin(self): Output Tensor """ return self.no_params_func("sin", return_response=True, return_type='FloatTensor'); - + def __repr__(self, verbose=True): tensor_str = str(self.to_numpy())
Implement the Eq function for IntTensor on the CPU As a Data Scientist using PySyft's IntTensor type, I want to leverage a wide range of methods which use our new Unity backend. For this ticket to be complete, the eq() should be added to our IntTensor class with the appropriate functionality, returning a new tensor. If you want to take it to the next level, boost it implementing the operation on the GPU: Search for an issue titled like this but with "on the GPU" on the title! HLSL (GPU language) tutorial here: [Direct Compute Programming Guide](https://github.com/OpenMined/OpenMined/blob/master/tutorials/DirectCompute_Programming_Guide.md) Note, it is possible that when you look in the code you'll find that parts of this issue were completed on the backend while implementing another issue. This is normal as features do not live in isolation. If this is the case, just take it as a convenience that someone already built that part and press on! ### Every Reference You Might Need for this Issue: - For a reference on the operation this performs check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation. - For a reference on how to program in Unity, check out [this basic tutorial](https://unity3d.com/learn/tutorials/projects/roll-ball-tutorial) - For a reference on how to write HLSL code, check out [this basic tutorial](http://kylehalladay.com/blog/tutorial/2014/06/27/Compute-Shaders-Are-Nifty.html) - For a complete tutorial on how to add functions to FloatTensor (step by step guide) see [this Google Document](https://docs.google.com/document/d/1WRd7gGLFN0Awtf86AICYIHtg3gfFWLBa5wYTthsB3i0/edit) - For a reference on how other functions like this have been implemented check out the functions in [this notebook](https://github.com/OpenMined/OpenMined/blob/master/notebooks/Syft%20Tensor%20Example%20Notebook.ipynb) as well as the corresponding files that made it possible ([SyftController](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined/Network/Controllers/SyftController.cs), [FloatTensor.Ops](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined/Syft/Tensor/FloatTensor.Ops.cs), [FloatTensorShaders](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined/Syft/Tensor/Ops/Shaders/FloatTensorShaders.compute), [TensorOpsShaders](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined/Syft/Tensor/Ops/Shaders/TensorOpsShaders.compute), [FloatTensorTest](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined.Tests/Editor/FloatTensor/FloatTensorTest.cs) and [FloatTensorGpuTest](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined.Tests/Editor/FloatTensor/FloatTensorGpuTest.cs)). - And of course, please consider our [Contributor Guidelines](https://github.com/OpenMined/Docs/blob/master/contributing/guidelines.md) for all contributions. ### Acceptance Criteria: - [ ] comment below that you're picking up this project - [ ] an example in a notebook in our [tests folder](https://github.com/OpenMined/OpenMined/tree/master/notebooks/tests) showing how to use the functionality from PySyft - [ ] an integration test in PySyft demonstrating the correct CPU operation implemented over an IntTensor while connected to a Unity backend - [ ] a Unit Test in OpenMined/OpenMined demonstrating the correct operation on a FloatTensor - [ ] [inline](http://pytorch.org/docs/master/tensors.html) documentation in the python code. For inspiration on inline documentation, please check out PyTorch's documentation for this operator. - [ ] Link your Pull Request back to this Issue so that it gets closed appropriately when the PR is merged.
i'll take this up! this will be my first contribution :p -nico
2018-01-18T20:34:25
OpenMined/PySyft
1,317
OpenMined__PySyft-1317
[ "1242" ]
26d89cfc137a29a8ff36048b0ee38a7be0059251
diff --git a/syft/tensor/int_tensor.py b/syft/tensor/int_tensor.py --- a/syft/tensor/int_tensor.py +++ b/syft/tensor/int_tensor.py @@ -222,6 +222,25 @@ def trace(self): """ return self.no_params_func("trace", return_response=True) + def topk(self,k,**kwargs): + """ + Returns a new tesnor with the k largest elements + + Parameters + ---------- + `k`: int + `kwargs`: could be one of the following + `dim`: (int) – the dimension to sort along (-1 default) + `largest`: (bool) - controls whether to return largest or smallest elements + `sorted`: (bool) - controls whether to return the elements in sorted order (True default) + + Returns + ------- + IntTensor + Output tensor + """ + return self.params_func('top_k',[k,kwargs.get('dim',-1),kwargs.get('largest',True),kwargs.get('sorted',True)],return_response=True) + def sin(self): """ Computes sin of each element of the tensor.
Implement the Topk function for IntTensor on the CPU As a Data Scientist using PySyft's IntTensor type, I want to leverage a wide range of methods which use our new Unity backend. For this ticket to be complete, the topk() should be added to our IntTensor class with the appropriate functionality, returning a new tensor. If you want to take it to the next level, boost it implementing the operation on the GPU: Search for an issue titled like this but with "on the GPU" on the title! HLSL (GPU language) tutorial here: [Direct Compute Programming Guide](https://github.com/OpenMined/OpenMined/blob/master/tutorials/DirectCompute_Programming_Guide.md) Note, it is possible that when you look in the code you'll find that parts of this issue were completed on the backend while implementing another issue. This is normal as features do not live in isolation. If this is the case, just take it as a convenience that someone already built that part and press on! ### Every Reference You Might Need for this Issue: - For a reference on the operation this performs check out [PyTorch](http://pytorch.org/docs/master/tensors.html)'s documentation. - For a reference on how to program in Unity, check out [this basic tutorial](https://unity3d.com/learn/tutorials/projects/roll-ball-tutorial) - For a reference on how to write HLSL code, check out [this basic tutorial](http://kylehalladay.com/blog/tutorial/2014/06/27/Compute-Shaders-Are-Nifty.html) - For a complete tutorial on how to add functions to FloatTensor (step by step guide) see [this Google Document](https://docs.google.com/document/d/1WRd7gGLFN0Awtf86AICYIHtg3gfFWLBa5wYTthsB3i0/edit) - For a reference on how other functions like this have been implemented check out the functions in [this notebook](https://github.com/OpenMined/OpenMined/blob/master/notebooks/Syft%20Tensor%20Example%20Notebook.ipynb) as well as the corresponding files that made it possible ([SyftController](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined/Network/Controllers/SyftController.cs), [FloatTensor.Ops](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined/Syft/Tensor/FloatTensor.Ops.cs), [FloatTensorShaders](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined/Syft/Tensor/Ops/Shaders/FloatTensorShaders.compute), [TensorOpsShaders](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined/Syft/Tensor/Ops/Shaders/TensorOpsShaders.compute), [FloatTensorTest](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined.Tests/Editor/FloatTensor/FloatTensorTest.cs) and [FloatTensorGpuTest](https://github.com/OpenMined/OpenMined/blob/master/UnityProject/Assets/OpenMined.Tests/Editor/FloatTensor/FloatTensorGpuTest.cs)). - And of course, please consider our [Contributor Guidelines](https://github.com/OpenMined/Docs/blob/master/contributing/guidelines.md) for all contributions. ### Acceptance Criteria: - [ ] comment below that you're picking up this project - [ ] an example in a notebook in our [tests folder](https://github.com/OpenMined/OpenMined/tree/master/notebooks/tests) showing how to use the functionality from PySyft - [ ] an integration test in PySyft demonstrating the correct CPU operation implemented over an IntTensor while connected to a Unity backend - [ ] a Unit Test in OpenMined/OpenMined demonstrating the correct operation on a FloatTensor - [ ] [inline](http://pytorch.org/docs/master/tensors.html) documentation in the python code. For inspiration on inline documentation, please check out PyTorch's documentation for this operator. - [ ] Link your Pull Request back to this Issue so that it gets closed appropriately when the PR is merged.
I am working on it
2018-02-05T17:59:21