├── dcnmt.png
├── visual
├── README.md
├── plot_curve.py
└── embedding.py
├── preprocess
├── shuffle_data.py
└── create_vocab.py
├── README.md
├── testing.py
├── configurations.py
├── train.sh
├── configurations_template.py
├── checkpoint.py
├── training.py
├── stream.py
├── sampling.py
├── model.py
└── LICENSE
/dcnmt.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/SwordYork/DCNMT/HEAD/dcnmt.png
--------------------------------------------------------------------------------
/visual/README.md:
--------------------------------------------------------------------------------
1 | `plot_curve.py` will plot the learning curve, you should copy `plot_curve.py` to `dcnmt_*` folder which contains the `cost_curve.npz` file.
2 |
3 | `embedding.py` will visualize the embedding of words by t-SNE, you should copy this file to parent folder, and create a `wordlist` file (one word per line).
4 |
--------------------------------------------------------------------------------
/visual/plot_curve.py:
--------------------------------------------------------------------------------
1 | import numpy
2 | import matplotlib.pyplot as plt
3 |
4 | def smooth(x,window_len=11,window='hanning'):
5 |
6 | if x.ndim != 1:
7 | raise ValueError("smooth only accepts 1 dimension arrays.")
8 |
9 | if x.size < window_len:
10 | raise ValueError("Input vector needs to be bigger than window size.")
11 |
12 | if window_len<3:
13 | return x
14 |
15 | if not window in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']:
16 | raise ValueError("Window is on of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'")
17 |
18 | s=numpy.r_[x[window_len-1:0:-1],x,x[-1:-window_len:-1]]
19 | if window == 'flat': #moving average
20 | w=numpy.ones(window_len,'d')
21 | else:
22 | w=eval('numpy.'+window+'(window_len)')
23 |
24 | y=numpy.convolve(w/w.sum(),s,mode='valid')
25 | return y
26 |
27 |
28 | if __name__ == '__main__':
29 | a = numpy.load('cost_curve.npz')
30 | c_dict = a['cost_curves'].tolist()
31 | vals = numpy.array([list(v.values())[0] for v in c_dict])
32 |
33 | stride = 500
34 |
35 | sv = smooth(vals, stride, 'hamming')[:-stride+1]
36 | plt.plot(vals, 'g', linewidth=0.4)
37 | plt.plot(sv, 'k', linewidth=4)
38 | plt.show()
39 |
--------------------------------------------------------------------------------
/preprocess/shuffle_data.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 |
3 | import logging
4 | import os
5 | import subprocess
6 | import uuid
7 | import sys
8 |
9 | from picklable_itertools.extras import equizip
10 |
11 |
12 | def merge_parallel(src_filename, trg_filename, merged_filename):
13 | total = 0
14 | with open(src_filename, 'r', encoding='utf-8') as left:
15 | with open(trg_filename, 'r', encoding='utf-8') as right:
16 | with open(merged_filename, 'w') as final:
17 | for lline, rline in equizip(left, right):
18 | if (lline != '\n') and (rline != '\n'):
19 | total += 1
20 | final.write(lline[:-1] + ' ||| ' + rline)
21 |
22 |
23 | def split_parallel(merged_filename, src_filename, trg_filename):
24 | total = 0
25 | with open(merged_filename) as combined:
26 | with open(src_filename, 'w') as left:
27 | with open(trg_filename, 'w') as right:
28 | for line in combined:
29 | total += 1
30 | line = line.split('|||')
31 | left.write(line[0].strip() + '\n')
32 | right.write(line[1].strip() + '\n')
33 |
34 |
35 | def shuffle_parallel(src_filename, trg_filename):
36 | logger.info("Shuffling jointly [{}] and [{}]".format(src_filename,
37 | trg_filename))
38 | out_src = src_filename + '.shuf'
39 | out_trg = trg_filename + '.shuf'
40 | merged_filename = str(uuid.uuid4())
41 | shuffled_filename = str(uuid.uuid4())
42 | if not os.path.exists(out_src) or not os.path.exists(out_trg):
43 | try:
44 | merge_parallel(src_filename, trg_filename, merged_filename)
45 | subprocess.check_call(
46 | " shuf {} > {} ".format(merged_filename, shuffled_filename),
47 | shell=True)
48 | split_parallel(shuffled_filename, out_src, out_trg)
49 | logger.info(
50 | "...files shuffled [{}] and [{}]".format(out_src, out_trg))
51 | except Exception as e:
52 | logger.error("{}".format(str(e)))
53 | else:
54 | logger.info("...files exist [{}] and [{}]".format(out_src, out_trg))
55 | if os.path.exists(merged_filename):
56 | os.remove(merged_filename)
57 | if os.path.exists(shuffled_filename):
58 | os.remove(shuffled_filename)
59 |
60 |
61 | if __name__ == "__main__":
62 | logging.basicConfig(level=logging.INFO)
63 | logger = logging.getLogger('shuffle_data')
64 |
65 | if len(sys.argv) != 3:
66 | sys.exit(-1)
67 | # Shuffle datasets
68 | src_file_name = sys.argv[1]
69 | trg_file_name = sys.argv[2]
70 | shuffle_parallel(src_file_name, trg_file_name)
71 |
--------------------------------------------------------------------------------
/preprocess/create_vocab.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | import pickle
4 | import logging
5 | import os
6 | import sys
7 |
8 | from collections import Counter
9 |
10 |
11 | def safe_pickle(obj, filename):
12 | if os.path.isfile(filename):
13 | logger.info("Overwriting %s." % filename)
14 | else:
15 | logger.info("Saving to %s." % filename)
16 | with open(filename, 'wb') as f:
17 | pickle.dump(obj, f, protocol=pickle.HIGHEST_PROTOCOL)
18 |
19 |
20 | def create_dictionary(input_file, dictionary_file, vocab_size):
21 | input_filename = os.path.basename(input_file.name)
22 | logger.info("Counting words in %s" % input_filename)
23 | counter = Counter()
24 | sentence_count = 0
25 | for line in input_file:
26 | words = list(line.strip())
27 | counter.update(words)
28 | sentence_count += 1
29 | logger.info("%d unique words in %d sentences with a total of %d words."
30 | % (len(counter), sentence_count, sum(counter.values())))
31 |
32 | if vocab_size is not None:
33 | if vocab_size <= 3:
34 | logger.info('Building a dictionary with all unique words')
35 | vocab_size = len(counter) + 3
36 | vocab_count = counter.most_common(vocab_size - 3)
37 | logger.info("Creating dictionary of %s most common words, covering "
38 | "%2.1f%% of the text."
39 | % (vocab_size,
40 | 100.0 * sum([count for word, count in vocab_count]) /
41 | sum(counter.values())))
42 | else:
43 | logger.info("Creating dictionary of all words")
44 | vocab_count = counter.most_common()
45 |
46 | vocab = {'UNK': 1, '': 0, '': vocab_size - 1}
47 | for i, (word, count) in enumerate(vocab_count):
48 | vocab[word] = i + 2
49 |
50 | print(counter, vocab_count)
51 | safe_pickle(vocab, dictionary_file)
52 |
53 |
54 | def create_vocabularies(src_file, trg_file, config):
55 | src_vocab_name = 'vocab.{}-{}.{}.pkl'.format(
56 | config['source'], config['target'], config['source'])
57 | trg_vocab_name = 'vocab.{}-{}.{}.pkl'.format(
58 | config['source'], config['target'], config['target'])
59 |
60 | logger.info("Creating source vocabulary [{}]".format(src_vocab_name))
61 | if not os.path.exists(src_vocab_name):
62 | create_dictionary(open(src_file, 'r', encoding='utf-8'), src_vocab_name, config['src_vocab_size'])
63 | else:
64 | logger.info("...file exists [{}]".format(src_vocab_name))
65 |
66 | logger.info("Creating target vocabulary [{}]".format(trg_vocab_name))
67 | if not os.path.exists(trg_vocab_name):
68 | create_dictionary(open(trg_file, 'r', encoding='utf-8'), trg_vocab_name, config['trg_vocab_size'])
69 | else:
70 | logger.info("...file exists [{}]".format(trg_vocab_name))
71 |
72 |
73 | if __name__ == "__main__":
74 | logging.basicConfig(level=logging.INFO)
75 | logger = logging.getLogger('create_vocab')
76 | if len(sys.argv) != 7:
77 | sys.exit(-1)
78 |
79 | configs = {'source': sys.argv[1], 'target': sys.argv[2], 'src_vocab_size': int(sys.argv[3]), 'trg_vocab_size': int(sys.argv[4])}
80 | src_file_name = sys.argv[5]
81 | trg_file_name = sys.argv[6]
82 | create_vocabularies(src_file_name, trg_file_name, configs)
83 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | Deep Character-Level Neural Machine Translation
2 | ============
3 | We implement a [**Deep Character-Level Neural Machine Translation**](https://arxiv.org/abs/1608.04738) based on [Theano](https://github.com/Theano/Theano) and [Blocks](https://github.com/mila-udem/blocks). Please intall relative packages according to [Blocks](http://blocks.readthedocs.io/en/latest/setup.html) before testing our program. Note that, please use Python 3 instead of Python 2. There will be some problems with Python 2.
4 |
5 | The architecture of DCNMT is shown in the following figure which is a single, large neural network.
6 | 
7 |
8 |
9 |
10 |
11 | Training
12 | -----------------------
13 | If you want to train your own model, please prepare a parallel linguistics corpus, like corpus in [WMT](http://www.statmt.org/wmt15/translation-task.html). A GPU with 12GB memory will be helpful. You could run `bash train.sh` or follow these steps.
14 | 1. Download the relative scripts (tokenizer.perl, multi-bleu.perl) and nonbreaking_prefix from [mose_git](https://raw.githubusercontent.com/moses-smt/mosesdecoder/master/scripts).
15 | 2. Download the datasets, then tokenize and shuffle the cropus.
16 | 3. Create the character list for both language using `create_vocab.py` in `preprocess` folder. Don't forget to pass the language setting, vocabulary size and file name to this script.
17 | 4. Create a `data` folder, and put the `vocab.*.*.pkl` and `*.shuf` in the `data` folder.
18 | 5. Prepare the tokenized validation and test set, and put them in `data` folder.
19 | 6. Edit the `configurations.py`, and run `python training.py`. It will take 1 to 2 weeks to train a good model.
20 |
21 |
22 | Testing
23 | -----------------------
24 | We have trained several models which listed in the following table. However, because of the limitation of available GPU and long training time (two weeks or more), we don't have enough time and resource to train on more language pairs. Would you like to help us to train on more language pairs? If you run into any trouble, please open an issue or email me directly at `echo c3dvcmQueW9ya0BnbWFpbC5jb20K | base64 -d`. Thanks!
25 |
26 |
27 | | language pair | dataset | encoder_layers | transition_layers | BLEU |
28 | |:--------:|:--------:|:--------:|:--------:|:--------:|
29 | | en-fr | same as [RNNsearch](https://arxiv.org/abs/1409.0473) | 1 | 1 | 30.46 |
30 | | en-fr | same as [RNNsearch](https://arxiv.org/abs/1409.0473) | 2 | 1 | 31.98 |
31 | | en-fr | same as [RNNsearch](https://arxiv.org/abs/1409.0473) | 2 | 2 | 32.12 |
32 | | en-cs | [wmt15](http://www.statmt.org/wmt15/translation-task.html) | 1 | 1 | 16.43 |
33 |
34 |
35 | These models are all trained for about 5 epochs, and evaluate on `newstest2014` using the best validation model on `newstest2013`. You can download these models from [dropbox](https://www.dropbox.com/sh/eiaexn8q2sf277s/AADQ4RKWEsCIGkeKUUyMHh2aa?dl=0), then put them (dcnmt_\*, data, configurations.py) in this directory. To perform testing, just run `python testing.py`. It takes about an hour to do translation on 3000 sentences if you have a moderate GPU.
36 |
37 |
38 | Embedding
39 | -----------------------
40 | Please prepare a wordlist to calculate embedding, then just run `python embedding.py` to view the results.
41 |
42 | Spelling Correction
43 | -----------------------
44 | It is the special feature of DCNMT model. For example,
45 |
46 | > *Source:* Unlike in Canada, the American States are **responisble** for the **orgainisation** of federal elections in the United States.
47 |
48 | > *Ref:* Contrairement au Canada, les États américains sont **responsables** de **l’organisation** des élections fédérales aux États-Unis.
49 |
50 | > *Google:* Contrairement au Canada, les États américains sont **responisble** pour le **orgainisation** des élections fédérales aux États-Unis.
51 |
52 | > *DCNMT:* Contrairement au Canada, les États américains sont **responsables** de **l’organisation** des élections fédérales aux États-Unis.
53 |
54 | The performance of misspelling correction would be analyzed later.
55 |
56 |
57 |
58 | This program have been tested under the latest Theano and Blocks, it may fail to run because of different version. If you failed to run these scripts, please make sure that you can run the examples of [Blocks](https://github.com/mila-udem/blocks-examples).
59 |
60 |
61 | References:
62 | ----------------------
63 | 1. [An Efficient Character-Level Neural Machine Translation](https://arxiv.org/abs/1608.04738)
64 | 2. [Neural Machine Translation by Jointly Learning to Align and Translate](https://arxiv.org/abs/1409.0473)
65 |
--------------------------------------------------------------------------------
/testing.py:
--------------------------------------------------------------------------------
1 | from theano import tensor
2 |
3 | from blocks.filter import VariableFilter
4 | from blocks.graph import ComputationGraph
5 | from blocks.main_loop import MainLoop
6 | from blocks.model import Model
7 |
8 | from checkpoint import LoadNMT
9 | from model import BidirectionalEncoder, Decoder
10 | from sampling import BleuTester
11 | import logging
12 | import pprint
13 |
14 | import configurations
15 | from stream import get_test_stream
16 |
17 | logger = logging.getLogger(__name__)
18 |
19 |
20 | def main(config, test_stream):
21 | # Create Theano variables
22 | logger.info('Creating theano variables')
23 | source_char_seq = tensor.lmatrix('source_char_seq')
24 | source_sample_matrix = tensor.tensor3('source_sample_matrix')
25 | source_char_aux = tensor.matrix('source_char_aux')
26 | source_word_mask = tensor.matrix('source_word_mask')
27 | target_char_seq = tensor.lmatrix('target_char_seq')
28 | target_char_aux = tensor.matrix('target_char_aux')
29 | target_char_mask = tensor.matrix('target_char_mask')
30 | target_sample_matrix = tensor.tensor3('target_sample_matrix')
31 | target_word_mask = tensor.matrix('target_word_mask')
32 | target_resample_matrix = tensor.tensor3('target_resample_matrix')
33 | target_prev_char_seq = tensor.lmatrix('target_prev_char_seq')
34 | target_prev_char_aux = tensor.matrix('target_prev_char_aux')
35 |
36 | target_bos_idx = test_stream.trg_bos
37 | target_space_idx = test_stream.space_idx['target']
38 |
39 | # Construct model
40 | logger.info('Building RNN encoder-decoder')
41 |
42 | encoder = BidirectionalEncoder(config['src_vocab_size'], config['enc_embed'], config['src_dgru_nhids'],
43 | config['enc_nhids'], config['src_dgru_depth'], config['bidir_encoder_depth'])
44 |
45 | decoder = Decoder(config['trg_vocab_size'], config['dec_embed'], config['trg_dgru_nhids'], config['trg_igru_nhids'],
46 | config['dec_nhids'], config['enc_nhids'] * 2, config['transition_depth'], config['trg_igru_depth'],
47 | config['trg_dgru_depth'], target_space_idx, target_bos_idx)
48 |
49 |
50 | representation = encoder.apply(source_char_seq, source_sample_matrix, source_char_aux,
51 | source_word_mask)
52 | cost = decoder.cost(representation, source_word_mask, target_char_seq, target_sample_matrix,
53 | target_resample_matrix, target_char_aux, target_char_mask,
54 | target_word_mask, target_prev_char_seq, target_prev_char_aux)
55 |
56 | # Set up training model
57 | logger.info("Building model")
58 | training_model = Model(cost)
59 |
60 | # Set extensions
61 | logger.info("Initializing extensions")
62 | # Extensions
63 | extensions = []
64 | # Reload model if necessary
65 | if config['reload']:
66 | extensions.append(LoadNMT(config['saveto']))
67 |
68 | # Set up beam search and sampling computation graphs if necessary
69 | if config['bleu_script'] is not None:
70 | logger.info("Building sampling model")
71 | generated = decoder.generate(representation, source_word_mask)
72 | search_model = Model(generated)
73 | _, samples = VariableFilter(
74 | bricks=[decoder.sequence_generator], name="outputs")(
75 | ComputationGraph(generated[config['transition_depth']])) # generated[config['transition_depth']] is next_outputs
76 |
77 | logger.info("Building bleu tester")
78 | extensions.append(
79 | BleuTester(source_char_seq, source_sample_matrix, source_char_aux,
80 | source_word_mask, samples=samples, config=config,
81 | model=search_model, data_stream=test_stream,
82 | normalize=config['normalized_bleu']))
83 |
84 | # Initialize main loop
85 | logger.info("Initializing main loop")
86 | main_loop = MainLoop(
87 | model=training_model,
88 | algorithm=None,
89 | data_stream=None,
90 | extensions=extensions
91 | )
92 |
93 | for extension in main_loop.extensions:
94 | extension.main_loop = main_loop
95 | main_loop._run_extensions('before_training')
96 |
97 |
98 | logger = logging.getLogger(__name__)
99 | logging.basicConfig(level=logging.INFO)
100 |
101 | if __name__ == '__main__':
102 | # Get configurations for model
103 | configuration = configurations.get_config()
104 | logger.info("Model options:\n{}".format(pprint.pformat(configuration)))
105 | # Get data streams and call main
106 | main(configuration, get_test_stream(**configuration))
107 |
108 |
109 |
--------------------------------------------------------------------------------
/configurations.py:
--------------------------------------------------------------------------------
1 | def get_config():
2 | config = {}
3 | # Where to save model, this corresponds to 'prefix' in groundhog
4 | config['saveto'] = 'dcnmt_en2fr'
5 |
6 | # prepare data
7 | config['source_language'] = 'en'
8 | config['target_language'] = 'fr'
9 |
10 | # Model related -----------------------------------------------------------
11 |
12 | # Sequences longer than this will be discarded
13 | config['max_src_seq_char_len'] = 300
14 | config['max_src_seq_word_len'] = 50
15 | config['max_trg_seq_char_len'] = 300
16 | config['max_trg_seq_word_len'] = 50
17 |
18 | # Number of hidden units in encoder/decoder GRU
19 | config['src_dgru_nhids'] = 512
20 | config['enc_nhids'] = 1024
21 | config['dec_nhids'] = 1024
22 | config['trg_dgru_nhids'] = 512
23 | config['trg_igru_nhids'] = 1024
24 |
25 |
26 | # Dimension of the word embedding matrix in encoder/decoder
27 | config['enc_embed'] = 64
28 | config['dec_embed'] = 64
29 | config['src_dgru_depth'] = 2
30 | config['bidir_encoder_depth'] = 2
31 | config['transition_depth'] = 1
32 | config['trg_dgru_depth'] = 1
33 | config['trg_igru_depth'] = 1
34 |
35 |
36 | # Optimization related ----------------------------------------------------
37 |
38 | # Batch size
39 | config['batch_size'] = 80
40 |
41 | # This many batches will be read ahead and sorted
42 | config['sort_k_batches'] = 12
43 |
44 | # Optimization step rule
45 | config['step_rule'] = 'AdaDelta'
46 |
47 | # Gradient clipping threshold
48 | config['step_clipping'] = 1.
49 |
50 | # Std of weight initialization
51 | config['weight_scale'] = 0.01
52 |
53 | # Vocabulary/dataset related ----------------------------------------------
54 |
55 | # Root directory for dataset
56 | datadir = './data/'
57 |
58 | # Module name of the stream that will be used
59 | config['stream'] = 'stream'
60 |
61 | # Source and target vocabularies
62 | config['src_vocab'] = datadir + 'vocab.{}-{}.{}.pkl'.format(config['source_language'], config['target_language'],
63 | config['source_language'])
64 | config['trg_vocab'] = datadir + 'vocab.{}-{}.{}.pkl'.format(config['source_language'], config['target_language'],
65 | config['target_language'])
66 |
67 | # Source and target datasets
68 | config['src_data'] = datadir + 'all.en-fr.en.tok.shuf'
69 | config['trg_data'] = datadir + 'all.en-fr.fr.tok.shuf'
70 |
71 | # Source and target vocabulary sizes, should include bos, eos, unk tokens
72 | config['src_vocab_size'] = 120
73 | config['trg_vocab_size'] = 120
74 |
75 | # Special tokens and indexes
76 | config['unk_id'] = 1
77 | config['bos_token'] = ''
78 | config['eos_token'] = ''
79 | config['unk_token'] = ''
80 |
81 | # Early stopping based on val related ------------------------------------
82 |
83 | # Normalize cost according to sequence length after beam-search
84 | config['normalized_val'] = True
85 |
86 | # Normalize cost according to sequence length after beam-search
87 | config['normalized_bleu'] = True
88 |
89 | # Bleu script that will be used (moses multi-perl in this case)
90 | config['bleu_script'] = datadir + 'multi-bleu.perl'
91 |
92 | # Validation set source file
93 | config['val_set'] = datadir + 'newstest2013.en.tok'
94 |
95 | # Validation set gold file
96 | config['val_set_grndtruth'] = datadir + 'newstest2013.fr.tok'
97 |
98 | # Test set source file
99 | config['test_set'] = datadir + 'newstest2014.en.tok'
100 |
101 | # Test set gold file
102 | config['test_set_grndtruth'] = datadir + 'newstest2014.fr.tok'
103 |
104 | config['validate'] = True
105 |
106 | # Print validation output to file
107 | config['output_val_set'] = True
108 |
109 | # Validation output file
110 | config['val_set_out'] = config['saveto'] + '/validation_out.txt'
111 |
112 | # Validation output file
113 | config['test_set_out'] = config['saveto'] + '/test_out.txt'
114 |
115 | # Beam-size
116 | config['beam_size'] = 12
117 |
118 | # Timing/monitoring related -----------------------------------------------
119 |
120 | # Maximum number of updates
121 | config['finish_after'] = 432000
122 |
123 | # Reload model from files if exist
124 | config['reload'] = True
125 |
126 | # Save model after this many updates
127 | config['save_freq'] = 500
128 |
129 | # Print training status after this many updates
130 | config['print_freq'] = 10
131 |
132 | # Show samples from model after this many updates
133 | config['sampling_freq'] = 30
134 |
135 | # Show this many samples at each sampling
136 | config['hook_samples'] = 2
137 |
138 | config['bleu_val_freq'] = 18000
139 | # Start validation after this many updates
140 | config['val_burn_in'] = 70000
141 |
142 | return config
143 |
--------------------------------------------------------------------------------
/train.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | # The repository of moses, we need to download some scripts from moses.
4 | # https://github.com/moses-smt/mosesdecoder/tree/master/scripts
5 | mose_git=https://raw.githubusercontent.com/moses-smt/mosesdecoder/master/scripts
6 |
7 | echo 'select the source language: en, cs, fi, fr, ru, de'
8 | read -p '==> ' source_language
9 | echo "the selected source language is $source_language"
10 |
11 |
12 | echo 'select the target language: en, cs, fi, fr, ru, de'
13 | read -p '==> ' target_language
14 | echo "the selected target language is $target_language"
15 |
16 | if [ $target_language = $source_language ]; then
17 | echo 'languages should be different'
18 | exit -1
19 | fi
20 |
21 | if [ ! -d share/nonbreaking_prefixes ]; then
22 | mkdir -p share/nonbreaking_prefixes
23 | fi
24 |
25 | echo "downloading nonbreaking_prefix $source_language ..."
26 | curl -s $mose_git/share/nonbreaking_prefixes/nonbreaking_prefix.$source_language > share/nonbreaking_prefixes/nonbreaking_prefix.$source_language
27 | echo "downloading nonbreaking_prefix $target_language ..."
28 | curl -s $mose_git/share/nonbreaking_prefixes/nonbreaking_prefix.$target_language > share/nonbreaking_prefixes/nonbreaking_prefix.$target_language
29 |
30 | if [ ! -d data ]; then
31 | echo 'creating data directory...'
32 | mkdir data
33 | fi
34 |
35 |
36 |
37 | cp preprocess/create_vocab.py preprocess/shuffle_data.py data/
38 |
39 | echo 'cd to data directory'
40 | cd data
41 | if [ ! -f tokenizer.perl ]; then
42 | echo 'downloading tokenizer.perl'
43 | curl -s $mose_git/tokenizer/tokenizer.perl > tokenizer.perl
44 | fi
45 | if [ ! -f multi-bleu.perl ]; then
46 | echo 'downloading multi-bleu.perl'
47 | curl -s $mose_git/generic/multi-bleu.perl > multi-bleu.perl
48 | fi
49 |
50 | echo 'please download corresponding datasets from WMT15 manually'
51 | echo 'and put the parallel corpus in the data directory'
52 | echo 'then enter the file name of source language dataset'
53 | read -p '==> ' source_data
54 | echo 'the file name of target language dataset'
55 | read -p '==> ' target_data
56 |
57 | if [ ! -f $source_data ]; then
58 | echo 'no such source dataset file'
59 | exit -1
60 | fi
61 |
62 | if [ ! -f $target_data ]; then
63 | echo 'no such target dataset file'
64 | exit -1
65 | fi
66 |
67 | tok_source_file=all.$source_language-$target_language.$source_language.tok
68 | tok_target_file=all.$source_language-$target_language.$target_language.tok
69 |
70 | perl tokenizer.perl -l $source_language -threads 4 -no-escape < $source_data > $tok_source_file
71 | perl tokenizer.perl -l $target_language -threads 4 -no-escape < $target_data > $tok_target_file
72 |
73 | echo 'please put the validation and test dataset in the data directory'
74 | echo 'the file name of source validation set:'
75 | read -p '==>' src_val
76 | echo 'the file name of target validation set:'
77 | read -p '==>' trg_val
78 | echo 'the file name of source test set:'
79 | read -p '==>' src_test
80 | echo 'the file name of targe test set:'
81 | read -p '==>' trg_test
82 |
83 | if [ ! -f $src_val ]; then
84 | echo 'no such source validation file'
85 | exit -1
86 | fi
87 |
88 | if [ ! -f $trg_val ]; then
89 | echo 'no such target validation file'
90 | exit -1
91 | fi
92 |
93 | if [ ! -f $src_test ]; then
94 | echo 'no such source test file'
95 | exit -1
96 | fi
97 |
98 | if [ ! -f $trg_test ]; then
99 | echo 'no such target test file'
100 | exit -1
101 | fi
102 |
103 | perl tokenizer.perl -l $source_language -threads 4 -no-escape < $src_val > $src_val.tok
104 | perl tokenizer.perl -l $source_language -threads 4 -no-escape < $src_test > $src_test.tok
105 | perl tokenizer.perl -l $target_language -threads 4 -no-escape < $trg_val > $trg_val.tok
106 | perl tokenizer.perl -l $target_language -threads 4 -no-escape < $trg_test > $trg_test.tok
107 |
108 |
109 | echo 'please ensure there is enough disk space'
110 | python shuffle_data.py $tok_source_file $tok_target_file
111 |
112 | echo 'please enter the size of source language vocabulary (120 is enough):'
113 | read -p '==>' src_vocab_size
114 | echo 'please enter the size of target language vocabulary (120 is enough):'
115 | read -p '==>' trg_vocab_size
116 | python create_vocab.py $source_language $target_language $src_vocab_size $trg_vocab_size $tok_source_file.shuf $tok_target_file.shuf
117 |
118 | cd ..
119 | if [ -f configurations.py ]; then
120 | cp configurations.py configurations_backup.py
121 | fi
122 |
123 | cp configurations_template.py configurations.py
124 |
125 | sed -i "s/--src_lang--/$source_language/" configurations.py
126 | sed -i "s/--trg_lang--/$target_language/" configurations.py
127 | sed -i "s/--src_vocab_size--/$src_vocab_size/" configurations.py
128 | sed -i "s/--trg_vocab_size--/$trg_vocab_size/" configurations.py
129 | sed -i "s/--src_val--/$src_val/" configurations.py
130 | sed -i "s/--trg_val--/$trg_val/" configurations.py
131 | sed -i "s/--src_test--/$src_test/" configurations.py
132 | sed -i "s/--trg_test--/$trg_test/" configurations.py
133 |
134 | echo "ok! just run 'python training.py'"
135 |
136 |
137 |
138 |
139 |
--------------------------------------------------------------------------------
/configurations_template.py:
--------------------------------------------------------------------------------
1 | def get_config():
2 | config = {}
3 |
4 | # prepare data
5 | config['source_language'] = '--src_lang--'
6 | config['target_language'] = '--trg_lang--'
7 |
8 |
9 | # Where to save model, this corresponds to 'prefix' in groundhog
10 | config['saveto'] = 'dcnmt_{}2{}'.format(config['source_language'], config['target_language'])
11 |
12 | # Model related -----------------------------------------------------------
13 |
14 | # Sequences longer than this will be discarded
15 | config['max_src_seq_char_len'] = 300
16 | config['max_src_seq_word_len'] = 50
17 | config['max_trg_seq_char_len'] = 300
18 | config['max_trg_seq_word_len'] = 50
19 |
20 | # Number of hidden units in encoder/decoder GRU
21 | config['src_dgru_nhids'] = 512
22 | config['enc_nhids'] = 1024
23 | config['dec_nhids'] = 1024
24 | config['trg_dgru_nhids'] = 512
25 | config['trg_igru_nhids'] = 1024
26 |
27 |
28 | # Dimension of the word embedding matrix in encoder/decoder
29 | config['enc_embed'] = 64
30 | config['dec_embed'] = 64
31 | config['src_dgru_depth'] = 2
32 | config['bidir_encoder_depth'] = 2
33 | config['transition_depth'] = 1
34 | config['trg_dgru_depth'] = 1
35 | config['trg_igru_depth'] = 1
36 |
37 | # Optimization related ----------------------------------------------------
38 |
39 | # Batch size
40 | config['batch_size'] = 80
41 |
42 | # This many batches will be read ahead and sorted
43 | config['sort_k_batches'] = 12
44 |
45 | # Optimization step rule
46 | config['step_rule'] = 'AdaDelta'
47 |
48 | # Gradient clipping threshold
49 | config['step_clipping'] = 1.
50 |
51 | # Std of weight initialization
52 | config['weight_scale'] = 0.01
53 |
54 |
55 | # Vocabulary/dataset related ----------------------------------------------
56 |
57 | # Root directory for dataset
58 | datadir = './data/'
59 |
60 | # Module name of the stream that will be used
61 | config['stream'] = 'stream'
62 |
63 | # Source and target vocabularies
64 | config['src_vocab'] = datadir + 'vocab.{}-{}.{}.pkl'.format(config['source_language'], config['target_language'],
65 | config['source_language'])
66 | config['trg_vocab'] = datadir + 'vocab.{}-{}.{}.pkl'.format(config['source_language'], config['target_language'],
67 | config['target_language'])
68 |
69 | # Source and target datasets
70 | config['src_data'] = datadir + 'all.{}-{}.{}.tok.shuf'.format(config['source_language'], config['target_language'],
71 | config['source_language'])
72 | config['trg_data'] = datadir + 'all.{}-{}.{}.tok.shuf'.format(config['source_language'], config['target_language'],
73 | config['target_language'])
74 |
75 | # Source and target vocabulary sizes, should include bos, eos, unk tokens
76 | config['src_vocab_size'] = --src_vocab_size--
77 | config['trg_vocab_size'] = --trg_vocab_size--
78 |
79 | # Special tokens and indexes
80 | config['unk_id'] = 1
81 | config['bos_token'] = ''
82 | config['eos_token'] = ''
83 | config['unk_token'] = ''
84 |
85 | # Early stopping based on val related ------------------------------------
86 |
87 | # Normalize cost according to sequence length after beam-search
88 | config['normalized_val'] = True
89 |
90 | # Normalize cost according to sequence length after beam-search
91 | config['normalized_bleu'] = True
92 |
93 | # Bleu script that will be used (moses multi-perl in this case)
94 | config['bleu_script'] = datadir + 'multi-bleu.perl'
95 |
96 | # Validation set source file
97 | config['val_set'] = datadir + '--src_val--.tok'
98 |
99 | # Validation set gold file
100 | config['val_set_grndtruth'] = datadir + '--trg_val--.tok'
101 |
102 | # Test set source file
103 | config['test_set'] = datadir + '--src_test--.tok'
104 |
105 | # Test set gold file
106 | config['test_set_grndtruth'] = datadir + '--trg_test--.tok'
107 |
108 | config['validate'] = True
109 |
110 | # Print validation output to file
111 | config['output_val_set'] = True
112 |
113 | # Validation output file
114 | config['val_set_out'] = config['saveto'] + '/validation_out.txt'
115 |
116 | # Validation output file
117 | config['test_set_out'] = config['saveto'] + '/test_out.txt'
118 |
119 | # Beam-size
120 | config['beam_size'] = 12
121 |
122 | # Timing/monitoring related -----------------------------------------------
123 |
124 | # Maximum number of updates
125 | config['finish_after'] = 800000
126 |
127 | # Reload model from files if exist
128 | config['reload'] = True
129 |
130 | # Save model after this many updates
131 | config['save_freq'] = 500
132 |
133 | # Print training status after this many updates
134 | config['print_freq'] = 10
135 |
136 | # Show samples from model after this many updates
137 | config['sampling_freq'] = 30
138 |
139 | # Show this many samples at each sampling
140 | config['hook_samples'] = 2
141 |
142 | config['bleu_val_freq'] = 18000
143 | # Start validation after this many updates
144 | config['val_burn_in'] = 70000
145 |
146 | return config
147 |
--------------------------------------------------------------------------------
/checkpoint.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import numpy
3 | import os
4 | import time
5 |
6 | from contextlib import closing
7 | from six.moves import cPickle
8 |
9 | from blocks.extensions.saveload import SAVED_TO, LOADED_FROM
10 | from blocks.extensions import TrainingExtension, SimpleExtension
11 | from blocks.serialization import secure_dump, load, BRICK_DELIMITER
12 | from blocks.utils import reraise_as
13 |
14 | logger = logging.getLogger(__name__)
15 |
16 |
17 | class SaveLoadUtils(object):
18 | """Utility class for checkpointing."""
19 |
20 | @property
21 | def path_to_folder(self):
22 | return self.folder
23 |
24 | @property
25 | def path_to_parameters(self):
26 | return os.path.join(self.folder, 'params.npz')
27 |
28 | @property
29 | def path_to_iteration_state(self):
30 | return os.path.join(self.folder, 'iterations_state.pkl')
31 |
32 | @property
33 | def path_to_log(self):
34 | return os.path.join(self.folder, 'log')
35 |
36 | def load_parameter_values(self, path):
37 | with closing(numpy.load(path)) as source:
38 | param_values = {}
39 | for name, value in source.items():
40 | if name != 'pkl':
41 | name_ = name.replace(BRICK_DELIMITER, '/')
42 | if not name_.startswith('/'):
43 | name_ = '/' + name_
44 | param_values[name_] = value
45 | return param_values
46 |
47 | def save_parameter_values(self, param_values, path):
48 | param_values = {name.replace("/", BRICK_DELIMITER): param
49 | for name, param in param_values.items()}
50 | numpy.savez(path, **param_values)
51 |
52 |
53 | class CheckpointNMT(SimpleExtension, SaveLoadUtils):
54 | """Redefines checkpointing for NMT.
55 |
56 | Saves only parameters (npz), iteration state (pickle) and log (pickle).
57 |
58 | """
59 |
60 | def __init__(self, saveto, **kwargs):
61 | self.folder = saveto
62 | kwargs.setdefault("after_training", True)
63 | super(CheckpointNMT, self).__init__(**kwargs)
64 |
65 | def dump_parameters(self, main_loop):
66 | params_to_save = main_loop.model.get_parameter_values()
67 | self.save_parameter_values(params_to_save,
68 | self.path_to_parameters)
69 |
70 | def dump_iteration_state(self, main_loop):
71 | secure_dump(main_loop.iteration_state, self.path_to_iteration_state)
72 |
73 | def dump_log(self, main_loop):
74 | secure_dump(main_loop.log, self.path_to_log, cPickle.dump)
75 |
76 | def dump(self, main_loop):
77 | if not os.path.exists(self.path_to_folder):
78 | os.mkdir(self.path_to_folder)
79 | print("")
80 | logger.info(" Saving model")
81 | start = time.time()
82 | logger.info(" ...saving parameters")
83 | self.dump_parameters(main_loop)
84 | logger.info(" ...saving iteration state")
85 | self.dump_iteration_state(main_loop)
86 | logger.info(" ...saving log")
87 | self.dump_log(main_loop)
88 | logger.info(" Model saved, took {} seconds.".format(time.time()-start))
89 |
90 | def do(self, callback_name, *args):
91 | try:
92 | self.dump(self.main_loop)
93 | except Exception:
94 | raise
95 | finally:
96 | already_saved_to = self.main_loop.log.current_row.get(SAVED_TO, ())
97 | self.main_loop.log.current_row[SAVED_TO] = (already_saved_to +
98 | (self.path_to_folder +
99 | 'params.npz',))
100 |
101 |
102 | class LoadNMT(TrainingExtension, SaveLoadUtils):
103 | """Loads parameters log and iterations state."""
104 |
105 | def __init__(self, saveto, **kwargs):
106 | self.folder = saveto
107 | super(LoadNMT, self).__init__(saveto, **kwargs)
108 |
109 | def before_training(self):
110 | if not os.path.exists(self.path_to_folder):
111 | logger.info("No dump found")
112 | return
113 | logger.info("Loading the state from {} into the main loop"
114 | .format(self.path_to_folder))
115 | try:
116 | self.load_to(self.main_loop)
117 | self.main_loop.log.current_row[LOADED_FROM] = self.path_to_folder
118 | except Exception:
119 | reraise_as("Failed to load the state")
120 |
121 | def load_parameters(self):
122 | return self.load_parameter_values(self.path_to_parameters)
123 |
124 | def load_iteration_state(self):
125 | with open(self.path_to_iteration_state, "rb") as source:
126 | return load(source, use_cpickle=True)
127 |
128 | def load_log(self):
129 | with open(self.path_to_log, "rb") as source:
130 | return cPickle.load(source)
131 |
132 | def load_to(self, main_loop):
133 | """Loads the dump from the root folder into the main loop."""
134 | logger.info(" Reloading model")
135 | try:
136 | logger.info(" ...loading model parameters")
137 | params_all = self.load_parameters()
138 | params_this = main_loop.model.get_parameter_dict()
139 | missing = set(params_this.keys()) - set(params_all.keys())
140 | for pname in params_this.keys():
141 | if pname in params_all:
142 | val = params_all[pname]
143 | if params_this[pname].get_value().shape != val.shape:
144 | logger.warning(
145 | " Dimension mismatch {}-{} for {}"
146 | .format(params_this[pname].get_value().shape,
147 | val.shape, pname))
148 |
149 | params_this[pname].set_value(val)
150 | logger.info(" Loaded to CG {:15}: {}"
151 | .format(str(val.shape), pname))
152 | else:
153 | logger.warning(
154 | " Parameter does not exist: {}".format(pname))
155 | logger.info(
156 | " Number of parameters loaded for computation graph: {}"
157 | .format(len(params_this) - len(missing)))
158 | except Exception as e:
159 | logger.error(" Error {0}".format(str(e)))
160 |
161 | try:
162 | logger.info(" Loading iteration state...")
163 | main_loop.iteration_state = self.load_iteration_state()
164 | except Exception as e:
165 | logger.error(" Error {0}".format(str(e)))
166 |
167 | try:
168 | logger.info(" Loading log...")
169 | main_loop.log = self.load_log()
170 | except Exception as e:
171 | logger.error(" Error {0}".format(str(e)))
172 |
--------------------------------------------------------------------------------
/visual/embedding.py:
--------------------------------------------------------------------------------
1 | import pickle
2 | from theano import tensor
3 | from blocks.main_loop import MainLoop
4 | from blocks.model import Model
5 |
6 | from checkpoint import LoadNMT
7 | from model import BidirectionalEncoder, Decoder
8 | from stream import get_tr_stream
9 | import numpy
10 |
11 | import argparse
12 | import logging
13 | import pprint
14 |
15 | import configurations
16 | import matplotlib.pyplot as plt
17 | from sklearn import manifold
18 |
19 | logger = logging.getLogger(__name__)
20 | logging.basicConfig(level=logging.INFO)
21 |
22 |
23 | def build_input_dict(input_, src_vocab):
24 | input_length = len(input_)
25 | input_ = numpy.array([src_vocab[i] for i in input_])
26 |
27 | total_word = list(input_).count(src_vocab[' '])
28 |
29 | source_sample_matrix = numpy.zeros((total_word, input_length), dtype='int8')
30 | source_sample_matrix[range(total_word), numpy.nonzero(input_ == src_vocab[' '])[0] - 1] = 1
31 |
32 | source_char_aux = numpy.ones(input_length, dtype='int8')
33 | source_char_aux[input_ == src_vocab[' ']] = 0
34 |
35 | input_dict = {'source_sample_matrix': source_sample_matrix[None, :],
36 | 'source_char_aux': source_char_aux[None, :],
37 | 'source_char_seq': input_[None, :]}
38 | return input_length, input_dict
39 |
40 |
41 | # Scale and visualize the embedding vectors
42 | def plot_embedding(X, Y, title=None):
43 | x_min, x_max = numpy.min(X, 0), numpy.max(X, 0)
44 | X = (X - x_min) / (x_max - x_min)
45 |
46 | plt.figure()
47 | for i in range(X.shape[0]):
48 | if str(Y[i]) in ['Sunday ', 'March ', 'June ', 'January ', 'February ',
49 | 'April ', 'May ', 'July ', 'August ', 'September ',
50 | 'October ', 'November ', 'December ']:
51 | plt.text(X[i, 0], X[i, 1], str(Y[i]),
52 | fontdict={'weight': 'bold', 'size': 18, 'color': 'blue'})
53 | elif str(Y[i]) != 'exercise ' and str(Y[i]) != 'exrecise ':
54 | plt.text(X[i, 0], X[i, 1], str(Y[i]),
55 | fontdict={'size': 18})
56 | else:
57 | plt.text(X[i, 0], X[i, 1], str(Y[i]),
58 | fontdict={'weight': 'bold', 'size': 18, 'color': 'red'})
59 |
60 | plt.xticks([]), plt.yticks([])
61 | if title is not None:
62 | plt.title(title)
63 |
64 |
65 | def embedding(embedding_model, src_vocab):
66 | sampling_fn = embedding_model.get_theano_function()
67 | try:
68 | f = open('wordlist')
69 | except FileNotFoundError:
70 | print('Please create a file named wordlist, and one word per line in this file')
71 | exit(0)
72 | s = f.read()
73 | core_list = s.strip().split('\n')
74 | f.close()
75 |
76 | X = []
77 | Y = []
78 | for word in core_list:
79 | word += ' '
80 | _, input_dict = build_input_dict(word, src_vocab)
81 | w_v = sampling_fn(**input_dict)[0][0][0]
82 | X.append(w_v)
83 | Y.append(word)
84 | X = numpy.array(X)
85 | print(X.shape)
86 |
87 | # t-SNE embedding of the digits dataset
88 | print("Computing t-SNE embedding")
89 | tsne = manifold.TSNE(n_components=2, init='pca', random_state=0)
90 | X_tsne = tsne.fit_transform(X)
91 |
92 | plot_embedding(X_tsne, Y, "t-SNE embedding of the words")
93 | plt.show()
94 |
95 |
96 | def main(config, tr_stream):
97 | # Create Theano variables
98 | logger.info('Creating theano variables')
99 | source_char_seq = tensor.lmatrix('source_char_seq')
100 | source_sample_matrix = tensor.btensor3('source_sample_matrix')
101 | source_char_aux = tensor.bmatrix('source_char_aux')
102 | source_word_mask = tensor.bmatrix('source_word_mask')
103 | target_char_seq = tensor.lmatrix('target_char_seq')
104 | target_char_aux = tensor.bmatrix('target_char_aux')
105 | target_char_mask = tensor.bmatrix('target_char_mask')
106 | target_sample_matrix = tensor.btensor3('target_sample_matrix')
107 | target_word_mask = tensor.bmatrix('target_word_mask')
108 | target_resample_matrix = tensor.btensor3('target_resample_matrix')
109 | target_prev_char_seq = tensor.lmatrix('target_prev_char_seq')
110 | target_prev_char_aux = tensor.bmatrix('target_prev_char_aux')
111 | target_bos_idx = tr_stream.trg_bos
112 | target_space_idx = tr_stream.space_idx['target']
113 | src_vocab = pickle.load(open(config['src_vocab'], 'rb'))
114 |
115 | logger.info('Building RNN encoder-decoder')
116 | encoder = BidirectionalEncoder(config['src_vocab_size'], config['enc_embed'], config['src_dgru_nhids'],
117 | config['enc_nhids'], config['src_dgru_depth'], config['bidir_encoder_depth'])
118 |
119 | decoder = Decoder(config['trg_vocab_size'], config['dec_embed'], config['trg_dgru_nhids'], config['trg_igru_nhids'],
120 | config['dec_nhids'], config['enc_nhids'] * 2, config['transition_depth'], config['trg_igru_depth'],
121 | config['trg_dgru_depth'], target_space_idx, target_bos_idx)
122 |
123 | representation = encoder.apply(source_char_seq, source_sample_matrix, source_char_aux,
124 | source_word_mask)
125 | cost = decoder.cost(representation, source_word_mask, target_char_seq, target_sample_matrix,
126 | target_resample_matrix, target_char_aux, target_char_mask,
127 | target_word_mask, target_prev_char_seq, target_prev_char_aux)
128 |
129 | # Set up model
130 | logger.info("Building model")
131 | training_model = Model(cost)
132 |
133 | # Set extensions
134 | logger.info("Initializing extensions")
135 | # Reload model if necessary
136 | extensions = [LoadNMT(config['saveto'])]
137 |
138 | # Initialize main loop
139 | logger.info("Initializing main loop")
140 | main_loop = MainLoop(
141 | model=training_model,
142 | algorithm=None,
143 | data_stream=None,
144 | extensions=extensions
145 | )
146 |
147 | for extension in main_loop.extensions:
148 | extension.main_loop = main_loop
149 | main_loop._run_extensions('before_training')
150 |
151 | char_embedding = encoder.decimator.apply(source_char_seq.T, source_sample_matrix, source_char_aux.T)
152 | embedding(Model(char_embedding), src_vocab)
153 |
154 |
155 | logger = logging.getLogger(__name__)
156 | logging.basicConfig(level=logging.INFO)
157 |
158 | # Get the arguments
159 | parser = argparse.ArgumentParser()
160 | parser.add_argument("--proto", default="get_config_en2fr",
161 | help="Prototype config to use for config")
162 | args = parser.parse_args()
163 |
164 | if __name__ == '__main__':
165 | # Get configurations for model
166 | configuration = getattr(configurations, args.proto)()
167 | logger.info("Model options:\n{}".format(pprint.pformat(configuration)))
168 | # Get data streams and call main
169 | main(configuration, get_tr_stream(**configuration))
170 |
--------------------------------------------------------------------------------
/training.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import sys
3 |
4 | from collections import Counter
5 |
6 | from theano import tensor
7 | from toolz import merge
8 |
9 | from blocks.algorithms import (GradientDescent, StepClipping, AdaDelta, CompositeRule)
10 | from blocks.extensions import FinishAfter, Printing, Timing
11 | from blocks.filter import VariableFilter
12 | from blocks.graph import ComputationGraph, apply_noise
13 | from blocks.initialization import IsotropicGaussian, Orthogonal, Constant
14 | from blocks.main_loop import MainLoop
15 | from blocks.model import Model
16 | from blocks.select import Selector
17 |
18 | from blocks.monitoring import aggregation
19 | from checkpoint import CheckpointNMT, LoadNMT
20 | from model import BidirectionalEncoder, Decoder
21 | from sampling import BleuValidator, Sampler, CostCurve
22 |
23 | import pprint
24 |
25 | import configurations
26 | from stream import get_tr_stream, get_dev_stream
27 |
28 | logger = logging.getLogger(__name__)
29 | logging.basicConfig(level=logging.INFO)
30 |
31 |
32 | def main(config, tr_stream, dev_stream):
33 | # Create Theano variables
34 | logger.info('Creating theano variables')
35 | source_char_seq = tensor.lmatrix('source_char_seq')
36 | source_sample_matrix = tensor.btensor3('source_sample_matrix')
37 | source_char_aux = tensor.bmatrix('source_char_aux')
38 | source_word_mask = tensor.bmatrix('source_word_mask')
39 | target_char_seq = tensor.lmatrix('target_char_seq')
40 | target_char_aux = tensor.bmatrix('target_char_aux')
41 | target_char_mask = tensor.bmatrix('target_char_mask')
42 | target_sample_matrix = tensor.btensor3('target_sample_matrix')
43 | target_word_mask = tensor.bmatrix('target_word_mask')
44 | target_resample_matrix = tensor.btensor3('target_resample_matrix')
45 | target_prev_char_seq = tensor.lmatrix('target_prev_char_seq')
46 | target_prev_char_aux = tensor.bmatrix('target_prev_char_aux')
47 | target_bos_idx = tr_stream.trg_bos
48 | target_space_idx = tr_stream.space_idx['target']
49 |
50 | # Construct model
51 | logger.info('Building RNN encoder-decoder')
52 |
53 | encoder = BidirectionalEncoder(config['src_vocab_size'], config['enc_embed'], config['src_dgru_nhids'],
54 | config['enc_nhids'], config['src_dgru_depth'], config['bidir_encoder_depth'])
55 |
56 | decoder = Decoder(config['trg_vocab_size'], config['dec_embed'], config['trg_dgru_nhids'], config['trg_igru_nhids'],
57 | config['dec_nhids'], config['enc_nhids'] * 2, config['transition_depth'], config['trg_igru_depth'],
58 | config['trg_dgru_depth'], target_space_idx, target_bos_idx)
59 |
60 | representation = encoder.apply(source_char_seq, source_sample_matrix, source_char_aux,
61 | source_word_mask)
62 | cost = decoder.cost(representation, source_word_mask, target_char_seq, target_sample_matrix,
63 | target_resample_matrix, target_char_aux, target_char_mask,
64 | target_word_mask, target_prev_char_seq, target_prev_char_aux)
65 |
66 | logger.info('Creating computational graph')
67 | cg = ComputationGraph(cost)
68 |
69 | # Initialize model
70 | logger.info('Initializing model')
71 | encoder.weights_init = decoder.weights_init = IsotropicGaussian(
72 | config['weight_scale'])
73 | encoder.biases_init = decoder.biases_init = Constant(0)
74 | encoder.push_initialization_config()
75 | decoder.push_initialization_config()
76 | for layer_n in range(config['src_dgru_depth']):
77 | encoder.decimator.dgru.transitions[layer_n].weights_init = Orthogonal()
78 | for layer_n in range(config['bidir_encoder_depth']):
79 | encoder.children[1 + layer_n].prototype.recurrent.weights_init = Orthogonal()
80 | if config['trg_igru_depth'] == 1:
81 | decoder.interpolator.igru.weights_init = Orthogonal()
82 | else:
83 | for layer_n in range(config['trg_igru_depth']):
84 | decoder.interpolator.igru.transitions[layer_n].weights_init = Orthogonal()
85 | for layer_n in range(config['trg_dgru_depth']):
86 | decoder.interpolator.feedback_brick.dgru.transitions[layer_n].weights_init = Orthogonal()
87 | for layer_n in range(config['transition_depth']):
88 | decoder.transition.transitions[layer_n].weights_init = Orthogonal()
89 | encoder.initialize()
90 | decoder.initialize()
91 |
92 |
93 | # Print shapes
94 | shapes = [param.get_value().shape for param in cg.parameters]
95 | logger.info("Parameter shapes: ")
96 | for shape, count in Counter(shapes).most_common():
97 | logger.info(' {:15}: {}'.format(str(shape), count))
98 | logger.info("Total number of parameters: {}".format(len(shapes)))
99 |
100 | # Print parameter names
101 | enc_dec_param_dict = merge(Selector(encoder).get_parameters(),
102 | Selector(decoder).get_parameters())
103 | logger.info("Parameter names: ")
104 | for name, value in enc_dec_param_dict.items():
105 | logger.info(' {:15}: {}'.format(str(value.get_value().shape), name))
106 | logger.info("Total number of parameters: {}"
107 | .format(len(enc_dec_param_dict)))
108 |
109 | # Set up training model
110 | logger.info("Building model")
111 | training_model = Model(cost)
112 | # Set up training algorithm
113 | logger.info("Initializing training algorithm")
114 | algorithm = GradientDescent(
115 | cost=cost, parameters=cg.parameters,
116 | step_rule=CompositeRule([StepClipping(config['step_clipping']),
117 | eval(config['step_rule'])()])
118 | )
119 |
120 | # Set extensions
121 | logger.info("Initializing extensions")
122 | # Extensions
123 | gradient_norm = aggregation.mean(algorithm.total_gradient_norm)
124 | step_norm = aggregation.mean(algorithm.total_step_norm)
125 | train_monitor = CostCurve([cost, gradient_norm, step_norm], config=config, after_batch=True,
126 | before_first_epoch=True, prefix='tra')
127 | extensions = [
128 | train_monitor, Timing(),
129 | Printing(every_n_batches=config['print_freq']),
130 | FinishAfter(after_n_batches=config['finish_after']),
131 | CheckpointNMT(config['saveto'], every_n_batches=config['save_freq'])]
132 |
133 | # Set up beam search and sampling computation graphs if necessary
134 | if config['hook_samples'] >= 1 or config['bleu_script'] is not None:
135 | logger.info("Building sampling model")
136 | generated = decoder.generate(representation, source_word_mask)
137 | search_model = Model(generated)
138 | _, samples = VariableFilter(
139 | bricks=[decoder.sequence_generator], name="outputs")(
140 | ComputationGraph(generated[config['transition_depth']])) # generated[transition_depth] is next_outputs
141 |
142 | # Add sampling
143 | if config['hook_samples'] >= 1:
144 | logger.info("Building sampler")
145 | extensions.append(
146 | Sampler(model=search_model, data_stream=tr_stream,
147 | hook_samples=config['hook_samples'], transition_depth=config['transition_depth'],
148 | every_n_batches=config['sampling_freq'], src_vocab_size=config['src_vocab_size']))
149 |
150 | # Add early stopping based on bleu
151 | if config['bleu_script'] is not None:
152 | logger.info("Building bleu validator")
153 | extensions.append(
154 | BleuValidator(source_char_seq, source_sample_matrix, source_char_aux,
155 | source_word_mask, samples=samples, config=config,
156 | model=search_model, data_stream=dev_stream,
157 | normalize=config['normalized_bleu'],
158 | every_n_batches=config['bleu_val_freq']))
159 |
160 | # Reload model if necessary
161 | if config['reload']:
162 | extensions.append(LoadNMT(config['saveto']))
163 |
164 | # Initialize main loop
165 | logger.info("Initializing main loop")
166 | main_loop = MainLoop(
167 | model=training_model,
168 | algorithm=algorithm,
169 | data_stream=tr_stream,
170 | extensions=extensions
171 | )
172 |
173 | # Train!
174 | main_loop.run()
175 |
176 |
177 | if __name__ == "__main__":
178 | assert sys.version_info >= (3,4)
179 | # Get configurations for model
180 | configuration = configurations.get_config()
181 | logger.info("Model options:\n{}".format(pprint.pformat(configuration)))
182 | # Get data streams and call main
183 | main(configuration, get_tr_stream(**configuration),
184 | get_dev_stream(**configuration))
185 |
--------------------------------------------------------------------------------
/stream.py:
--------------------------------------------------------------------------------
1 | import numpy
2 |
3 | from fuel.datasets import TextFile
4 | from fuel.schemes import ConstantScheme
5 | from fuel.streams import DataStream
6 | from fuel.transformers import (
7 | Merge, Batch, Filter, Padding, SortMapping, Unpack, Mapping)
8 |
9 | import pickle
10 | import configurations
11 |
12 |
13 | def _ensure_special_tokens(vocab, bos_idx=0, eos_idx=0, unk_idx=1):
14 | """Ensures special tokens exist in the dictionary."""
15 |
16 | # remove tokens if they exist in some other index
17 | tokens_to_remove = [k for k, v in vocab.items()
18 | if v in [bos_idx, eos_idx, unk_idx]]
19 | for token in tokens_to_remove:
20 | vocab.pop(token)
21 | # put corresponding item
22 | vocab[''] = bos_idx
23 | vocab[''] = eos_idx
24 | vocab[''] = unk_idx
25 | return vocab
26 |
27 |
28 | def _length(sentence_pair):
29 | """Assumes target is the last element in the tuple."""
30 | return len(sentence_pair[-1])
31 |
32 |
33 | class TextFileWithSEOSS(TextFile):
34 | """ Add space eos space to end of source """
35 |
36 | def __init__(self, files, dictionary, bos_token='', eos_token='',
37 | unk_token='', level='word', preprocess=None,
38 | encoding=None):
39 | super(TextFileWithSEOSS, self).__init__(files, dictionary, bos_token, eos_token,
40 | unk_token, level, preprocess, encoding)
41 |
42 | def get_data(self, state=None, request=None):
43 | if request is not None:
44 | raise ValueError
45 | sentence = next(state)
46 | if self.preprocess is not None:
47 | sentence = self.preprocess(sentence)
48 | data = [self.dictionary[self.bos_token]] if self.bos_token else []
49 | if self.level == 'word':
50 | data.extend(self._get_from_dictionary(word)
51 | for word in sentence.split())
52 | else:
53 | data.extend(self._get_from_dictionary(char)
54 | for char in sentence.strip())
55 | if self.eos_token:
56 | data.append(self.dictionary[' '])
57 | data.append(self.dictionary[self.eos_token])
58 | data.append(self.dictionary[' '])
59 | return (data,)
60 |
61 |
62 | class PaddingWithEOS(Padding):
63 | """Padds a stream with given end of sequence idx."""
64 |
65 | def __init__(self, data_stream, space_idx, trg_bos, **kwargs):
66 | kwargs['data_stream'] = data_stream
67 | self.space_idx = space_idx
68 | self.trg_bos = trg_bos
69 | super(PaddingWithEOS, self).__init__(**kwargs)
70 |
71 | @property
72 | def sources(self):
73 | sources = ['source_char_seq', 'source_sample_matrix', 'source_char_aux', 'source_word_mask',
74 | 'target_char_seq', 'target_sample_matrix', 'target_char_aux', 'target_word_mask',
75 | 'target_char_mask', 'target_resample_matrix', 'target_prev_char_seq', 'target_prev_char_aux']
76 | return tuple(sources)
77 |
78 | def transform_batch(self, batch):
79 | batch_with_masks = []
80 | for k, (source, source_batch) in enumerate(zip(self.data_stream.sources, batch)):
81 | if source not in self.mask_sources:
82 | batch_with_masks.append(source_batch)
83 | continue
84 | word_shapes = [0] * len(source_batch)
85 | shapes = [0] * len(source_batch)
86 | for i, sample in enumerate(source_batch):
87 | np_sample = numpy.asarray(sample)
88 | word_shapes[i] = numpy.count_nonzero(np_sample == self.space_idx[source])
89 | shapes[i] = np_sample.shape
90 |
91 | lengths = [shape[0] for shape in shapes]
92 | max_word_len = max(word_shapes)
93 | add_space_length = []
94 | for i in range(len(lengths)):
95 | add_space_length.append(lengths[i] + max_word_len - word_shapes[i])
96 | max_char_seq_length = max(add_space_length)
97 | rest_shape = shapes[0][1:]
98 | if not all([shape[1:] == rest_shape for shape in shapes]):
99 | raise ValueError("All dimensions except length must be equal")
100 | dtype = numpy.asarray(source_batch[0]).dtype
101 |
102 | char_seq = numpy.zeros(
103 | (len(source_batch), max_char_seq_length) + rest_shape, dtype=dtype)
104 |
105 | for i, sample in enumerate(source_batch):
106 | char_seq[i, :len(sample)] = sample
107 | char_seq[i, len(sample):add_space_length[i]] = self.space_idx[source]
108 |
109 | sample_matrix = numpy.zeros((len(source_batch), max_word_len, max_char_seq_length),
110 | dtype=self.mask_dtype)
111 | char_seq_space_index = char_seq == self.space_idx[source]
112 |
113 | for i in range(len(source_batch)):
114 | sample_matrix[i, range(max_word_len),
115 | numpy.where(char_seq_space_index[i])[0] - 1] = 1
116 |
117 | char_aux = numpy.ones((len(source_batch), max_char_seq_length), self.mask_dtype)
118 | char_aux[char_seq_space_index] = 0
119 |
120 | word_mask = numpy.zeros((len(source_batch), max_word_len), self.mask_dtype)
121 | for i, ws in enumerate(word_shapes):
122 | word_mask[i, :ws] = 1
123 |
124 | batch_with_masks.append(char_seq)
125 | batch_with_masks.append(sample_matrix)
126 | batch_with_masks.append(char_aux)
127 | batch_with_masks.append(word_mask)
128 |
129 | # target sequence
130 | if source == 'target':
131 | target_char_mask = numpy.zeros((len(source_batch), max_char_seq_length), self.mask_dtype)
132 | for i, sequence_length in enumerate(lengths):
133 | target_char_mask[i, :sequence_length] = 1
134 | target_prev_char_seq = numpy.roll(char_seq, 1)
135 | target_prev_char_seq[:, 0] = self.trg_bos
136 | target_prev_char_aux = numpy.roll(char_aux, 1)
137 | # start of sequence, must be 0
138 | target_prev_char_aux[:, 0] = 0
139 | target_resample_matrix = numpy.zeros((len(source_batch), max_char_seq_length, max_word_len),
140 | dtype=self.mask_dtype)
141 |
142 | curr_space_idx = numpy.where(char_seq_space_index)
143 | for i in range(len(source_batch)):
144 | pj = 0
145 | for cj in range(max_word_len):
146 | target_resample_matrix[i, pj:curr_space_idx[1][i * max_word_len + cj] + 1, cj] = 1
147 | pj = curr_space_idx[1][i * max_word_len + cj] + 1
148 |
149 | batch_with_masks.append(target_char_mask)
150 | batch_with_masks.append(target_resample_matrix)
151 | batch_with_masks.append(target_prev_char_seq)
152 | batch_with_masks.append(target_prev_char_aux)
153 | return tuple(batch_with_masks)
154 |
155 |
156 | class _oov_to_unk(object):
157 | """Maps out of vocabulary token index to unk token index."""
158 |
159 | def __init__(self, src_vocab_size=120, trg_vocab_size=120,
160 | unk_id=1):
161 | self.src_vocab_size = src_vocab_size
162 | self.trg_vocab_size = trg_vocab_size
163 | self.unk_id = unk_id
164 |
165 | def __call__(self, sentence_pair):
166 | return ([x if x < self.src_vocab_size else self.unk_id
167 | for x in sentence_pair[0]],
168 | [x if x < self.trg_vocab_size else self.unk_id
169 | for x in sentence_pair[1]])
170 |
171 |
172 | class _too_long(object):
173 | """Filters sequences longer than given sequence length."""
174 |
175 | def __init__(self, unk_id, space_idx, max_src_seq_char_len, max_src_seq_word_len,
176 | max_trg_seq_char_len, max_trg_seq_word_len):
177 | self.unk_id = unk_id
178 | self.max_src_seq_char_len = max_src_seq_char_len
179 | self.max_src_seq_word_len = max_src_seq_word_len
180 | self.max_trg_seq_char_len = max_trg_seq_char_len
181 | self.max_trg_seq_word_len = max_trg_seq_word_len
182 | self.space_idx = space_idx
183 |
184 | def __call__(self, sentence_pair):
185 | max_unk = 5
186 | return all(
187 | [len(sentence_pair[0]) <= self.max_src_seq_char_len and sentence_pair[0].count(self.unk_id) < max_unk and
188 | sentence_pair[0].count(self.space_idx[0]) < self.max_src_seq_word_len,
189 | len(sentence_pair[1]) <= self.max_trg_seq_char_len and sentence_pair[1].count(self.unk_id) < max_unk and
190 | sentence_pair[1].count(self.space_idx[1]) < self.max_trg_seq_word_len])
191 |
192 |
193 | def get_tr_stream(src_vocab, trg_vocab, src_data, trg_data,
194 | src_vocab_size=120, trg_vocab_size=120, unk_id=1, bos_token='', max_src_seq_char_len=300,
195 | max_src_seq_word_len=50, max_trg_seq_char_len=300, max_trg_seq_word_len=50,
196 | batch_size=80, sort_k_batches=12, **kwargs):
197 | """Prepares the training data stream."""
198 |
199 | # Load dictionaries and ensure special tokens exist
200 | src_vocab = _ensure_special_tokens(
201 | src_vocab if isinstance(src_vocab, dict)
202 | else pickle.load(open(src_vocab, 'rb')),
203 | bos_idx=0, eos_idx=src_vocab_size - 1, unk_idx=unk_id)
204 |
205 | trg_vocab = _ensure_special_tokens(
206 | trg_vocab if isinstance(trg_vocab, dict) else
207 | pickle.load(open(trg_vocab, 'rb')),
208 | bos_idx=0, eos_idx=trg_vocab_size - 1, unk_idx=unk_id)
209 |
210 | # Get text files from both source and target
211 | src_dataset = TextFileWithSEOSS([src_data], src_vocab, None, level='character')
212 | trg_dataset = TextFileWithSEOSS([trg_data], trg_vocab, None, level='character')
213 |
214 | # Merge them to get a source, target pair
215 | stream = Merge([src_dataset.get_example_stream(),
216 | trg_dataset.get_example_stream()],
217 | ('source', 'target'))
218 |
219 | # Filter sequences that are too long
220 | stream = Filter(stream, predicate=_too_long(unk_id, [src_vocab[' '], trg_vocab[' ']],
221 | max_src_seq_char_len, max_src_seq_word_len,
222 | max_trg_seq_char_len, max_trg_seq_word_len))
223 |
224 | # Replace out of vocabulary tokens with unk token
225 | stream = Mapping(stream,
226 | _oov_to_unk(src_vocab_size=src_vocab_size,
227 | trg_vocab_size=trg_vocab_size,
228 | unk_id=unk_id))
229 |
230 | # Build a batched version of stream to read k batches ahead
231 | stream = Batch(stream,
232 | iteration_scheme=ConstantScheme(
233 | batch_size * sort_k_batches))
234 |
235 | # Sort all samples in the read-ahead batch
236 | stream = Mapping(stream, SortMapping(_length))
237 |
238 | # Convert it into a stream again
239 | stream = Unpack(stream)
240 | # Construct batches from the stream with specified batch size
241 | stream = Batch(
242 | stream, iteration_scheme=ConstantScheme(batch_size))
243 |
244 | # Pad sequences that are short
245 | masked_stream = PaddingWithEOS(stream, {'source': src_vocab[' '], 'target': trg_vocab[' ']}, trg_vocab[bos_token],
246 | mask_dtype='int8')
247 |
248 | return masked_stream
249 |
250 |
251 | def get_dev_stream(val_set=None, src_vocab=None, src_vocab_size=120,
252 | unk_id=1, **kwargs):
253 | """Setup development set stream if necessary."""
254 | dev_stream = None
255 | if val_set is not None and src_vocab is not None:
256 | src_vocab = _ensure_special_tokens(
257 | src_vocab if isinstance(src_vocab, dict) else
258 | pickle.load(open(src_vocab, 'rb')),
259 | bos_idx=0, eos_idx=src_vocab_size - 1, unk_idx=unk_id)
260 | dev_src_dataset = TextFileWithSEOSS([val_set], src_vocab, None, level='character')
261 | dev_stream = DataStream(dev_src_dataset)
262 | return dev_stream
263 |
264 |
265 | def get_test_stream(test_set=None, src_vocab=None, trg_vocab=None, src_vocab_size=120, trg_vocab_size=120, unk_id=1,
266 | bos_token='', **kwargs):
267 | """Setup development set stream if necessary."""
268 | test_stream = None
269 | if test_set is not None and src_vocab is not None and trg_vocab is not None:
270 | src_vocab = _ensure_special_tokens(
271 | src_vocab if isinstance(src_vocab, dict) else
272 | pickle.load(open(src_vocab, 'rb')),
273 | bos_idx=0, eos_idx=src_vocab_size - 1, unk_idx=unk_id)
274 |
275 | trg_vocab = _ensure_special_tokens(
276 | trg_vocab if isinstance(trg_vocab, dict) else
277 | pickle.load(open(trg_vocab, 'rb')),
278 | bos_idx=0, eos_idx=trg_vocab_size - 1, unk_idx=unk_id)
279 |
280 | test_src_dataset = TextFileWithSEOSS([test_set], src_vocab, None, level='character')
281 | test_stream = DataStream(test_src_dataset)
282 | test_stream.space_idx = {'source': src_vocab[' '], 'target': trg_vocab[' ']}
283 | test_stream.trg_bos = trg_vocab[bos_token]
284 | test_stream.trg_vocab = trg_vocab
285 | test_stream.eos_token = ''
286 |
287 | return test_stream
288 |
289 |
290 | if __name__ == '__main__':
291 | # test stream
292 | configuration = configurations.get_config()
293 | tr = get_tr_stream(**configuration)
294 | total = 0
295 | # test
296 | for s in tr.get_epoch_iterator():
297 | total += 1
298 | if total % 10000 == 0:
299 | print(total)
300 | print(total)
301 |
--------------------------------------------------------------------------------
/sampling.py:
--------------------------------------------------------------------------------
1 | from __future__ import print_function
2 |
3 | import logging
4 | import operator
5 | import os
6 | import time
7 | import re
8 | import signal
9 |
10 | import numpy
11 | from blocks.extensions import SimpleExtension, TrainingExtension
12 | from blocks.extensions.monitoring import TrainingDataMonitoring
13 | from blocks.search import BeamSearch
14 | from subprocess import Popen, PIPE
15 | from checkpoint import SaveLoadUtils
16 |
17 | logger = logging.getLogger(__name__)
18 |
19 |
20 | class SamplingBase(object):
21 | """Utility class for Validator and Sampler."""
22 |
23 | def _get_attr_rec(self, obj, attr):
24 | return self._get_attr_rec(getattr(obj, attr), attr) \
25 | if hasattr(obj, attr) else obj
26 |
27 | def _get_true_length(self, seq, vocab):
28 | try:
29 | return seq.tolist().index(vocab['']) + 1
30 | except ValueError:
31 | return len(seq)
32 |
33 | def _oov_to_unk(self, seq, vocab_size, unk_idx):
34 | return [x if x < vocab_size else unk_idx for x in seq]
35 |
36 | def _idx_to_word(self, seq, ivocab):
37 | return "".join([ivocab.get(idx, "") for idx in seq])
38 |
39 | def build_input_dict(self, input_, src_vocab):
40 | input_length = self._get_true_length(input_, src_vocab) + 1
41 | input_ = input_[:input_length]
42 | total_word = list(input_).count(src_vocab[' '])
43 |
44 | source_sample_matrix = numpy.zeros((total_word, input_length), dtype='int8')
45 | source_sample_matrix[range(total_word), numpy.nonzero(input_ == src_vocab[' '])[0] - 1] = 1
46 |
47 | source_word_mask = numpy.ones(total_word, dtype='int8')
48 |
49 | source_char_aux = numpy.ones(input_length, dtype='int8')
50 | source_char_aux[input_ == src_vocab[' ']] = 0
51 |
52 | input_dict = {'source_sample_matrix': source_sample_matrix[None, :],
53 | 'source_char_aux': source_char_aux[None, :],
54 | 'source_char_seq': input_[None, :],
55 | 'source_word_mask': source_word_mask[None, :]}
56 | return input_length, input_dict
57 |
58 | def build_input_dict_tile(self, input_, src_vocab, beam_size):
59 | input_length = self._get_true_length(input_, src_vocab) + 1
60 | input_ = input_[:input_length]
61 | total_word = list(input_).count(src_vocab[' '])
62 |
63 | source_sample_matrix = numpy.zeros((total_word, input_length), dtype='int8')
64 | source_sample_matrix[range(total_word), numpy.nonzero(input_ == src_vocab[' '])[0] - 1] = 1
65 |
66 | source_word_mask = numpy.ones(total_word, dtype='int8')
67 |
68 | source_char_aux = numpy.ones(input_length, dtype='int8')
69 | source_char_aux[input_ == src_vocab[' ']] = 0
70 |
71 | input_dict = {'source_sample_matrix': numpy.tile(source_sample_matrix, (beam_size, 1, 1)),
72 | 'source_word_mask': numpy.tile(source_word_mask, (beam_size, 1)),
73 | 'source_char_aux': numpy.tile(source_char_aux, (beam_size, 1)),
74 | 'source_char_seq': numpy.tile(input_, (beam_size, 1))}
75 |
76 | return input_dict
77 |
78 |
79 | class CostCurve(TrainingDataMonitoring):
80 | """ Record training curve """
81 |
82 | def __init__(self, variables, config, **kwargs):
83 | super(CostCurve, self).__init__(variables, **kwargs)
84 | self.cost_curve = []
85 | self.config = config
86 | # Create saving directory if it does not exist
87 | if not os.path.exists(self.config['saveto']):
88 | os.makedirs(self.config['saveto'])
89 |
90 | if self.config['reload']:
91 | try:
92 | self.cost_curve = numpy.load(os.path.join(self.config['saveto'],
93 | 'cost_curve.npz'))
94 | self.cost_curve = self.cost_curve['cost_curves'].tolist()
95 | logger.info("Cost Curve Reloaded")
96 | except:
97 | logger.info("Cost Curve not Found")
98 |
99 | def do(self, callback_name, *args):
100 | """Initializes the buffer or commits the values to the log.
101 | What this method does depends on from what callback it is called
102 | and with which arguments. When called within `before_training`, it
103 | initializes the aggregation buffer and instructs the training
104 | algorithm what additional computations should be carried at each
105 | step by adding corresponding updates to it. In most_other cases it
106 | writes aggregated values of the monitored variables to the log. An
107 | exception is when an argument `just_aggregate` is given: in this
108 | cases it updates the values of monitored non-Theano quantities, but
109 | does not write anything to the log.
110 | """
111 | data, args = self.parse_args(callback_name, args)
112 | if callback_name == 'before_training':
113 | self.main_loop.algorithm.add_updates(
114 | self._variables.accumulation_updates)
115 | self.main_loop.algorithm.add_updates(
116 | self._required_for_non_variables.accumulation_updates)
117 | self._variables.initialize_aggregators()
118 | self._required_for_non_variables.initialize_aggregators()
119 | self._non_variables.initialize_quantities()
120 | else:
121 | # When called first time at any iterations, update
122 | # monitored non-Theano quantities
123 | if (self.main_loop.status['iterations_done'] >
124 | self._last_time_called):
125 | self._non_variables.aggregate_quantities(
126 | list(self._required_for_non_variables
127 | .get_aggregated_values().values()))
128 | self._required_for_non_variables.initialize_aggregators()
129 | self._last_time_called = (
130 | self.main_loop.status['iterations_done'])
131 | # If only called to update non-Theano quantities,
132 | # do just that
133 | if args == ('just_aggregate',):
134 | return
135 | # Otherwise, also save current values of from the accumulators
136 | curr_iter = self.main_loop.status['iterations_done']
137 | if curr_iter == 0:
138 | return
139 |
140 | curr_cost = self._variables.get_aggregated_values()
141 | curr_cost = curr_cost['decoder_cost_cost'].tolist()
142 | self.cost_curve.append({curr_iter: curr_cost})
143 |
144 | if curr_iter % 100 == 0:
145 | numpy.savez(os.path.join(self.config['saveto'], 'cost_curve.npz'),
146 | cost_curves=self.cost_curve)
147 |
148 | self.add_records(
149 | self.main_loop.log,
150 | self._variables.get_aggregated_values().items())
151 | self._variables.initialize_aggregators()
152 | self.add_records(
153 | self.main_loop.log,
154 | self._non_variables.get_aggregated_values().items())
155 | self._non_variables.initialize_quantities()
156 |
157 |
158 | class Sampler(SimpleExtension, SamplingBase):
159 | """Random Sampling from model."""
160 |
161 | def __init__(self, model, data_stream, hook_samples=1, transition_depth=1,
162 | src_vocab=None, trg_vocab=None, src_ivocab=None,
163 | trg_ivocab=None, src_vocab_size=None, **kwargs):
164 | super(Sampler, self).__init__(**kwargs)
165 | self.model = model
166 | self.hook_samples = hook_samples
167 | self.data_stream = data_stream
168 | self.src_vocab = src_vocab
169 | self.trg_vocab = trg_vocab
170 | self.src_ivocab = src_ivocab
171 | self.transition_depth = transition_depth
172 | self.trg_ivocab = trg_ivocab
173 | self.src_vocab_size = src_vocab_size
174 | self.is_synced = False
175 | self.sampling_fn = model.get_theano_function()
176 |
177 | def do(self, which_callback, *args):
178 |
179 | # Get dictionaries, this may not be the practical way
180 | sources = self._get_attr_rec(self.main_loop, 'data_stream')
181 |
182 | # Load vocabularies and invert if necessary
183 | # WARNING: Source and target indices from data stream
184 | # can be different
185 | if not self.src_vocab:
186 | self.src_vocab = sources.data_streams[0].dataset.dictionary
187 | if not self.trg_vocab:
188 | self.trg_vocab = sources.data_streams[1].dataset.dictionary
189 | if not self.src_ivocab:
190 | self.src_ivocab = {v: k for k, v in self.src_vocab.items()}
191 | if not self.trg_ivocab:
192 | self.trg_ivocab = {v: k for k, v in self.trg_vocab.items()}
193 | if not self.src_vocab_size:
194 | self.src_vocab_size = len(self.src_vocab)
195 |
196 | # Randomly select source samples from the current batch
197 | # WARNING: Source and target indices from data stream
198 | # can be different
199 | batch = args[0]
200 | batch_size = batch['source_char_seq'].shape[0]
201 | hook_samples = min(batch_size, self.hook_samples)
202 |
203 | # TODO: this is problematic for boundary conditions, eg. last batch
204 | sample_idx = numpy.random.choice(
205 | batch_size, hook_samples, replace=False)
206 | src_batch = batch['source_char_seq']
207 | trg_batch = batch['target_char_seq']
208 | input_ = src_batch[sample_idx, :]
209 | target_ = trg_batch[sample_idx, :]
210 |
211 | # Sample
212 | print()
213 | for i in range(hook_samples):
214 | input_length, input_dict = self.build_input_dict(input_[i], self.src_vocab)
215 | target_length = self._get_true_length(target_[i], self.trg_vocab) + 1
216 | sfn = self.sampling_fn(**input_dict)
217 | outputs = sfn[self.transition_depth]
218 | costs = sfn[-1]
219 | outputs = outputs.flatten()
220 | costs = costs.flatten()
221 |
222 | sample_length = self._get_true_length(outputs, self.trg_vocab)
223 | print("Input : ", self._idx_to_word(input_[i][:input_length],
224 | self.src_ivocab))
225 | print("Target: ", self._idx_to_word(target_[i][:target_length],
226 | self.trg_ivocab))
227 | print("Sample: ", self._idx_to_word(outputs[:sample_length],
228 | self.trg_ivocab))
229 | print("Sample cost: ", costs[:sample_length].mean())
230 | print()
231 |
232 |
233 | class BleuValidator(SimpleExtension, SamplingBase, SaveLoadUtils):
234 | # TODO: a lot has been changed in NMT, sync respectively
235 | """Implements early stopping based on BLEU score."""
236 |
237 | def __init__(self, source_char_seq, source_sample_matrix, source_char_aux,
238 | source_word_mask, samples, model, data_stream,
239 | config, n_best=1, track_n_models=1,
240 | normalize=True, **kwargs):
241 | # TODO: change config structure
242 | super(BleuValidator, self).__init__(**kwargs)
243 | self.source_char_seq = source_char_seq
244 | self.source_sample_matrix = source_sample_matrix
245 | self.source_char_aux = source_char_aux
246 | self.source_word_mask = source_word_mask
247 | self.samples = samples
248 | self.model = model
249 | self.data_stream = data_stream
250 | self.config = config
251 | self.n_best = n_best
252 | self.track_n_models = track_n_models
253 | self.normalize = normalize
254 | self.verbose = config.get('val_set_out', None)
255 |
256 | # Helpers
257 | self.vocab = data_stream.dataset.dictionary
258 | self.src_ivocab = {v: k for k, v in self.vocab.items()}
259 | self.unk_sym = data_stream.dataset.unk_token
260 | self.eos_sym = data_stream.dataset.eos_token
261 | self.unk_idx = self.vocab[self.unk_sym]
262 | self.eos_idx = self.vocab[self.eos_sym]
263 | self.best_models = []
264 | self.val_bleu_curve = []
265 | self.beam_search = BeamSearch(samples=samples)
266 | self.multibleu_cmd = ['perl', self.config['bleu_script'],
267 | self.config['val_set_grndtruth'], '<']
268 |
269 | # Create saving directory if it does not exist
270 | if not os.path.exists(self.config['saveto']):
271 | os.makedirs(self.config['saveto'])
272 |
273 | if self.config['reload']:
274 | try:
275 | bleu_score = numpy.load(os.path.join(self.config['saveto'],
276 | 'val_bleu_scores.npz'))
277 | self.val_bleu_curve = bleu_score['bleu_scores'].tolist()
278 | # Track n best previous bleu scores
279 | for i, bleu in enumerate(
280 | sorted([list(v.values())[0] for v in self.val_bleu_curve], reverse=True)):
281 | if i < self.track_n_models:
282 | self.best_models.append(ModelInfo(bleu, self.config['saveto']))
283 | logger.info("BleuScores Reloaded")
284 | except:
285 | logger.info("BleuScores not Found")
286 |
287 | def do(self, which_callback, *args):
288 |
289 | # Track validation burn in
290 | if self.main_loop.status['iterations_done'] < \
291 | self.config['val_burn_in']:
292 | return
293 |
294 | # Evaluate and save if necessary
295 | self._save_model(self._evaluate_model(self.main_loop))
296 |
297 | def _evaluate_model(self, main_loop):
298 | curr_iter = main_loop.status['iterations_done']
299 | logger.info("Started Validation: ")
300 | val_start_time = time.time()
301 | mb_subprocess = Popen(self.multibleu_cmd, stdin=PIPE, stdout=PIPE, universal_newlines=True)
302 | total_cost = 0.0
303 |
304 | # Get target vocabulary
305 | sources = self._get_attr_rec(self.main_loop, 'data_stream')
306 | trg_vocab = sources.data_streams[1].dataset.dictionary
307 | self.trg_vocab = trg_vocab
308 | self.trg_ivocab = {v: k for k, v in trg_vocab.items()}
309 | trg_eos_sym = sources.data_streams[1].dataset.eos_token
310 | self.trg_eos_idx = trg_vocab[trg_eos_sym]
311 |
312 | if self.verbose:
313 | ftrans = open(self.config['val_set_out'] + str(curr_iter), 'w')
314 |
315 | for i, line in enumerate(self.data_stream.get_epoch_iterator()):
316 | """
317 | Load the sentence, retrieve the sample, write to file
318 | """
319 |
320 | seq = self._oov_to_unk(
321 | line[0], self.config['src_vocab_size'], self.unk_idx)
322 | input_dict = self.build_input_dict_tile(numpy.asarray(seq), self.vocab, self.config['beam_size'])
323 |
324 | # draw sample, checking to ensure we don't get an empty string back
325 | trans, costs = \
326 | self.beam_search.search(
327 | input_values={self.source_char_seq: input_dict['source_char_seq'],
328 | self.source_sample_matrix: input_dict['source_sample_matrix'],
329 | self.source_word_mask: input_dict['source_word_mask'],
330 | self.source_char_aux: input_dict['source_char_aux']},
331 | max_length=3 * len(seq), eol_symbol=self.trg_eos_idx,
332 | ignore_first_eol=False)
333 |
334 | # normalize costs according to the sequence lengths
335 | if self.normalize:
336 | lengths = numpy.array([len(s) for s in trans])
337 | costs = costs / lengths
338 |
339 | nbest_idx = numpy.argsort(costs)[:self.n_best]
340 | for j, best in enumerate(nbest_idx):
341 | try:
342 | total_cost += costs[best]
343 | trans_out = trans[best]
344 |
345 | # convert idx to words
346 | try:
347 | sample_length = trans_out.index(self.trg_vocab[''])
348 | except ValueError:
349 | sample_length = len(seq)
350 | trans_out = trans_out[:sample_length]
351 | trans_out = self._idx_to_word(trans_out, self.trg_ivocab)
352 |
353 | except ValueError:
354 | logger.info(
355 | "Can NOT find a translation for line: {}".format(i + 1))
356 | trans_out = ''
357 |
358 | if j == 0:
359 | # Write to subprocess and file if it exists
360 | print("Line:", i)
361 | print("Input : ", self._idx_to_word(line[0], self.src_ivocab))
362 | print("Sample: ", trans_out)
363 | print("Error:", costs[best])
364 | print()
365 |
366 | print(trans_out, file=mb_subprocess.stdin)
367 | if self.verbose:
368 | print(trans_out, file=ftrans)
369 |
370 | if i != 0 and i % 100 == 0:
371 | logger.info(
372 | "Translated {} lines of validation set...".format(i))
373 |
374 | mb_subprocess.stdin.flush()
375 |
376 | logger.info("Total cost of the validation: {}".format(total_cost))
377 | self.data_stream.reset()
378 | if self.verbose:
379 | ftrans.close()
380 |
381 | # send end of file, read output.
382 | mb_subprocess.stdin.close()
383 | stdout = mb_subprocess.stdout.readline()
384 | logger.info(stdout)
385 | out_parse = re.match(r'BLEU = [-.0-9]+', stdout)
386 | logger.info("Validation Took: {} minutes".format(
387 | float(time.time() - val_start_time) / 60.))
388 | assert out_parse is not None
389 |
390 | # extract the score
391 | bleu_score = float(out_parse.group()[6:])
392 | self.val_bleu_curve.append({curr_iter: bleu_score})
393 | logger.info(bleu_score)
394 | mb_subprocess.terminate()
395 |
396 | return bleu_score
397 |
398 | def _is_valid_to_save(self, bleu_score):
399 | if not self.best_models or min(self.best_models,
400 | key=operator.attrgetter('bleu_score')).bleu_score < bleu_score:
401 | return True
402 | return False
403 |
404 | def _save_model(self, bleu_score):
405 | numpy.savez(
406 | os.path.join(self.config['saveto'], 'val_bleu_scores.npz'),
407 | bleu_scores=self.val_bleu_curve)
408 | if self._is_valid_to_save(bleu_score):
409 | model = ModelInfo(bleu_score, self.config['saveto'])
410 |
411 | # Manage n-best model list first
412 | if len(self.best_models) >= self.track_n_models:
413 | old_model = self.best_models[0]
414 | if old_model.path and os.path.isfile(old_model.path):
415 | logger.info("Deleting old model %s" % old_model.path)
416 | os.remove(old_model.path)
417 | self.best_models.remove(old_model)
418 |
419 | self.best_models.append(model)
420 | self.best_models.sort(key=operator.attrgetter('bleu_score'))
421 |
422 | # Save the model here
423 | s = signal.signal(signal.SIGINT, signal.SIG_IGN)
424 | logger.info("Saving new model {}".format(model.path))
425 | params_to_save = self.main_loop.model.get_parameter_values()
426 | self.save_parameter_values(params_to_save, model.path)
427 | signal.signal(signal.SIGINT, s)
428 |
429 |
430 | class BleuTester(TrainingExtension, SamplingBase):
431 | # TODO: a lot has been changed in NMT, sync respectively
432 | """Implements Testing BLEU score."""
433 |
434 | def __init__(self, source_char_seq, source_sample_matrix, source_char_aux,
435 | source_word_mask, samples, model, data_stream,
436 | config, n_best=1, track_n_models=1,
437 | normalize=True, **kwargs):
438 | # TODO: change config structure
439 | super(BleuTester, self).__init__(**kwargs)
440 | self.source_char_seq = source_char_seq
441 | self.source_sample_matrix = source_sample_matrix
442 | self.source_char_aux = source_char_aux
443 | self.source_word_mask = source_word_mask
444 | self.samples = samples
445 | self.model = model
446 | self.data_stream = data_stream
447 | self.config = config
448 | self.n_best = n_best
449 | self.track_n_models = track_n_models
450 | self.normalize = normalize
451 | self.verbose = True
452 |
453 | # Helpers
454 | self.vocab = data_stream.dataset.dictionary
455 | self.src_ivocab = {v: k for k, v in self.vocab.items()}
456 | self.unk_sym = data_stream.dataset.unk_token
457 | self.eos_sym = data_stream.dataset.eos_token
458 | self.unk_idx = self.vocab[self.unk_sym]
459 | self.eos_idx = self.vocab[self.eos_sym]
460 | self.beam_search = BeamSearch(samples=samples)
461 | self.multibleu_cmd = ['perl', self.config['bleu_script'],
462 | self.config['test_set_grndtruth'], '<']
463 |
464 | # Create saving directory if it does not exist
465 | if not os.path.exists(self.config['saveto']):
466 | os.makedirs(self.config['saveto'])
467 |
468 | def before_training(self):
469 | self._evaluate_model()
470 |
471 | def _evaluate_model(self):
472 |
473 | logger.info("Started Test: ")
474 | test_start_time = time.time()
475 | mb_subprocess = Popen(self.multibleu_cmd, stdin=PIPE, stdout=PIPE, universal_newlines=True)
476 | total_cost = 0.0
477 |
478 | # Get target vocabulary
479 | trg_vocab = self.data_stream.trg_vocab
480 | self.trg_vocab = trg_vocab
481 | self.trg_ivocab = {v: k for k, v in trg_vocab.items()}
482 | trg_eos_sym = self.data_stream.eos_token
483 | self.trg_eos_idx = trg_vocab[trg_eos_sym]
484 |
485 | if self.verbose:
486 | ftrans = open(self.config['test_set_out'], 'w')
487 |
488 | for i, line in enumerate(self.data_stream.get_epoch_iterator()):
489 | """
490 | Load the sentence, retrieve the sample, write to file
491 | """
492 |
493 | seq = self._oov_to_unk(
494 | line[0], self.config['src_vocab_size'], self.unk_idx)
495 | input_dict = self.build_input_dict_tile(numpy.asarray(seq), self.vocab, self.config['beam_size'])
496 |
497 | # draw sample, checking to ensure we don't get an empty string back
498 | trans, costs = \
499 | self.beam_search.search(
500 | input_values={self.source_char_seq: input_dict['source_char_seq'],
501 | self.source_sample_matrix: input_dict['source_sample_matrix'],
502 | self.source_word_mask: input_dict['source_word_mask'],
503 | self.source_char_aux: input_dict['source_char_aux']},
504 | max_length=3 * len(seq), eol_symbol=self.trg_eos_idx,
505 | ignore_first_eol=False)
506 |
507 | # normalize costs according to the sequence lengths
508 | if self.normalize:
509 | lengths = numpy.array([len(s) for s in trans])
510 | costs = costs / lengths
511 |
512 | nbest_idx = numpy.argsort(costs)[:self.n_best]
513 | for j, best in enumerate(nbest_idx):
514 | try:
515 | total_cost += costs[best]
516 | trans_out = trans[best]
517 |
518 | # convert idx to words
519 | try:
520 | sample_length = trans_out.index(self.trg_vocab[''])
521 | except ValueError:
522 | sample_length = len(seq)
523 | trans_out = trans_out[:sample_length]
524 | trans_out = self._idx_to_word(trans_out, self.trg_ivocab)
525 |
526 | except ValueError:
527 | logger.info(
528 | "Can NOT find a translation for line: {}".format(i + 1))
529 | trans_out = ''
530 |
531 | if j == 0:
532 | # Write to subprocess and file if it exists
533 | print("Line:", i)
534 | print("Input : ", self._idx_to_word(line[0], self.src_ivocab))
535 | print("Sample: ", trans_out)
536 | print("Error:", costs[best])
537 | print()
538 |
539 | print(trans_out, file=mb_subprocess.stdin)
540 | if self.verbose:
541 | print(trans_out, file=ftrans)
542 |
543 | if i != 0 and i % 100 == 0:
544 | logger.info(
545 | "Translated {} lines of test set...".format(i))
546 |
547 | mb_subprocess.stdin.flush()
548 |
549 | logger.info("Total cost of the test: {}".format(total_cost))
550 | self.data_stream.reset()
551 | if self.verbose:
552 | ftrans.close()
553 |
554 | # send end of file, read output.
555 | mb_subprocess.stdin.close()
556 | stdout = mb_subprocess.stdout.readline()
557 | logger.info(stdout)
558 | out_parse = re.match(r'BLEU = [-.0-9]+', stdout)
559 | logger.info("Test Took: {} minutes".format(
560 | float(time.time() - test_start_time) / 60.))
561 | assert out_parse is not None
562 |
563 | # extract the score
564 | bleu_score = float(out_parse.group()[6:])
565 | logger.info(bleu_score)
566 | mb_subprocess.terminate()
567 |
568 | return bleu_score
569 |
570 |
571 |
572 | class ModelInfo:
573 | """Utility class to keep track of evaluated models."""
574 |
575 | def __init__(self, bleu_score, path=''):
576 | self.bleu_score = bleu_score
577 |
578 | self.path = self._generate_path(path)
579 |
580 | def _generate_path(self, path):
581 | gen_path = os.path.join(
582 | path, 'best_bleu_params_BLEU%.2f.npz' %
583 | (self.bleu_score) if path else None)
584 | return gen_path
585 |
--------------------------------------------------------------------------------
/model.py:
--------------------------------------------------------------------------------
1 | import copy
2 |
3 | from blocks.bricks import (Tanh, Linear, FeedforwardSequence, Identity,
4 | Initializable, MLP)
5 | from blocks.bricks.attention import SequenceContentAttention, AttentionRecurrent
6 | from blocks.bricks.base import application, lazy
7 | from blocks.bricks.lookup import LookupTable
8 | from blocks.bricks.parallel import Fork
9 | from blocks.bricks.recurrent import GatedRecurrent, Bidirectional, recurrent, RecurrentStack
10 | from blocks.bricks.sequence_generators import (
11 | Readout, SoftmaxEmitter, BaseSequenceGenerator)
12 | from blocks.roles import add_role, WEIGHT
13 | from blocks.utils import shared_floatx_nans, dict_subset, dict_union
14 | from theano import tensor
15 | from toolz import merge
16 | from blocks.bricks.recurrent.misc import RECURRENTSTACK_SEPARATOR
17 |
18 | # Helper class
19 | class InitializableFeedforwardSequence(FeedforwardSequence, Initializable):
20 | pass
21 |
22 |
23 | class DGRU(GatedRecurrent):
24 | """DGRU in Decimator"""
25 |
26 | def __init__(self, dim, activation=None, gate_activation=None,
27 | **kwargs):
28 | super(DGRU, self).__init__(dim, activation, gate_activation, **kwargs)
29 |
30 | @recurrent(sequences=['mask', 'inputs', 'gate_inputs'],
31 | states=['states'], outputs=['states'], contexts=[])
32 | def apply(self, inputs, gate_inputs, states, mask=None):
33 | """Apply the gated recurrent transition.
34 | Parameters
35 | ----------
36 | states : :class:`~tensor.TensorVariable`
37 | The 2 dimensional matrix of current states in the shape
38 | (batch_size, dim). Required for `one_step` usage.
39 | inputs : :class:`~tensor.TensorVariable`
40 | The 2 dimensional matrix of inputs in the shape (batch_size,
41 | dim)
42 | gate_inputs : :class:`~tensor.TensorVariable`
43 | The 2 dimensional matrix of inputs to the gates in the
44 | shape (batch_size, 2 * dim).
45 | mask : :class:`~tensor.TensorVariable`
46 | A 1D binary array in the shape (batch,) which is 1 if there is
47 | the charater available, 0 if there is the delimiter.
48 | Returns
49 | -------
50 | output : :class:`~tensor.TensorVariable`
51 | Next states of the network.
52 | """
53 | gate_values = self.gate_activation.apply(
54 | states.dot(self.state_to_gates) + gate_inputs)
55 | update_values = gate_values[:, :self.dim]
56 | reset_values = gate_values[:, self.dim:]
57 | states_reset = states * reset_values
58 | next_states = self.activation.apply(
59 | states_reset.dot(self.state_to_state) + inputs)
60 | next_states = (next_states * update_values +
61 | states * (1 - update_values))
62 | if mask:
63 | next_states = (mask[:, None] * next_states +
64 | (1 - mask[:, None]) * self.initial_states(mask.shape[0]))
65 | return next_states
66 |
67 |
68 | class Decimator(Initializable):
69 | """Char encoder, mapping a charater-level word to a vector"""
70 |
71 | def __init__(self, vocab_size, embedding_dim, dgru_state_dim, dgru_depth, **kwargs):
72 | super(Decimator, self).__init__(**kwargs)
73 |
74 | self.vocab_size = vocab_size
75 | self.embedding_dim = embedding_dim
76 | self.dgru_state_dim = dgru_state_dim
77 | self.embedding_dim = embedding_dim
78 | self.lookup = LookupTable(name='embeddings')
79 | self.dgru_depth = dgru_depth
80 | self.dgru = RecurrentStack([DGRU(activation=Tanh(), dim=self.dgru_state_dim) for _ in range(dgru_depth)],
81 | skip_connections=True)
82 |
83 | self.gru_fork = Fork([name for name in self.dgru.apply.sequences
84 | if name != 'mask'], prototype=Linear(), name='gru_fork')
85 |
86 | self.children = [self.lookup, self.dgru, self.gru_fork]
87 |
88 | def _push_allocation_config(self):
89 | self.lookup.length = self.vocab_size
90 | self.lookup.dim = self.embedding_dim
91 |
92 | self.gru_fork.input_dim = self.embedding_dim
93 | self.gru_fork.output_dims = [self.dgru.get_dim(name)
94 | for name in self.gru_fork.output_names]
95 |
96 | @application(inputs=['char_seq', 'sample_matrix', 'char_aux'],
97 | outputs=['representation'])
98 | def apply(self, char_seq, sample_matrix, char_aux):
99 | # Time as first dimension
100 | embeddings = self.lookup.apply(char_seq)
101 | gru_out = self.dgru.apply(
102 | **merge(self.gru_fork.apply(embeddings, as_dict=True),
103 | {'mask': char_aux}))
104 | if self.dgru_depth > 1:
105 | gru_out = gru_out[-1]
106 | sampled_representation = tensor.batched_dot(sample_matrix, gru_out.dimshuffle([1, 0, 2]))
107 | return sampled_representation.dimshuffle([1, 0, 2])
108 |
109 | @application(inputs=['target_single_char'])
110 | def single_emit(self, target_single_char, batch_size, mask, states=None):
111 | # Time as first dimension
112 | # only one batch
113 | embeddings = self.lookup.apply(target_single_char)
114 | if states is None:
115 | states = self.dgru.initial_states(batch_size)
116 | states_dict = {'states':states[0]}
117 | for i in range(1,self.dgru_depth):
118 | states_dict['states'+RECURRENTSTACK_SEPARATOR+str(i)] = states[i]
119 | gru_out = self.dgru.apply(**merge(self.gru_fork.apply(embeddings, as_dict=True), states_dict,
120 | {'mask': mask, 'iterate': False}))
121 | return gru_out
122 |
123 | @single_emit.property('outputs')
124 | def single_emit_outputs(self):
125 | return ['gru_out' + RECURRENTSTACK_SEPARATOR + str(i) for i in range(self.dgru_depth)]
126 |
127 | def get_dim(self, name):
128 | if name in ['output', 'feedback']:
129 | return self.dgru_state_dim
130 | super(Decimator, self).get_dim(name)
131 |
132 |
133 | class RecurrentWithFork(Initializable):
134 | @lazy(allocation=['input_dim'])
135 | def __init__(self, proto, input_dim, **kwargs):
136 | super(RecurrentWithFork, self).__init__(**kwargs)
137 | self.recurrent = proto
138 | self.input_dim = input_dim
139 | self.fork = Fork(
140 | [name for name in self.recurrent.apply.sequences
141 | if name != 'mask'],
142 | prototype=Linear())
143 | self.children = [self.recurrent, self.fork]
144 |
145 | def _push_allocation_config(self):
146 | self.fork.input_dim = self.input_dim
147 | self.fork.output_dims = [self.recurrent.get_dim(name)
148 | for name in self.fork.output_names]
149 |
150 | @application(inputs=['input_', 'mask'])
151 | def apply(self, input_, mask=None, **kwargs):
152 | return self.recurrent.apply(
153 | mask=mask, **dict_union(self.fork.apply(input_, as_dict=True),
154 | kwargs))
155 |
156 | @apply.property('outputs')
157 | def apply_outputs(self):
158 | return self.recurrent.states
159 |
160 |
161 | class BidirectionalEncoder(Initializable):
162 | """Encoder of model."""
163 |
164 | def __init__(self, src_vocab_size, embedding_dim, dgru_state_dim, state_dim, src_dgru_depth,
165 | bidir_encoder_depth, **kwargs):
166 | super(BidirectionalEncoder, self).__init__(**kwargs)
167 | self.state_dim = state_dim
168 | self.dgru_state_dim = dgru_state_dim
169 | self.decimator = Decimator(src_vocab_size, embedding_dim, dgru_state_dim, src_dgru_depth)
170 | self.bidir = Bidirectional(
171 | RecurrentWithFork(GatedRecurrent(activation=Tanh(), dim=state_dim), dgru_state_dim, name='with_fork'),
172 | name='bidir0')
173 |
174 | self.children = [self.decimator, self.bidir]
175 | for layer_n in range(1, bidir_encoder_depth):
176 | self.children.append(copy.deepcopy(self.bidir))
177 | for child in self.children[-1].children:
178 | child.input_dim = 2 * state_dim
179 | self.children[-1].name = 'bidir{}'.format(layer_n)
180 |
181 | @application(inputs=['source_char_seq', 'source_sample_matrix', 'source_char_aux', 'source_word_mask'],
182 | outputs=['representation'])
183 | def apply(self, source_char_seq, source_sample_matrix, source_char_aux, source_word_mask):
184 | # Time as first dimension
185 | source_char_seq = source_char_seq.T
186 | source_char_aux = source_char_aux.T
187 | source_word_mask = source_word_mask.T
188 | source_word_representation = self.decimator.apply(source_char_seq, source_sample_matrix, source_char_aux)
189 | representation = source_word_representation
190 | for bidir in self.children[1:]:
191 | representation = bidir.apply(representation, source_word_mask)
192 | return representation
193 |
194 |
195 | class IGRU(GatedRecurrent):
196 | """IGRU in interpolator """
197 |
198 | def __init__(self, dim, activation=None, gate_activation=None,
199 | **kwargs):
200 | super(IGRU, self).__init__(dim, activation, gate_activation, **kwargs)
201 |
202 | @recurrent(sequences=['mask', 'inputs', 'gate_inputs', 'input_states'],
203 | states=['states'], outputs=['states'], contexts=[])
204 | def apply(self, inputs, gate_inputs, states, input_states, mask=None):
205 | """Apply the gated recurrent transition.
206 | Parameters
207 | ----------
208 | states : :class:`~tensor.TensorVariable`
209 | The 2 dimensional matrix of current states in the shape
210 | (batch_size, dim). Required for `one_step` usage.
211 | inputs : :class:`~tensor.TensorVariable`
212 | The 2 dimensional matrix of inputs in the shape (batch_size,
213 | dim)
214 | gate_inputs : :class:`~tensor.TensorVariable`
215 | The 2 dimensional matrix of inputs to the gates in the
216 | shape (batch_size, 2 * dim).
217 | input_states : :class:`~tensor.TensorVariable`
218 | The 2 dimensional matrix of outputs of decoder in the shape
219 | (batch_size, dim), which generated by decoder.
220 | mask : :class:`~tensor.TensorVariable`
221 | A 1D binary array in the shape (batch,) which is 1 if there is
222 | the charater available, 0 if there is the delimiter.
223 | Returns
224 | -------
225 | output : :class:`~tensor.TensorVariable`
226 | Next states of the network.
227 | """
228 | # put masked states at last may be possible
229 | if mask:
230 | states = (mask[:, None] * states + (1 - mask[:, None]) * input_states)
231 | gate_values = self.gate_activation.apply(
232 | states.dot(self.state_to_gates) + gate_inputs)
233 | update_values = gate_values[:, :self.dim]
234 | reset_values = gate_values[:, self.dim:]
235 | #states_reset = (states + input_states) * reset_values / 2
236 | states_reset = states * reset_values
237 | next_states = self.activation.apply(
238 | states_reset.dot(self.state_to_state) + inputs)
239 | next_states = (next_states * update_values +
240 | states * (1 - update_values))
241 | return next_states
242 |
243 | # using constant initial_states
244 | def _allocate(self):
245 | self.parameters.append(shared_floatx_nans((self.dim, self.dim),
246 | name='state_to_state'))
247 | self.parameters.append(shared_floatx_nans((self.dim, 2 * self.dim),
248 | name='state_to_gates'))
249 | for i in range(2):
250 | if self.parameters[i]:
251 | add_role(self.parameters[i], WEIGHT)
252 |
253 | @application(outputs=apply.states)
254 | def initial_states(self, batch_size, *args, **kwargs):
255 | return tensor.zeros((batch_size, self.dim))
256 |
257 |
258 | class UpperIGRU(GatedRecurrent):
259 | """ Upper IGRU in interpolator """
260 |
261 | def __init__(self, dim, activation=None, gate_activation=None,
262 | **kwargs):
263 | super(UpperIGRU, self).__init__(dim, activation, gate_activation, **kwargs)
264 |
265 | @recurrent(sequences=['mask', 'inputs', 'gate_inputs'],
266 | states=['states'], outputs=['states'], contexts=[])
267 | def apply(self, inputs, gate_inputs, states, mask=None):
268 | """Apply the gated recurrent transition.
269 | Parameters
270 | ----------
271 | states : :class:`~tensor.TensorVariable`
272 | The 2 dimensional matrix of current states in the shape
273 | (batch_size, dim). Required for `one_step` usage.
274 | inputs : :class:`~tensor.TensorVariable`
275 | The 2 dimensional matrix of inputs in the shape (batch_size,
276 | dim)
277 | gate_inputs : :class:`~tensor.TensorVariable`
278 | The 2 dimensional matrix of inputs to the gates in the
279 | shape (batch_size, 2 * dim).
280 | input_states : :class:`~tensor.TensorVariable`
281 | The 2 dimensional matrix of outputs of decoder in the shape
282 | (batch_size, dim), which generated by decoder.
283 | mask : :class:`~tensor.TensorVariable`
284 | A 1D binary array in the shape (batch,) which is 1 if there is
285 | the charater available, 0 if there is the delimiter.
286 | Returns
287 | -------
288 | output : :class:`~tensor.TensorVariable`
289 | Next states of the network.
290 | """
291 | if mask:
292 | states = (mask[:, None] * states + (1 - mask[:, None]) * self.initial_states(mask.shape[0]))
293 | gate_values = self.gate_activation.apply(
294 | states.dot(self.state_to_gates) + gate_inputs)
295 | update_values = gate_values[:, :self.dim]
296 | reset_values = gate_values[:, self.dim:]
297 | states_reset = states * reset_values
298 | next_states = self.activation.apply(
299 | states_reset.dot(self.state_to_state) + inputs)
300 | next_states = (next_states * update_values +
301 | states * (1 - update_values))
302 |
303 | return next_states
304 |
305 |
306 | class Interpolator(Readout):
307 | def __init__(self, vocab_size, embedding_dim, igru_state_dim, igru_depth, trg_dgru_depth, emitter=None, feedback_brick=None,
308 | merge=None, merge_prototype=None, post_merge=None, merged_dim=None, igru=None, **kwargs):
309 | # for compatible
310 | if igru_depth == 1:
311 | self.igru = IGRU(dim=igru_state_dim)
312 | else:
313 | self.igru = RecurrentStack([IGRU(dim=igru_state_dim, name='igru')] +
314 | [UpperIGRU(dim=igru_state_dim, activation=Tanh(), name='upper_igru' + str(i))
315 | for i in range(1, igru_depth)],
316 | skip_connections=True)
317 | self.igru_depth = igru_depth
318 | self.trg_dgru_depth = trg_dgru_depth
319 | self.lookup = LookupTable(name='embeddings')
320 | self.vocab_size = vocab_size
321 | self.igru_state_dim = igru_state_dim
322 | self.gru_to_softmax = Linear(input_dim=igru_state_dim, output_dim=vocab_size)
323 | self.embedding_dim = embedding_dim
324 | self.gru_fork = Fork([name for name in self.igru.apply.sequences
325 | if name != 'mask' and name != 'input_states'], prototype=Linear(), name='gru_fork')
326 | kwargs['children'] = [self.igru, self.lookup, self.gru_to_softmax, self.gru_fork]
327 | super(Interpolator, self).__init__(emitter=emitter, feedback_brick=feedback_brick, merge=merge,
328 | merge_prototype=merge_prototype, post_merge=post_merge,
329 | merged_dim=merged_dim, **kwargs)
330 |
331 | @application
332 | def initial_igru_outputs(self, batch_size):
333 | return self.igru.initial_states(batch_size)
334 |
335 | def _push_allocation_config(self):
336 | self.lookup.length = self.vocab_size
337 | self.lookup.dim = self.embedding_dim
338 | self.emitter.readout_dim = self.get_dim('readouts')
339 | self.merge.input_names = self.source_names
340 | self.merge.input_dims = self.source_dims
341 | self.merge.output_dim = self.merged_dim
342 | self.post_merge.input_dim = self.merged_dim
343 | self.post_merge.output_dim = self.igru_state_dim
344 | self.gru_fork.input_dim = self.embedding_dim
345 | self.gru_fork.output_dims = [self.igru.get_dim(name)
346 | for name in self.gru_fork.output_names]
347 |
348 | @application(outputs=['feedback'])
349 | def feedback_apply(self, target_char_seq, target_sample_matrix, target_char_aux):
350 | return self.feedback_brick.apply(target_char_seq, target_sample_matrix, target_char_aux)
351 |
352 | @application
353 | def single_feedback(self, target_single_char, batch_size, mask=None, states=None):
354 | return self.feedback_brick.single_emit(target_single_char, batch_size, mask, states)
355 |
356 | @single_feedback.property('outputs')
357 | def single_feedback_outputs(self):
358 | return ['single_feedback' + RECURRENTSTACK_SEPARATOR + str(i) for i in range(self.trg_dgru_depth)]
359 |
360 | @application(outputs=['gru_out', 'readout_chars'])
361 | def single_readout_gru(self, target_prev_char, target_prev_char_aux, input_states, states):
362 | embeddings = self.lookup.apply(target_prev_char)
363 | states_dict = {'states':states[0]}
364 | if self.igru_depth > 1:
365 | for i in range(1, self.igru_depth):
366 | states_dict['states' + RECURRENTSTACK_SEPARATOR +str(i)] = states[i]
367 | gru_out = self.igru.apply(
368 | **merge(self.gru_fork.apply(embeddings, as_dict=True), states_dict,
369 | {'mask': target_prev_char_aux, 'input_states': input_states,
370 | 'iterate': False}))
371 | if self.igru_depth > 1:
372 | readout_chars = self.gru_to_softmax.apply(gru_out[-1])
373 | else:
374 | readout_chars = self.gru_to_softmax.apply(gru_out)
375 | return gru_out, readout_chars
376 |
377 | @application(outputs=['readout_chars'])
378 | def readout_gru(self, target_prev_char_seq, target_prev_char_aux, input_states):
379 | embeddings = self.lookup.apply(target_prev_char_seq)
380 | gru_out = self.igru.apply(
381 | **merge(self.gru_fork.apply(embeddings, as_dict=True),
382 | {'mask': target_prev_char_aux, 'input_states': input_states}))
383 | if self.igru_depth > 1:
384 | gru_out = gru_out[-1]
385 | readout_chars = self.gru_to_softmax.apply(gru_out)
386 | return readout_chars
387 |
388 |
389 | class SequenceGeneratorDCNMT(BaseSequenceGenerator):
390 | """A more user-friendly interface for :class:`BaseSequenceGenerator`. """
391 |
392 | def __init__(self, trg_space_idx, readout, transition, attention=None, transition_depth=1, igru_depth=1, trg_dgru_depth=1,
393 | add_contexts=True, **kwargs):
394 | self.trg_space_idx = trg_space_idx
395 | self.transition_depth = transition_depth
396 | self.igru_depth = igru_depth
397 | self.trg_dgru_depth = trg_dgru_depth
398 | self.igru_states_name = ['igru_states'+RECURRENTSTACK_SEPARATOR+str(i) for i in range(self.igru_depth)]
399 | self.feedback_name = ['feedback'+RECURRENTSTACK_SEPARATOR+str(i) for i in range(self.trg_dgru_depth)]
400 |
401 | normal_inputs = [name for name in transition.apply.sequences
402 | if 'mask' not in name]
403 | kwargs.setdefault('fork', Fork(normal_inputs))
404 | transition = AttentionRecurrent(
405 | transition, attention,
406 | add_contexts=add_contexts, name="att_trans")
407 | super(SequenceGeneratorDCNMT, self).__init__(
408 | readout, transition, **kwargs)
409 |
410 | @application
411 | def cost_matrix_nmt(self, application_call, target_char_seq, target_sample_matrix, target_resample_matrix,
412 | target_word_mask, target_char_aux, target_prev_char_seq, target_prev_char_aux, **kwargs):
413 | """Returns generation costs for output sequences.
414 |
415 | See Also
416 | --------
417 | :meth:`cost` : Scalar cost.
418 |
419 | """
420 | # We assume the data has axes (time, batch, features, ...)
421 | batch_size = target_char_seq.shape[1]
422 |
423 | # Prepare input for the iterative part
424 | states = dict_subset(kwargs, self._state_names, must_have=False)
425 | # masks in context are optional (e.g. `attended_mask`)
426 | contexts = dict_subset(kwargs, self._context_names, must_have=False)
427 | feedback = self.readout.feedback_apply(target_char_seq, target_sample_matrix, target_char_aux)
428 | inputs = self.fork.apply(feedback, as_dict=True)
429 |
430 | # Run the recurrent network
431 | results = self.transition.apply(
432 | mask=target_word_mask, return_initial_states=True, as_dict=True,
433 | **dict_union(inputs, states, contexts))
434 |
435 | # Separate the deliverables. The last states are discarded: they
436 | # are not used to predict any output symbol. The initial glimpses
437 | # are discarded because they are not used for prediction.
438 | # Remember, glimpses are computed _before_ output stage, states are
439 | # computed after.
440 | states = {name: results[name][:-1] for name in self._state_names}
441 | glimpses = {name: results[name][1:] for name in self._glimpse_names}
442 |
443 | feedback = tensor.roll(feedback, 1, 0)
444 | if self.trg_dgru_depth == 1:
445 | feedback = tensor.set_subtensor(
446 | feedback[0],
447 | self.readout.single_feedback(self.readout.initial_outputs(batch_size), batch_size))
448 | else:
449 | feedback = tensor.set_subtensor(
450 | feedback[0],
451 | self.readout.single_feedback(self.readout.initial_outputs(batch_size), batch_size)[-1])
452 |
453 | decoder_readout_outputs = self.readout.readout(
454 | feedback=feedback, **dict_union(states, glimpses, contexts))
455 | resampled_representation = tensor.batched_dot(target_resample_matrix,
456 | decoder_readout_outputs.dimshuffle([1, 0, 2]))
457 | resampled_readouts = resampled_representation.dimshuffle([1, 0, 2])
458 | readouts_chars = self.readout.readout_gru(target_prev_char_seq, target_prev_char_aux, resampled_readouts)
459 |
460 | # Compute the cost
461 | costs = self.readout.cost(readouts_chars, target_char_seq)
462 |
463 | for name, variable in list(glimpses.items()) + list(states.items()):
464 | application_call.add_auxiliary_variable(
465 | variable.copy(), name=name)
466 |
467 | # This variables can be used to initialize the initial states of the
468 | # next batch using the last states of the current batch.
469 | for name in self._state_names + self._glimpse_names:
470 | application_call.add_auxiliary_variable(
471 | results[name][-1].copy(), name=name + "_final_value")
472 |
473 | return costs
474 |
475 | @recurrent
476 | def generate(self, outputs, **kwargs):
477 | """A sequence generation step.
478 |
479 | Parameters
480 | ----------
481 | outputs : :class:`~tensor.TensorVariable`
482 | The outputs from the previous step.
483 |
484 | Notes
485 | -----
486 | The contexts, previous states and glimpses are expected as keyword
487 | arguments.
488 |
489 | """
490 | states = dict_subset(kwargs, self._state_names)
491 | # masks in context are optional (e.g. `attended_mask`)
492 | contexts = dict_subset(kwargs, self._context_names, must_have=False)
493 | glimpses = dict_subset(kwargs, self._glimpse_names)
494 | feedback = dict_subset(kwargs, self.feedback_name)
495 | readout_feedback = dict_subset(kwargs, ['readout_feedback'])['readout_feedback']
496 | batch_size = outputs.shape[0]
497 | igru_states = dict_subset(kwargs, self.igru_states_name)
498 |
499 | next_glimpses = self.transition.take_glimpses(
500 | as_dict=True, **dict_union(states, glimpses, contexts))
501 |
502 | next_readouts = self.readout.readout(
503 | feedback=readout_feedback,
504 | **dict_union(states, next_glimpses, contexts))
505 |
506 | next_char_aux = 1 - tensor.eq(outputs, 0) - tensor.eq(outputs, self.trg_space_idx)
507 | next_igru_states, readout_chars = self.readout.single_readout_gru(outputs, next_char_aux, next_readouts,
508 | [igru_states[self.igru_states_name[i]] for i in range(self.igru_depth)])
509 | next_outputs = self.readout.emit(readout_chars)
510 | next_costs = self.readout.cost(readout_chars, next_outputs)
511 |
512 | update_next = tensor.eq(next_outputs, self.trg_space_idx)
513 | next_char_mask = 1 - update_next
514 | update_next = update_next[:, None]
515 | next_readout_feedback = (1 - update_next) * readout_feedback + update_next * feedback[self.feedback_name[-1]]
516 |
517 | next_feedback = self.readout.single_feedback(next_outputs, batch_size, next_char_mask,
518 | [feedback[self.feedback_name[i]] for i in range(self.trg_dgru_depth)])
519 |
520 | next_inputs = (self.fork.apply(next_readout_feedback, as_dict=True)
521 | if self.fork else {'feedback': next_readout_feedback})
522 | next_states = self.transition.compute_states(
523 | as_list=True,
524 | **dict_union(next_inputs, states, next_glimpses, contexts))
525 |
526 | next_states[0] = update_next * next_states[0] + (1 - update_next) * states['states']
527 | for i in range(1, self.transition_depth):
528 | next_states[i] = update_next * next_states[i] + (1 - update_next) * states['states' + RECURRENTSTACK_SEPARATOR + str(i)]
529 |
530 | next_glimpses['weights'] = update_next * next_glimpses['weights'] + (1 - update_next) * glimpses['weights']
531 | next_glimpses['weighted_averages'] = update_next * next_glimpses['weighted_averages'] + \
532 | (1 - update_next) * glimpses['weighted_averages']
533 | # combine all updates
534 | next_all = list(next_states) + [next_outputs] + list(next_glimpses.values())
535 | if self.trg_dgru_depth > 1:
536 | next_all += list(next_feedback)
537 | else:
538 | next_all += [next_feedback]
539 | if self.igru_depth > 1:
540 | next_all += list(next_igru_states)
541 | else:
542 | next_all += [next_igru_states]
543 | next_all += [next_readout_feedback] + [next_costs]
544 |
545 | return (next_all)
546 |
547 | @generate.delegate
548 | def generate_delegate(self):
549 | return self.transition.apply
550 |
551 | @generate.property('outputs')
552 | def generate_outputs(self):
553 | return self._state_names + ['outputs'] + self._glimpse_names + \
554 | self.feedback_name + self.igru_states_name + ['readout_feedback', 'cost']
555 |
556 | @generate.property('states')
557 | def generate_states(self):
558 | return self._state_names + ['outputs'] + self._glimpse_names + \
559 | self.feedback_name + self.igru_states_name + ['readout_feedback']
560 |
561 | def get_dim(self, name):
562 | if name in (self._state_names + self._context_names + self._glimpse_names):
563 | return self.transition.get_dim(name)
564 | elif name == 'outputs' or name in self.feedback_name or name == 'readout_feedback' or name in self.igru_states_name:
565 | return self.readout.get_dim('outputs')
566 | return super(BaseSequenceGenerator, self).get_dim(name)
567 |
568 | @application
569 | def initial_states(self, batch_size, *args, **kwargs):
570 | # TODO: support dict of outputs for application methods
571 | # to simplify this code.
572 | igru_initial_states = self.readout.initial_igru_outputs(batch_size)
573 | if self.igru_depth == 1:
574 | igru_initial_states_dict = {self.igru_states_name[0]:igru_initial_states}
575 | else:
576 | igru_initial_states_dict = {self.igru_states_name[i]:igru_initial_states[i]
577 | for i in range(self.igru_depth)}
578 |
579 | initial_outputs=self.readout.initial_outputs(batch_size)
580 | feedback = self.readout.single_feedback(initial_outputs, batch_size)
581 | if self.trg_dgru_depth == 1:
582 | feedback_dict = {self.feedback_name[0]:feedback, 'readout_feedback':feedback}
583 | else:
584 | feedback_dict = {'readout_feedback':feedback[-1]}
585 | feedback_dict.update({self.feedback_name[i]:feedback[i] for i in range(self.trg_dgru_depth)})
586 |
587 | state_dict = dict(
588 | self.transition.initial_states(
589 | batch_size, as_dict=True, *args, **kwargs),
590 | outputs=initial_outputs)
591 | state_dict.update(feedback_dict)
592 | state_dict.update(igru_initial_states_dict)
593 | return [state_dict[state_name]
594 | for state_name in self.generate.states]
595 |
596 | @initial_states.property('outputs')
597 | def initial_states_outputs(self):
598 | return self.generate.states
599 |
600 |
601 | class GRUInitialState(GatedRecurrent):
602 | """Gated Recurrent with special initial state.
603 |
604 | Initial state of Gated Recurrent is set by an MLP that conditions on the
605 | first hidden state of the bidirectional encoder, applies an affine
606 | transformation followed by a tanh non-linearity to set initial state.
607 |
608 | """
609 |
610 | def __init__(self, attended_dim, **kwargs):
611 | super(GRUInitialState, self).__init__(**kwargs)
612 | self.attended_dim = attended_dim
613 | self.initial_transformer = MLP(activations=[Tanh()],
614 | dims=[attended_dim, self.dim],
615 | name='state_initializer')
616 | self.children.append(self.initial_transformer)
617 |
618 | @application
619 | def initial_states(self, batch_size, *args, **kwargs):
620 | attended = kwargs['attended']
621 | initial_state = self.initial_transformer.apply(
622 | attended[0, :, -self.attended_dim:])
623 | return initial_state
624 |
625 | def _allocate(self):
626 | self.parameters.append(shared_floatx_nans((self.dim, self.dim),
627 | name='state_to_state'))
628 | self.parameters.append(shared_floatx_nans((self.dim, 2 * self.dim),
629 | name='state_to_gates'))
630 | for i in range(2):
631 | if self.parameters[i]:
632 | add_role(self.parameters[i], WEIGHT)
633 |
634 |
635 | class Decoder(Initializable):
636 | """Decoder of dcnmt model."""
637 |
638 | def __init__(self, vocab_size, embedding_dim, dgru_state_dim, igru_state_dim, state_dim,
639 | representation_dim, transition_depth, trg_igru_depth, trg_dgru_depth, trg_space_idx, trg_bos,
640 | theano_seed=None, **kwargs):
641 | super(Decoder, self).__init__(**kwargs)
642 | self.vocab_size = vocab_size
643 | self.embedding_dim = embedding_dim
644 | self.dgru_state_dim = dgru_state_dim
645 | self.igru_state_dim = igru_state_dim
646 | self.state_dim = state_dim
647 | self.trg_space_idx = trg_space_idx
648 | self.representation_dim = representation_dim
649 | self.theano_seed = theano_seed
650 |
651 | # Initialize gru with special initial state
652 | self.transition = RecurrentStack(
653 | [GRUInitialState(attended_dim=state_dim, dim=state_dim, activation=Tanh(), name='decoder_gru_withinit')] +
654 | [GatedRecurrent(dim=state_dim, activation=Tanh(), name='decoder_gru' + str(i))
655 | for i in range(1, transition_depth)], skip_connections=True)
656 |
657 | # Initialize the attention mechanism
658 | self.attention = SequenceContentAttention(
659 | state_names=self.transition.apply.states,
660 | attended_dim=representation_dim,
661 | match_dim=state_dim, name="attention")
662 |
663 | self.interpolator = Interpolator(
664 | vocab_size=vocab_size,
665 | embedding_dim=embedding_dim,
666 | igru_state_dim=igru_state_dim,
667 | igru_depth=trg_igru_depth,
668 | trg_dgru_depth=trg_dgru_depth,
669 | source_names=['states', 'feedback', self.attention.take_glimpses.outputs[0]],
670 | readout_dim=self.vocab_size,
671 | emitter=SoftmaxEmitter(initial_output=trg_bos, theano_seed=theano_seed),
672 | feedback_brick=Decimator(vocab_size, embedding_dim, self.dgru_state_dim, trg_dgru_depth),
673 | post_merge=InitializableFeedforwardSequence([Identity().apply]),
674 | merged_dim=igru_state_dim)
675 |
676 | # Build sequence generator accordingly
677 | self.sequence_generator = SequenceGeneratorDCNMT(
678 | trg_space_idx=self.trg_space_idx,
679 | readout=self.interpolator,
680 | transition=self.transition,
681 | attention=self.attention,
682 | transition_depth=transition_depth,
683 | igru_depth=trg_igru_depth,
684 | trg_dgru_depth=trg_dgru_depth,
685 | fork=Fork([name for name in self.transition.apply.sequences
686 | if name != 'mask'], prototype=Linear())
687 | )
688 | self.children = [self.sequence_generator]
689 |
690 | @application(inputs=['representation', 'source_word_mask', 'target_char_seq', 'target_sample_matrix',
691 | 'target_resample_matrix', 'target_char_aux', 'target_char_mask', 'target_word_mask',
692 | 'target_prev_char_seq', 'target_prev_char_aux'],
693 | outputs=['cost'])
694 | def cost(self, representation, source_word_mask, target_char_seq, target_sample_matrix,
695 | target_resample_matrix, target_char_aux, target_char_mask, target_word_mask,
696 | target_prev_char_seq, target_prev_char_aux):
697 | source_word_mask = source_word_mask.T
698 | target_char_seq = target_char_seq.T
699 | target_prev_char_seq = target_prev_char_seq.T
700 | target_char_mask = target_char_mask.T
701 | target_char_aux = target_char_aux.T
702 | target_prev_char_aux = target_prev_char_aux.T
703 | target_word_mask = target_word_mask.T
704 |
705 | # Get the cost matrix
706 | cost = self.sequence_generator.cost_matrix_nmt(**{
707 | 'target_char_seq': target_char_seq,
708 | 'target_sample_matrix': target_sample_matrix,
709 | 'target_resample_matrix': target_resample_matrix,
710 | 'target_word_mask': target_word_mask,
711 | 'target_char_aux': target_char_aux,
712 | 'target_prev_char_seq': target_prev_char_seq,
713 | 'target_prev_char_aux': target_prev_char_aux,
714 | 'attended': representation,
715 | 'attended_mask': source_word_mask})
716 |
717 | return (cost * target_char_mask).sum() / target_char_mask.shape[1]
718 |
719 | @application
720 | def generate(self, representation, attended_mask, **kwargs):
721 | return self.sequence_generator.generate(
722 | n_steps=10 * attended_mask.shape[1],
723 | batch_size=attended_mask.shape[0],
724 | attended=representation,
725 | attended_mask=attended_mask.T,
726 | **kwargs)
727 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------