Skip to content

Commit 8511795

Browse files
author
Tarry Singh
committed
2 parents a18fe5b + f130543 commit 8511795

File tree

2,424 files changed

+1131416
-1
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

2,424 files changed

+1131416
-1
lines changed

.gitignore

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,4 +57,8 @@ target/
5757
.ipynb_checkpoints
5858

5959
# Repo scratch directory
60-
scratch/
60+
scratch/
61+
.DS_Store
62+
deep-learning/.DS_Store
63+
.DS_Store
64+
deep-learning/.DS_Store

deep-learning/NLP/.DS_Store

2 KB
Binary file not shown.
12 MB
Binary file not shown.
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
2+
Version 2, December 2004
3+
4+
Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>
5+
6+
Everyone is permitted to copy and distribute verbatim or modified
7+
copies of this license document, and changing it is allowed as long
8+
as the name is changed.
9+
10+
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
11+
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
12+
13+
0. You just DO WHAT THE FUCK YOU WANT TO.
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# Sequence to Sequence models with PyTorch
2+
3+
This repository contains implementations of Sequence to Sequence (Seq2Seq) models in PyTorch
4+
5+
At present it has implementations for :
6+
7+
* Vanilla Sequence to Sequence models
8+
9+
* Attention based Sequence to Sequence models from https://arxiv.org/abs/1409.0473 and https://arxiv.org/abs/1508.04025
10+
11+
* Faster attention mechanisms using dot products between the **final** encoder and decoder hidden states
12+
13+
* Sequence to Sequence autoencoders (experimental)
14+
15+
## Sequence to Sequence models
16+
17+
A vanilla sequence to sequence model presented in https://arxiv.org/abs/1409.3215, https://arxiv.org/abs/1406.1078 consits of using a recurrent neural network such as an LSTM (http://dl.acm.org/citation.cfm?id=1246450) or GRU (https://arxiv.org/abs/1412.3555) to encode a sequence of words or characters in a *source* language into a fixed length vector representation and then deocoding from that representation using another RNN in the *target* language.
18+
19+
![Sequence to Sequence](/images/Seq2Seq.png)
20+
21+
An extension of sequence to sequence models that incorporate an attention mechanism was presented in https://arxiv.org/abs/1409.0473 that uses information from the RNN hidden states in the source language at each time step in the deocder RNN. This attention mechanism significantly improves performance on tasks like machine translation. A few variants of the attention model for the task of machine translation have been presented in https://arxiv.org/abs/1508.04025.
22+
23+
![Sequence to Sequence with attention](/images/Seq2SeqAttention.png)
24+
25+
The repository also contains a simpler and faster variant of the attention mechanism that doesn't attend over the hidden states of the encoder at each time step in the deocder. Instead, it computes the a single batched dot product between all the hidden states of the decoder and encoder once after the decoder has processed all inputs in the target. This however comes at a minor cost in model performance. One advantage of this model is that it is possible to use the cuDNN LSTM in the attention based decoder as well since the attention is computed after running through all the inputs in the decoder.
26+
27+
## Results on English - French WMT14
28+
29+
The following presents the model architecture and results obtained when training on the WMT14 English - French dataset. The training data is the english-french bitext from Europral-v7. The validation dataset is newstest2011
30+
31+
The model was trained with following configuration
32+
33+
* Source and target word embedding dimensions - 512
34+
35+
* Source and target LSTM hidden dimensions - 1024
36+
37+
* Encoder - 2 Layer Bidirectional LSTM
38+
39+
* Decoder - 1 Layer LSTM
40+
41+
* Optimization - ADAM with a learning rate of 0.0001 and batch size of 80
42+
43+
* Decoding - Greedy decoding (argmax)
44+
45+
46+
| Model | BLEU | Train Time Per Epoch |
47+
| ------------- | ------------- | ------------- |
48+
| Seq2Seq | 11.82 | 2h 50min |
49+
| Seq2Seq FastAttention | 18.89 | 3h 45min |
50+
| Seq2Seq Attention | 22.60 | 4h 47min |
51+
52+
Times reported are using a Pre 2016 Nvidia GeForce Titan X
53+
54+
## Running
55+
56+
To run, edit the config file and execute python nmt.py --config <your_config_file>
57+
58+
NOTE: This only runs on a GPU for now.
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
"""Beam search implementation in PyTorch."""
2+
#
3+
#
4+
# hyp1#-hyp1---hyp1 -hyp1
5+
# \ /
6+
# hyp2 \-hyp2 /-hyp2#hyp2
7+
# / \
8+
# hyp3#-hyp3---hyp3 -hyp3
9+
# ========================
10+
#
11+
# Takes care of beams, back pointers, and scores.
12+
13+
# Code borrowed from PyTorch OpenNMT example
14+
# https://github.com/pytorch/examples/blob/master/OpenNMT/onmt/Beam.py
15+
16+
import torch
17+
18+
19+
class Beam(object):
20+
"""Ordered beam of candidate outputs."""
21+
22+
def __init__(self, size, vocab, cuda=False):
23+
"""Initialize params."""
24+
self.size = size
25+
self.done = False
26+
self.pad = vocab['<pad>']
27+
self.bos = vocab['<s>']
28+
self.eos = vocab['</s>']
29+
self.tt = torch.cuda if cuda else torch
30+
31+
# The score for each translation on the beam.
32+
self.scores = self.tt.FloatTensor(size).zero_()
33+
34+
# The backpointers at each time-step.
35+
self.prevKs = []
36+
37+
# The outputs at each time-step.
38+
self.nextYs = [self.tt.LongTensor(size).fill_(self.pad)]
39+
self.nextYs[0][0] = self.bos
40+
41+
# The attentions (matrix) for each time.
42+
self.attn = []
43+
44+
# Get the outputs for the current timestep.
45+
def get_current_state(self):
46+
"""Get state of beam."""
47+
return self.nextYs[-1]
48+
49+
# Get the backpointers for the current timestep.
50+
def get_current_origin(self):
51+
"""Get the backpointer to the beam at this step."""
52+
return self.prevKs[-1]
53+
54+
# Given prob over words for every last beam `wordLk` and attention
55+
# `attnOut`: Compute and update the beam search.
56+
#
57+
# Parameters:
58+
#
59+
# * `wordLk`- probs of advancing from the last step (K x words)
60+
# * `attnOut`- attention at the last step
61+
#
62+
# Returns: True if beam search is complete.
63+
64+
def advance(self, workd_lk):
65+
"""Advance the beam."""
66+
num_words = workd_lk.size(1)
67+
68+
# Sum the previous scores.
69+
if len(self.prevKs) > 0:
70+
beam_lk = workd_lk + self.scores.unsqueeze(1).expand_as(workd_lk)
71+
else:
72+
beam_lk = workd_lk[0]
73+
74+
flat_beam_lk = beam_lk.view(-1)
75+
76+
bestScores, bestScoresId = flat_beam_lk.topk(self.size, 0, True, True)
77+
self.scores = bestScores
78+
79+
# bestScoresId is flattened beam x word array, so calculate which
80+
# word and beam each score came from
81+
prev_k = bestScoresId / num_words
82+
self.prevKs.append(prev_k)
83+
self.nextYs.append(bestScoresId - prev_k * num_words)
84+
85+
# End condition is when top-of-beam is EOS.
86+
if self.nextYs[-1][0] == self.eos:
87+
self.done = True
88+
89+
return self.done
90+
91+
def sort_best(self):
92+
"""Sort the beam."""
93+
return torch.sort(self.scores, 0, True)
94+
95+
# Get the score of the best in the beam.
96+
def get_best(self):
97+
"""Get the most likely candidate."""
98+
scores, ids = self.sort_best()
99+
return scores[1], ids[1]
100+
101+
# Walk back to construct the full hypothesis.
102+
#
103+
# Parameters.
104+
#
105+
# * `k` - the position in the beam to construct.
106+
#
107+
# Returns.
108+
#
109+
# 1. The hypothesis
110+
# 2. The attention at each time step.
111+
def get_hyp(self, k):
112+
"""Get hypotheses."""
113+
hyp = []
114+
# print(len(self.prevKs), len(self.nextYs), len(self.attn))
115+
for j in range(len(self.prevKs) - 1, -1, -1):
116+
hyp.append(self.nextYs[j + 1][k])
117+
k = self.prevKs[j][k]
118+
119+
return hyp[::-1]
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
{
2+
"training": {
3+
"optimizer": "adam",
4+
"clip_c": 1,
5+
"lrate": 0.0002,
6+
},
7+
"management": {
8+
"monitor_loss": 1000,
9+
"print_samples": 20000
10+
},
11+
"data": {
12+
"src": "/data/lisatmp4/subramas/datasets/1-billion-words/all-1-billion-words-train.en.train",
13+
"test_src": "/data/lisatmp4/subramas/datasets/1-billion-words/all-1-billion-words-train.en.dev",
14+
"batch_size": 80,
15+
"valid_batch_size": 80,
16+
"n_words_src": 30000,
17+
"max_src_length": 50,
18+
"task": "autoencode",
19+
"save_dir": "/data/lisatmp4/subramas/models/torch_seq2seq",
20+
"load_dir": false
21+
},
22+
"model": {
23+
"dim": 1024,
24+
"dim_trg": 1024,
25+
"use_dropout": false,
26+
"dim_word_src": 512,
27+
"n_words_src": 30000,
28+
"n_words": 30000,
29+
"dim_word_trg": 512,
30+
"n_layers_src": 2,
31+
"n_layers_trg": 1,
32+
"bidirectional": true,
33+
"src_lang": "en",
34+
"trg_lang": "en",
35+
"decode": "greedy",
36+
"seq2seq": "vanilla",
37+
"optimizer": "adam"
38+
}
39+
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
{
2+
"training": {
3+
"optimizer": "adam",
4+
"clip_c": 1,
5+
"lrate": 0.0001
6+
},
7+
"management": {
8+
"monitor_loss": 1000,
9+
"print_samples": 20000
10+
},
11+
"data": {
12+
"src": "/data/lisatmp4/subramas/datasets/nmt/en-fr/data/europarl-v7.fr-en.tok.true.clean.fr",
13+
"trg": "/data/lisatmp4/subramas/datasets/nmt/en-fr/data/europarl-v7.fr-en.tok.true.clean.en",
14+
"test_src": "/data/lisatmp4/subramas/datasets/nmt/en-fr/data/newstest2011.fr.true.tok",
15+
"test_trg": "/data/lisatmp4/subramas/datasets/nmt/en-fr/data/newstest2011.en.true.tok",
16+
"batch_size": 80,
17+
"n_words_trg": 30000,
18+
"valid_batch_size": 80,
19+
"n_words_src": 30000,
20+
"max_src_length": 50,
21+
"max_trg_length": 50,
22+
"task": "translation",
23+
"save_dir": "/data/lisatmp4/subramas/models/torch_seq2seq",
24+
"load_dir": false
25+
},
26+
"model": {
27+
"dim": 1000,
28+
"dim_trg": 1000,
29+
"use_dropout": false,
30+
"dim_word_src": 500,
31+
"n_words_src": 30000,
32+
"n_words": 30000,
33+
"dim_word_trg": 500,
34+
"n_layers_src": 2,
35+
"n_layers_trg": 1,
36+
"bidirectional": true,
37+
"src_lang": "fr",
38+
"trg_lang": "en",
39+
"decode": "greedy",
40+
"seq2seq": "attention",
41+
"optimizer": "adam"
42+
}
43+
}

0 commit comments

Comments
 (0)