Thamme Gowda, April 27, 2018
With Help from http://pytorch.org/tutorials/beginner/nlp/advanced_tutorial.html#bi-lstm-conditional-random-field-discussion
In [46]:
import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import os
torch.manual_seed(1)
print(f'Torch Version {torch.__version__}')
assert int(torch.__version__.split('.')[1]) >= 4 # should be greater than equal to 0.4
print(f'Cuda is available: {torch.cuda.is_available()}')
print(f'CUDA_VISIBLE_DEVICES : {os.environ["CUDA_VISIBLE_DEVICES"]}')
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(device)
def tensor(*args, **kwargs):
return torch.tensor(*args, device=DEVICE, **kwargs)
In [49]:
# Helper Functions
def argmax(vec):
# return the argmax as a python int
_, idx = torch.max(vec, 1)
return idx.item()
# Compute log sum exp in a numerically stable way for the forward algorithm
def log_sum_exp(vec):
max_score = vec[0, argmax(vec)]
max_score_broadcast = max_score.view(1, -1).expand(1, vec.size()[1])
return max_score + torch.log(torch.sum(torch.exp(vec - max_score_broadcast)))
In [50]:
class LSTMFeaturizer(nn.Module):
def __init__(self, embedding_dim, hidden_dim, tok2idx, device=DEVICE,
num_layers=1, num_directions=2, UNK='-UNK-'):
super(LSTMFeaturizer, self).__init__()
self.device = device
self.n_layers = num_layers
self.n_dirs = num_directions
self.embedding_dim = embedding_dim
self.hidden_dim = hidden_dim
self._feat_dim = self.n_dirs * self.hidden_dim
assert type(tok2idx) is dict
assert UNK in tok2idx, f'{UNK} index should be reserved for Unknown characters'
self.unk_tok_idx = tok2idx[UNK]
self.tok2idx = tok2idx
self.embed = nn.Embedding(len(tok2idx), embedding_dim)
self.lstm = nn.LSTM(embedding_dim, hidden_dim, num_layers=self.n_layers,
bidirectional=self.n_dirs==2)
def init_hidden(self, batch_size=1):
# The axes semantics are (num_layers*directions, minibatch_size, hidden_dim)
return (torch.zeros(self.n_layers * self.n_dirs, batch_size, self.hidden_dim, device=self.device),
torch.zeros(self.n_layers * self.n_dirs, batch_size, self.hidden_dim, device=self.device))
def forward(self, sequence):
hidden = self.init_hidden()
tok_ixs = [self.tok2idx.get(tok, self.unk_tok_idx) for tok in sequence]
embeds = self.embed(tensor(tok_ixs, dtype=torch.long))
seq_repr, _ = self.lstm(embeds.view(len(sequence), 1, -1), hidden)
return seq_repr
class BiLSTM_CRF(nn.Module):
def __init__(self, embedding_dim, hidden_dim, word_to_ix, char_to_ix, tag_to_ix, debug=True):
super(BiLSTM_CRF, self).__init__()
self.debug = debug
self.tag_to_ix = tag_to_ix
self.ix_to_tag = {ix:tag for tag,ix in tag_to_ix.items()}
self.word_to_idx = word_to_ix
self.tagset_size = len(tag_to_ix)
self.hidden_dim = hidden_dim
self.word_featurizer = LSTMFeaturizer(embedding_dim, hidden_dim //2, word_to_ix)
self.char_featurizer = LSTMFeaturizer(embedding_dim, hidden_dim //2, char_to_ix)
# TODO: Merged LSTM for word and char features
#self.merged_lstm = nn.LSTM(2 * hidden_dim, hidden_dim, num_layers=1, bidirectional=True)
# Maps the output of the LSTM into tag space.
self.hidden2tag = nn.Linear(2 * hidden_dim, self.tagset_size)
# Matrix of transition parameters. Entry i,j is the score of
# transitioning *to* i *from* j.
self.transitions = nn.Parameter(torch.randn(self.tagset_size, self.tagset_size, device=device))
# These two statements enforce the constraint that we never transfer
# to the start tag and we never transfer from the stop tag
self.transitions.data[tag_to_ix[START_TAG], :] = -10000
self.transitions.data[:, tag_to_ix[STOP_TAG]] = -10000
def init_hidden(self):
return (torch.randn(2, 1, self.hidden_dim // 2, device=device),
torch.randn(2, 1, self.hidden_dim // 2, device=device))
def _forward_alg(self, feats):
# Do the forward algorithm to compute the partition function
init_alphas = torch.full((1, self.tagset_size), -10000., device=device)
# START_TAG has all of the score.
init_alphas[0][self.tag_to_ix[START_TAG]] = 0.
# Wrap in a variable so that we will get automatic backprop
forward_var = init_alphas
# Iterate through the sentence
for feat in feats:
alphas_t = [] # The forward tensors at this timestep
for next_tag in range(self.tagset_size):
# broadcast the emission score: it is the same regardless of
# the previous tag
emit_score = feat[next_tag].view(1, -1).expand(1, self.tagset_size)
# the ith entry of trans_score is the score of transitioning to
# next_tag from i
trans_score = self.transitions[next_tag].view(1, -1)
# The ith entry of next_tag_var is the value for the
# edge (i -> next_tag) before we do log-sum-exp
next_tag_var = forward_var + trans_score + emit_score
# The forward variable for this tag is log-sum-exp of all the
# scores.
alphas_t.append(log_sum_exp(next_tag_var).view(1))
forward_var = torch.cat(alphas_t).view(1, -1)
terminal_var = forward_var + self.transitions[self.tag_to_ix[STOP_TAG]]
alpha = log_sum_exp(terminal_var)
return alpha
def _get_lstm_features(self, sentence):
'''
sentence = prepare_sequence(sentence, self.word_to_idx)
self.hidden = self.init_hidden()
embeds = self.word_embeds(sentence).view(len(sentence), 1, -1)
lstm_out, self.hidden = self.lstm(embeds, self.hidden)
'''
word_feats = self.word_featurizer(sentence)
word_feats = word_feats.view(len(sentence), self.hidden_dim)
# TODO: characters in a batch
char_feats = [self.char_featurizer(word)[-1] for word in sentence]
char_feats = torch.cat(char_feats, dim=0) # cocat one below the other
if self.debug:
assert char_feats.size()[0] == word_feats.size()[0]
merged_feats = torch.cat([word_feats,char_feats], dim=1) # concat side by side
lstm_feats = self.hidden2tag(merged_feats)
return lstm_feats
def _score_sentence(self, feats, tags):
# Gives the score of a provided tag sequence
score = torch.zeros(1, device=device)
tags = torch.cat([torch.tensor([self.tag_to_ix[START_TAG]], dtype=torch.long, device=device), tags])
for i, feat in enumerate(feats):
score = score + self.transitions[tags[i + 1], tags[i]] + feat[tags[i + 1]]
score = score + self.transitions[self.tag_to_ix[STOP_TAG], tags[-1]]
return score
def _viterbi_decode(self, feats):
backpointers = []
# Initialize the viterbi variables in log space
init_vvars = torch.full((1, self.tagset_size), -10000., device=device)
init_vvars[0][self.tag_to_ix[START_TAG]] = 0
# forward_var at step i holds the viterbi variables for step i-1
forward_var = init_vvars
for feat in feats:
bptrs_t = [] # holds the backpointers for this step
viterbivars_t = [] # holds the viterbi variables for this step
for next_tag in range(self.tagset_size):
# next_tag_var[i] holds the viterbi variable for tag i at the
# previous step, plus the score of transitioning
# from tag i to next_tag.
# We don't include the emission scores here because the max
# does not depend on them (we add them in below)
next_tag_var = forward_var + self.transitions[next_tag]
best_tag_id = argmax(next_tag_var)
bptrs_t.append(best_tag_id)
viterbivars_t.append(next_tag_var[0][best_tag_id].view(1))
# Now add in the emission scores, and assign forward_var to the set
# of viterbi variables we just computed
forward_var = (torch.cat(viterbivars_t) + feat).view(1, -1)
backpointers.append(bptrs_t)
# Transition to STOP_TAG
terminal_var = forward_var + self.transitions[self.tag_to_ix[STOP_TAG]]
best_tag_id = argmax(terminal_var)
path_score = terminal_var[0][best_tag_id]
# Follow the back pointers to decode the best path.
best_path = [best_tag_id]
for bptrs_t in reversed(backpointers):
best_tag_id = bptrs_t[best_tag_id]
best_path.append(best_tag_id)
# Pop off the start tag (we dont want to return that to the caller)
start = best_path.pop()
assert start == self.tag_to_ix[START_TAG] # Sanity check
best_path.reverse()
return path_score, best_path
def neg_log_likelihood(self, sentence, tags):
feats = self._get_lstm_features(sentence)
forward_score = self._forward_alg(feats)
gold_score = self._score_sentence(feats, tags)
return forward_score - gold_score
def forward(self, sentence): # dont confuse this with _forward_alg above.
# Get the emission scores from the BiLSTM
lstm_feats = self._get_lstm_features(sentence)
# Find the best path, given the features.
score, tag_seq = self._viterbi_decode(lstm_feats)
return score, tag_seq
def tag(self, sentence):
score, idx = self(sentence)
return score.item(), [self.ix_to_tag[i] for i in idx]
In [52]:
START_TAG = "<START>"
STOP_TAG = "<STOP>"
EMBEDDING_DIM = 5
HIDDEN_DIM = 4
# Make up some training data
training_data = [(
"the wall street journal reported today that apple corporation made money".split(),
"B I I I O O O B I O O".split()
), (
"georgia tech is a university in georgia".split(),
"B I O O O O B".split()
)]
word_to_ix = {'-UNK-': 0}
for sentence, tags in training_data:
for word in sentence:
if word not in word_to_ix:
word_to_ix[word] = len(word_to_ix)
tag_to_ix = {"B": 0, "I": 1, "O": 2, START_TAG: 3, STOP_TAG: 4}
char_to_ix= {'-UNK-': 0}
uniq_chars = {ch for sent, _ in training_data for word in sent for ch in word}
for ch in uniq_chars:
char_to_ix[ch] = len(char_to_ix)
model = BiLSTM_CRF(EMBEDDING_DIM, HIDDEN_DIM, word_to_ix, char_to_ix, tag_to_ix).to(device)
optimizer = optim.SGD(model.parameters(), lr=0.01, weight_decay=1e-4)
# Check predictions before training
with torch.no_grad():
check_sent = training_data[0][0]
print(check_sent)
print(model.tag(check_sent))
# Make sure prepare_sequence from earlier in the LSTM section is loaded
for epoch in range(300): # again, normally you would NOT do 300 epochs, it is toy data
for sentence, tags in training_data:
# Step 1. Remember that Pytorch accumulates gradients.
# We need to clear them out before each instance
model.zero_grad()
# Step 2. Get our inputs ready for the network, that is,
# turn them into Tensors of word indices.
#sentence_in = prepare_sequence(sentence, word_to_ix)
targets = tensor([tag_to_ix[t] for t in tags])
# Step 3. Run our forward pass.
loss = model.neg_log_likelihood(sentence, targets)
# Step 4. Compute the loss, gradients, and update the parameters by
# calling optimizer.step()
loss.backward()
optimizer.step()
# Check predictions after training
with torch.no_grad():
print(model.tag(check_sent))
print("Gold Tags:", training_data[0][1])
In [ ]: