Update draft of parser neural network model
Model is good, but code is messy. Currently requires Chainer, which may cause the build to fail on machines without a GPU.
Outline of the model:
We first predict context-sensitive vectors for each word in the input:
(embed_lower | embed_prefix | embed_suffix | embed_shape)
>> Maxout(token_width)
>> convolution ** 4
This convolutional layer is shared between the tagger and the parser. This prevents the parser from needing tag features.
To boost the representation, we make a "super tag" with POS, morphology and dependency label. The tagger predicts this
by adding a softmax layer onto the convolutional layer --- so, we're teaching the convolutional layer to give us a
representation that's one affine transform from this informative lexical information. This is obviously good for the
parser (which backprops to the convolutions too).
The parser model makes a state vector by concatenating the vector representations for its context tokens. Current
results suggest few context tokens works well. Maybe this is a bug.
The current context tokens:
* S0, S1, S2: Top three words on the stack
* B0, B1: First two words of the buffer
* S0L1, S0L2: Leftmost and second leftmost children of S0
* S0R1, S0R2: Rightmost and second rightmost children of S0
* S1L1, S1L2, S1R2, S1R, B0L1, B0L2: Likewise for S1 and B0
This makes the state vector quite long: 13*T, where T is the token vector width (128 is working well). Fortunately,
there's a way to structure the computation to save some expense (and make it more GPU friendly).
The parser typically visits 2*N states for a sentence of length N (although it may visit more, if it back-tracks
with a non-monotonic transition). A naive implementation would require 2*N (B, 13*T) @ (13*T, H) matrix multiplications
for a batch of size B. We can instead perform one (B*N, T) @ (T, 13*H) multiplication, to pre-compute the hidden
weights for each positional feature wrt the words in the batch. (Note that our token vectors come from the CNN
-- so we can't play this trick over the vocabulary. That's how Stanford's NN parser works --- and why its model
is so big.)
This pre-computation strategy allows a nice compromise between GPU-friendliness and implementation simplicity.
The CNN and the wide lower layer are computed on the GPU, and then the precomputed hidden weights are moved
to the CPU, before we start the transition-based parsing process. This makes a lot of things much easier.
We don't have to worry about variable-length batch sizes, and we don't have to implement the dynamic oracle
in CUDA to train.
Currently the parser's loss function is multilabel log loss, as the dynamic oracle allows multiple states to
be 0 cost. This is defined as:
(exp(score) / Z) - (exp(score) / gZ)
Where gZ is the sum of the scores assigned to gold classes. I'm very interested in regressing on the cost directly,
but so far this isn't working well.
Machinery is in place for beam-search, which has been working well for the linear model. Beam search should benefit
greatly from the pre-computation trick.
2017-05-12 21:09:15 +00:00
|
|
|
# cython: infer_types=True
|
|
|
|
# cython: profile=True
|
2017-04-15 10:05:47 +00:00
|
|
|
# coding: utf8
|
|
|
|
from __future__ import unicode_literals
|
|
|
|
|
2017-05-06 12:22:20 +00:00
|
|
|
from thinc.api import chain, layerize, with_getitem
|
|
|
|
from thinc.neural import Model, Softmax
|
2017-05-07 16:04:24 +00:00
|
|
|
import numpy
|
Update draft of parser neural network model
Model is good, but code is messy. Currently requires Chainer, which may cause the build to fail on machines without a GPU.
Outline of the model:
We first predict context-sensitive vectors for each word in the input:
(embed_lower | embed_prefix | embed_suffix | embed_shape)
>> Maxout(token_width)
>> convolution ** 4
This convolutional layer is shared between the tagger and the parser. This prevents the parser from needing tag features.
To boost the representation, we make a "super tag" with POS, morphology and dependency label. The tagger predicts this
by adding a softmax layer onto the convolutional layer --- so, we're teaching the convolutional layer to give us a
representation that's one affine transform from this informative lexical information. This is obviously good for the
parser (which backprops to the convolutions too).
The parser model makes a state vector by concatenating the vector representations for its context tokens. Current
results suggest few context tokens works well. Maybe this is a bug.
The current context tokens:
* S0, S1, S2: Top three words on the stack
* B0, B1: First two words of the buffer
* S0L1, S0L2: Leftmost and second leftmost children of S0
* S0R1, S0R2: Rightmost and second rightmost children of S0
* S1L1, S1L2, S1R2, S1R, B0L1, B0L2: Likewise for S1 and B0
This makes the state vector quite long: 13*T, where T is the token vector width (128 is working well). Fortunately,
there's a way to structure the computation to save some expense (and make it more GPU friendly).
The parser typically visits 2*N states for a sentence of length N (although it may visit more, if it back-tracks
with a non-monotonic transition). A naive implementation would require 2*N (B, 13*T) @ (13*T, H) matrix multiplications
for a batch of size B. We can instead perform one (B*N, T) @ (T, 13*H) multiplication, to pre-compute the hidden
weights for each positional feature wrt the words in the batch. (Note that our token vectors come from the CNN
-- so we can't play this trick over the vocabulary. That's how Stanford's NN parser works --- and why its model
is so big.)
This pre-computation strategy allows a nice compromise between GPU-friendliness and implementation simplicity.
The CNN and the wide lower layer are computed on the GPU, and then the precomputed hidden weights are moved
to the CPU, before we start the transition-based parsing process. This makes a lot of things much easier.
We don't have to worry about variable-length batch sizes, and we don't have to implement the dynamic oracle
in CUDA to train.
Currently the parser's loss function is multilabel log loss, as the dynamic oracle allows multiple states to
be 0 cost. This is defined as:
(exp(score) / Z) - (exp(score) / gZ)
Where gZ is the sum of the scores assigned to gold classes. I'm very interested in regressing on the cost directly,
but so far this isn't working well.
Machinery is in place for beam-search, which has been working well for the linear model. Beam search should benefit
greatly from the pre-computation trick.
2017-05-12 21:09:15 +00:00
|
|
|
cimport numpy as np
|
2017-05-16 14:17:30 +00:00
|
|
|
import cytoolz
|
2017-05-18 09:29:51 +00:00
|
|
|
import util
|
2017-05-16 14:17:30 +00:00
|
|
|
|
|
|
|
from thinc.api import add, layerize, chain, clone, concatenate
|
|
|
|
from thinc.neural import Model, Maxout, Softmax, Affine
|
|
|
|
from thinc.neural._classes.hash_embed import HashEmbed
|
|
|
|
from thinc.neural.util import to_categorical
|
|
|
|
|
|
|
|
from thinc.neural._classes.convolution import ExtractWindow
|
|
|
|
from thinc.neural._classes.resnet import Residual
|
|
|
|
from thinc.neural._classes.batchnorm import BatchNorm as BN
|
2017-05-06 12:22:20 +00:00
|
|
|
|
2017-05-08 12:53:45 +00:00
|
|
|
from .tokens.doc cimport Doc
|
2017-05-16 09:21:59 +00:00
|
|
|
from .syntax.parser cimport Parser as LinearParser
|
|
|
|
from .syntax.nn_parser cimport Parser as NeuralParser
|
2017-05-13 22:55:01 +00:00
|
|
|
from .syntax.parser import get_templates as get_feature_templates
|
2017-03-11 13:00:20 +00:00
|
|
|
from .syntax.beam_parser cimport BeamParser
|
2016-10-15 23:47:12 +00:00
|
|
|
from .syntax.ner cimport BiluoPushDown
|
|
|
|
from .syntax.arc_eager cimport ArcEager
|
2016-10-16 19:34:57 +00:00
|
|
|
from .tagger import Tagger
|
2017-05-17 10:04:50 +00:00
|
|
|
from .syntax.stateclass cimport StateClass
|
Update draft of parser neural network model
Model is good, but code is messy. Currently requires Chainer, which may cause the build to fail on machines without a GPU.
Outline of the model:
We first predict context-sensitive vectors for each word in the input:
(embed_lower | embed_prefix | embed_suffix | embed_shape)
>> Maxout(token_width)
>> convolution ** 4
This convolutional layer is shared between the tagger and the parser. This prevents the parser from needing tag features.
To boost the representation, we make a "super tag" with POS, morphology and dependency label. The tagger predicts this
by adding a softmax layer onto the convolutional layer --- so, we're teaching the convolutional layer to give us a
representation that's one affine transform from this informative lexical information. This is obviously good for the
parser (which backprops to the convolutions too).
The parser model makes a state vector by concatenating the vector representations for its context tokens. Current
results suggest few context tokens works well. Maybe this is a bug.
The current context tokens:
* S0, S1, S2: Top three words on the stack
* B0, B1: First two words of the buffer
* S0L1, S0L2: Leftmost and second leftmost children of S0
* S0R1, S0R2: Rightmost and second rightmost children of S0
* S1L1, S1L2, S1R2, S1R, B0L1, B0L2: Likewise for S1 and B0
This makes the state vector quite long: 13*T, where T is the token vector width (128 is working well). Fortunately,
there's a way to structure the computation to save some expense (and make it more GPU friendly).
The parser typically visits 2*N states for a sentence of length N (although it may visit more, if it back-tracks
with a non-monotonic transition). A naive implementation would require 2*N (B, 13*T) @ (13*T, H) matrix multiplications
for a batch of size B. We can instead perform one (B*N, T) @ (T, 13*H) multiplication, to pre-compute the hidden
weights for each positional feature wrt the words in the batch. (Note that our token vectors come from the CNN
-- so we can't play this trick over the vocabulary. That's how Stanford's NN parser works --- and why its model
is so big.)
This pre-computation strategy allows a nice compromise between GPU-friendliness and implementation simplicity.
The CNN and the wide lower layer are computed on the GPU, and then the precomputed hidden weights are moved
to the CPU, before we start the transition-based parsing process. This makes a lot of things much easier.
We don't have to worry about variable-length batch sizes, and we don't have to implement the dynamic oracle
in CUDA to train.
Currently the parser's loss function is multilabel log loss, as the dynamic oracle allows multiple states to
be 0 cost. This is defined as:
(exp(score) / Z) - (exp(score) / gZ)
Where gZ is the sum of the scores assigned to gold classes. I'm very interested in regressing on the cost directly,
but so far this isn't working well.
Machinery is in place for beam-search, which has been working well for the linear model. Beam search should benefit
greatly from the pre-computation trick.
2017-05-12 21:09:15 +00:00
|
|
|
from .gold cimport GoldParse
|
2017-05-17 10:04:50 +00:00
|
|
|
from .morphology cimport Morphology
|
|
|
|
from .vocab cimport Vocab
|
Update draft of parser neural network model
Model is good, but code is messy. Currently requires Chainer, which may cause the build to fail on machines without a GPU.
Outline of the model:
We first predict context-sensitive vectors for each word in the input:
(embed_lower | embed_prefix | embed_suffix | embed_shape)
>> Maxout(token_width)
>> convolution ** 4
This convolutional layer is shared between the tagger and the parser. This prevents the parser from needing tag features.
To boost the representation, we make a "super tag" with POS, morphology and dependency label. The tagger predicts this
by adding a softmax layer onto the convolutional layer --- so, we're teaching the convolutional layer to give us a
representation that's one affine transform from this informative lexical information. This is obviously good for the
parser (which backprops to the convolutions too).
The parser model makes a state vector by concatenating the vector representations for its context tokens. Current
results suggest few context tokens works well. Maybe this is a bug.
The current context tokens:
* S0, S1, S2: Top three words on the stack
* B0, B1: First two words of the buffer
* S0L1, S0L2: Leftmost and second leftmost children of S0
* S0R1, S0R2: Rightmost and second rightmost children of S0
* S1L1, S1L2, S1R2, S1R, B0L1, B0L2: Likewise for S1 and B0
This makes the state vector quite long: 13*T, where T is the token vector width (128 is working well). Fortunately,
there's a way to structure the computation to save some expense (and make it more GPU friendly).
The parser typically visits 2*N states for a sentence of length N (although it may visit more, if it back-tracks
with a non-monotonic transition). A naive implementation would require 2*N (B, 13*T) @ (13*T, H) matrix multiplications
for a batch of size B. We can instead perform one (B*N, T) @ (T, 13*H) multiplication, to pre-compute the hidden
weights for each positional feature wrt the words in the batch. (Note that our token vectors come from the CNN
-- so we can't play this trick over the vocabulary. That's how Stanford's NN parser works --- and why its model
is so big.)
This pre-computation strategy allows a nice compromise between GPU-friendliness and implementation simplicity.
The CNN and the wide lower layer are computed on the GPU, and then the precomputed hidden weights are moved
to the CPU, before we start the transition-based parsing process. This makes a lot of things much easier.
We don't have to worry about variable-length batch sizes, and we don't have to implement the dynamic oracle
in CUDA to train.
Currently the parser's loss function is multilabel log loss, as the dynamic oracle allows multiple states to
be 0 cost. This is defined as:
(exp(score) / Z) - (exp(score) / gZ)
Where gZ is the sum of the scores assigned to gold classes. I'm very interested in regressing on the cost directly,
but so far this isn't working well.
Machinery is in place for beam-search, which has been working well for the linear model. Beam search should benefit
greatly from the pre-computation trick.
2017-05-12 21:09:15 +00:00
|
|
|
|
2017-05-17 10:04:50 +00:00
|
|
|
from .attrs import ID, LOWER, PREFIX, SUFFIX, SHAPE, TAG, DEP, POS
|
2017-05-15 19:46:08 +00:00
|
|
|
from ._ml import Tok2Vec, flatten, get_col, doc2feats
|
2017-05-17 10:04:50 +00:00
|
|
|
from .parts_of_speech import X
|
2016-10-15 23:47:12 +00:00
|
|
|
|
|
|
|
|
2017-05-06 12:22:20 +00:00
|
|
|
class TokenVectorEncoder(object):
|
|
|
|
'''Assign position-sensitive vectors to tokens, using a CNN or RNN.'''
|
2017-05-16 09:21:59 +00:00
|
|
|
name = 'tok2vec'
|
Update draft of parser neural network model
Model is good, but code is messy. Currently requires Chainer, which may cause the build to fail on machines without a GPU.
Outline of the model:
We first predict context-sensitive vectors for each word in the input:
(embed_lower | embed_prefix | embed_suffix | embed_shape)
>> Maxout(token_width)
>> convolution ** 4
This convolutional layer is shared between the tagger and the parser. This prevents the parser from needing tag features.
To boost the representation, we make a "super tag" with POS, morphology and dependency label. The tagger predicts this
by adding a softmax layer onto the convolutional layer --- so, we're teaching the convolutional layer to give us a
representation that's one affine transform from this informative lexical information. This is obviously good for the
parser (which backprops to the convolutions too).
The parser model makes a state vector by concatenating the vector representations for its context tokens. Current
results suggest few context tokens works well. Maybe this is a bug.
The current context tokens:
* S0, S1, S2: Top three words on the stack
* B0, B1: First two words of the buffer
* S0L1, S0L2: Leftmost and second leftmost children of S0
* S0R1, S0R2: Rightmost and second rightmost children of S0
* S1L1, S1L2, S1R2, S1R, B0L1, B0L2: Likewise for S1 and B0
This makes the state vector quite long: 13*T, where T is the token vector width (128 is working well). Fortunately,
there's a way to structure the computation to save some expense (and make it more GPU friendly).
The parser typically visits 2*N states for a sentence of length N (although it may visit more, if it back-tracks
with a non-monotonic transition). A naive implementation would require 2*N (B, 13*T) @ (13*T, H) matrix multiplications
for a batch of size B. We can instead perform one (B*N, T) @ (T, 13*H) multiplication, to pre-compute the hidden
weights for each positional feature wrt the words in the batch. (Note that our token vectors come from the CNN
-- so we can't play this trick over the vocabulary. That's how Stanford's NN parser works --- and why its model
is so big.)
This pre-computation strategy allows a nice compromise between GPU-friendliness and implementation simplicity.
The CNN and the wide lower layer are computed on the GPU, and then the precomputed hidden weights are moved
to the CPU, before we start the transition-based parsing process. This makes a lot of things much easier.
We don't have to worry about variable-length batch sizes, and we don't have to implement the dynamic oracle
in CUDA to train.
Currently the parser's loss function is multilabel log loss, as the dynamic oracle allows multiple states to
be 0 cost. This is defined as:
(exp(score) / Z) - (exp(score) / gZ)
Where gZ is the sum of the scores assigned to gold classes. I'm very interested in regressing on the cost directly,
but so far this isn't working well.
Machinery is in place for beam-search, which has been working well for the linear model. Beam search should benefit
greatly from the pre-computation trick.
2017-05-12 21:09:15 +00:00
|
|
|
|
2017-05-15 19:46:08 +00:00
|
|
|
@classmethod
|
|
|
|
def Model(cls, width=128, embed_size=5000, **cfg):
|
2017-05-18 09:29:51 +00:00
|
|
|
width = util.env_opt('token_vector_width', width)
|
|
|
|
embed_size = util.env_opt('embed_size', embed_size)
|
2017-05-16 14:17:30 +00:00
|
|
|
return Tok2Vec(width, embed_size, preprocess=None)
|
Update draft of parser neural network model
Model is good, but code is messy. Currently requires Chainer, which may cause the build to fail on machines without a GPU.
Outline of the model:
We first predict context-sensitive vectors for each word in the input:
(embed_lower | embed_prefix | embed_suffix | embed_shape)
>> Maxout(token_width)
>> convolution ** 4
This convolutional layer is shared between the tagger and the parser. This prevents the parser from needing tag features.
To boost the representation, we make a "super tag" with POS, morphology and dependency label. The tagger predicts this
by adding a softmax layer onto the convolutional layer --- so, we're teaching the convolutional layer to give us a
representation that's one affine transform from this informative lexical information. This is obviously good for the
parser (which backprops to the convolutions too).
The parser model makes a state vector by concatenating the vector representations for its context tokens. Current
results suggest few context tokens works well. Maybe this is a bug.
The current context tokens:
* S0, S1, S2: Top three words on the stack
* B0, B1: First two words of the buffer
* S0L1, S0L2: Leftmost and second leftmost children of S0
* S0R1, S0R2: Rightmost and second rightmost children of S0
* S1L1, S1L2, S1R2, S1R, B0L1, B0L2: Likewise for S1 and B0
This makes the state vector quite long: 13*T, where T is the token vector width (128 is working well). Fortunately,
there's a way to structure the computation to save some expense (and make it more GPU friendly).
The parser typically visits 2*N states for a sentence of length N (although it may visit more, if it back-tracks
with a non-monotonic transition). A naive implementation would require 2*N (B, 13*T) @ (13*T, H) matrix multiplications
for a batch of size B. We can instead perform one (B*N, T) @ (T, 13*H) multiplication, to pre-compute the hidden
weights for each positional feature wrt the words in the batch. (Note that our token vectors come from the CNN
-- so we can't play this trick over the vocabulary. That's how Stanford's NN parser works --- and why its model
is so big.)
This pre-computation strategy allows a nice compromise between GPU-friendliness and implementation simplicity.
The CNN and the wide lower layer are computed on the GPU, and then the precomputed hidden weights are moved
to the CPU, before we start the transition-based parsing process. This makes a lot of things much easier.
We don't have to worry about variable-length batch sizes, and we don't have to implement the dynamic oracle
in CUDA to train.
Currently the parser's loss function is multilabel log loss, as the dynamic oracle allows multiple states to
be 0 cost. This is defined as:
(exp(score) / Z) - (exp(score) / gZ)
Where gZ is the sum of the scores assigned to gold classes. I'm very interested in regressing on the cost directly,
but so far this isn't working well.
Machinery is in place for beam-search, which has been working well for the linear model. Beam search should benefit
greatly from the pre-computation trick.
2017-05-12 21:09:15 +00:00
|
|
|
|
2017-05-15 19:46:08 +00:00
|
|
|
def __init__(self, vocab, model=True, **cfg):
|
|
|
|
self.vocab = vocab
|
|
|
|
self.doc2feats = doc2feats()
|
2017-05-18 09:29:51 +00:00
|
|
|
self.model = model
|
2017-05-17 11:13:14 +00:00
|
|
|
|
2017-05-16 14:17:30 +00:00
|
|
|
def __call__(self, docs, state=None):
|
|
|
|
if isinstance(docs, Doc):
|
|
|
|
docs = [docs]
|
|
|
|
tokvecs = self.predict(docs)
|
|
|
|
self.set_annotations(docs, tokvecs)
|
2017-05-17 10:04:50 +00:00
|
|
|
state = {} if state is None else state
|
2017-05-16 14:17:30 +00:00
|
|
|
state['tokvecs'] = tokvecs
|
|
|
|
return state
|
|
|
|
|
2017-05-18 13:30:59 +00:00
|
|
|
def pipe(self, stream, batch_size=128, n_threads=-1):
|
|
|
|
for batch in cytoolz.partition_all(batch_size, stream):
|
|
|
|
docs, states = zip(*batch)
|
|
|
|
tokvecs = self.predict(docs)
|
|
|
|
self.set_annotations(docs, tokvecs)
|
|
|
|
for state in states:
|
|
|
|
state['tokvecs'] = tokvecs
|
|
|
|
yield from zip(docs, states)
|
2017-05-18 09:29:51 +00:00
|
|
|
|
2017-05-16 14:17:30 +00:00
|
|
|
def predict(self, docs):
|
|
|
|
feats = self.doc2feats(docs)
|
|
|
|
tokvecs = self.model(feats)
|
|
|
|
return tokvecs
|
|
|
|
|
|
|
|
def set_annotations(self, docs, tokvecs):
|
|
|
|
start = 0
|
Update draft of parser neural network model
Model is good, but code is messy. Currently requires Chainer, which may cause the build to fail on machines without a GPU.
Outline of the model:
We first predict context-sensitive vectors for each word in the input:
(embed_lower | embed_prefix | embed_suffix | embed_shape)
>> Maxout(token_width)
>> convolution ** 4
This convolutional layer is shared between the tagger and the parser. This prevents the parser from needing tag features.
To boost the representation, we make a "super tag" with POS, morphology and dependency label. The tagger predicts this
by adding a softmax layer onto the convolutional layer --- so, we're teaching the convolutional layer to give us a
representation that's one affine transform from this informative lexical information. This is obviously good for the
parser (which backprops to the convolutions too).
The parser model makes a state vector by concatenating the vector representations for its context tokens. Current
results suggest few context tokens works well. Maybe this is a bug.
The current context tokens:
* S0, S1, S2: Top three words on the stack
* B0, B1: First two words of the buffer
* S0L1, S0L2: Leftmost and second leftmost children of S0
* S0R1, S0R2: Rightmost and second rightmost children of S0
* S1L1, S1L2, S1R2, S1R, B0L1, B0L2: Likewise for S1 and B0
This makes the state vector quite long: 13*T, where T is the token vector width (128 is working well). Fortunately,
there's a way to structure the computation to save some expense (and make it more GPU friendly).
The parser typically visits 2*N states for a sentence of length N (although it may visit more, if it back-tracks
with a non-monotonic transition). A naive implementation would require 2*N (B, 13*T) @ (13*T, H) matrix multiplications
for a batch of size B. We can instead perform one (B*N, T) @ (T, 13*H) multiplication, to pre-compute the hidden
weights for each positional feature wrt the words in the batch. (Note that our token vectors come from the CNN
-- so we can't play this trick over the vocabulary. That's how Stanford's NN parser works --- and why its model
is so big.)
This pre-computation strategy allows a nice compromise between GPU-friendliness and implementation simplicity.
The CNN and the wide lower layer are computed on the GPU, and then the precomputed hidden weights are moved
to the CPU, before we start the transition-based parsing process. This makes a lot of things much easier.
We don't have to worry about variable-length batch sizes, and we don't have to implement the dynamic oracle
in CUDA to train.
Currently the parser's loss function is multilabel log loss, as the dynamic oracle allows multiple states to
be 0 cost. This is defined as:
(exp(score) / Z) - (exp(score) / gZ)
Where gZ is the sum of the scores assigned to gold classes. I'm very interested in regressing on the cost directly,
but so far this isn't working well.
Machinery is in place for beam-search, which has been working well for the linear model. Beam search should benefit
greatly from the pre-computation trick.
2017-05-12 21:09:15 +00:00
|
|
|
for doc in docs:
|
2017-05-16 14:17:30 +00:00
|
|
|
doc.tensor = tokvecs[start : start + len(doc)]
|
|
|
|
start += len(doc)
|
2017-05-17 10:04:50 +00:00
|
|
|
|
2017-05-16 14:17:30 +00:00
|
|
|
def update(self, docs, golds, state=None,
|
|
|
|
drop=0., sgd=None):
|
|
|
|
if isinstance(docs, Doc):
|
|
|
|
docs = [docs]
|
|
|
|
golds = [golds]
|
|
|
|
state = {} if state is None else state
|
|
|
|
feats = self.doc2feats(docs)
|
|
|
|
tokvecs, bp_tokvecs = self.model.begin_update(feats, drop=drop)
|
|
|
|
state['feats'] = feats
|
|
|
|
state['tokvecs'] = tokvecs
|
|
|
|
state['bp_tokvecs'] = bp_tokvecs
|
|
|
|
return state
|
2017-05-06 12:22:20 +00:00
|
|
|
|
2017-05-16 14:17:30 +00:00
|
|
|
def get_loss(self, docs, golds, scores):
|
|
|
|
raise NotImplementedError
|
2017-05-06 12:22:20 +00:00
|
|
|
|
2017-05-18 09:29:51 +00:00
|
|
|
def begin_training(self, gold_tuples, pipeline=None):
|
|
|
|
self.doc2feats = doc2feats()
|
|
|
|
if self.model is True:
|
|
|
|
self.model = self.Model()
|
|
|
|
|
2017-05-18 13:30:59 +00:00
|
|
|
def use_params(self, params):
|
|
|
|
with self.model.use_params(params):
|
|
|
|
yield
|
|
|
|
|
2017-05-06 12:22:20 +00:00
|
|
|
|
2017-05-16 14:17:30 +00:00
|
|
|
class NeuralTagger(object):
|
|
|
|
name = 'nn_tagger'
|
2017-05-17 10:04:50 +00:00
|
|
|
def __init__(self, vocab, model=True):
|
2017-05-16 14:17:30 +00:00
|
|
|
self.vocab = vocab
|
2017-05-17 10:04:50 +00:00
|
|
|
self.model = model
|
2017-05-16 14:17:30 +00:00
|
|
|
|
|
|
|
def __call__(self, doc, state=None):
|
|
|
|
assert state is not None
|
|
|
|
assert 'tokvecs' in state
|
|
|
|
tokvecs = state['tokvecs']
|
|
|
|
tags = self.predict(tokvecs)
|
|
|
|
self.set_annotations([doc], tags)
|
|
|
|
return state
|
|
|
|
|
|
|
|
def pipe(self, stream, batch_size=128, n_threads=-1):
|
2017-05-18 13:30:59 +00:00
|
|
|
for batch in cytoolz.partition_all(batch_size, stream):
|
|
|
|
docs, states = zip(*batch)
|
|
|
|
tag_ids = self.predict(states[0]['tokvecs'])
|
2017-05-16 14:17:30 +00:00
|
|
|
self.set_annotations(docs, tag_ids)
|
2017-05-18 13:30:59 +00:00
|
|
|
for state in states:
|
|
|
|
state['tag_ids'] = tag_ids
|
|
|
|
yield from zip(docs, states)
|
2017-05-16 14:17:30 +00:00
|
|
|
|
|
|
|
def predict(self, tokvecs):
|
|
|
|
scores = self.model(tokvecs)
|
2017-05-13 22:20:23 +00:00
|
|
|
guesses = scores.argmax(axis=1)
|
|
|
|
if not isinstance(guesses, numpy.ndarray):
|
|
|
|
guesses = guesses.get()
|
2017-05-16 14:17:30 +00:00
|
|
|
return guesses
|
|
|
|
|
2017-05-18 09:29:51 +00:00
|
|
|
def set_annotations(self, docs, batch_tag_ids):
|
2017-05-16 14:17:30 +00:00
|
|
|
if isinstance(docs, Doc):
|
|
|
|
docs = [docs]
|
|
|
|
cdef Doc doc
|
|
|
|
cdef int idx = 0
|
2017-05-18 13:30:59 +00:00
|
|
|
cdef int i, j, tag_id
|
2017-05-18 09:29:51 +00:00
|
|
|
cdef Vocab vocab = self.vocab
|
2017-05-08 12:53:45 +00:00
|
|
|
for i, doc in enumerate(docs):
|
2017-05-18 09:29:51 +00:00
|
|
|
doc_tag_ids = batch_tag_ids[idx:idx+len(doc)]
|
|
|
|
for j, tag_id in enumerate(doc_tag_ids):
|
|
|
|
vocab.morphology.assign_tag_id(&doc.c[j], tag_id)
|
2017-05-08 12:53:45 +00:00
|
|
|
idx += 1
|
|
|
|
|
2017-05-16 14:17:30 +00:00
|
|
|
def update(self, docs, golds, state=None, drop=0., sgd=None):
|
|
|
|
state = {} if state is None else state
|
|
|
|
|
|
|
|
tokvecs = state['tokvecs']
|
|
|
|
bp_tokvecs = state['bp_tokvecs']
|
|
|
|
if self.model.nI is None:
|
|
|
|
self.model.nI = tokvecs.shape[1]
|
2017-05-17 10:04:50 +00:00
|
|
|
|
2017-05-16 14:17:30 +00:00
|
|
|
tag_scores, bp_tag_scores = self.model.begin_update(tokvecs, drop=drop)
|
|
|
|
loss, d_tag_scores = self.get_loss(docs, golds, tag_scores)
|
2017-05-18 09:29:51 +00:00
|
|
|
|
|
|
|
d_tokvecs = bp_tag_scores(d_tag_scores, sgd=sgd)
|
2017-05-16 14:17:30 +00:00
|
|
|
|
2017-05-17 11:13:14 +00:00
|
|
|
bp_tokvecs(d_tokvecs, sgd=sgd)
|
|
|
|
|
2017-05-16 14:17:30 +00:00
|
|
|
state['tag_scores'] = tag_scores
|
|
|
|
state['tag_loss'] = loss
|
|
|
|
return state
|
|
|
|
|
|
|
|
def get_loss(self, docs, golds, scores):
|
2017-05-18 09:29:51 +00:00
|
|
|
tag_index = {tag: i for i, tag in enumerate(self.vocab.morphology.tag_names)}
|
Update draft of parser neural network model
Model is good, but code is messy. Currently requires Chainer, which may cause the build to fail on machines without a GPU.
Outline of the model:
We first predict context-sensitive vectors for each word in the input:
(embed_lower | embed_prefix | embed_suffix | embed_shape)
>> Maxout(token_width)
>> convolution ** 4
This convolutional layer is shared between the tagger and the parser. This prevents the parser from needing tag features.
To boost the representation, we make a "super tag" with POS, morphology and dependency label. The tagger predicts this
by adding a softmax layer onto the convolutional layer --- so, we're teaching the convolutional layer to give us a
representation that's one affine transform from this informative lexical information. This is obviously good for the
parser (which backprops to the convolutions too).
The parser model makes a state vector by concatenating the vector representations for its context tokens. Current
results suggest few context tokens works well. Maybe this is a bug.
The current context tokens:
* S0, S1, S2: Top three words on the stack
* B0, B1: First two words of the buffer
* S0L1, S0L2: Leftmost and second leftmost children of S0
* S0R1, S0R2: Rightmost and second rightmost children of S0
* S1L1, S1L2, S1R2, S1R, B0L1, B0L2: Likewise for S1 and B0
This makes the state vector quite long: 13*T, where T is the token vector width (128 is working well). Fortunately,
there's a way to structure the computation to save some expense (and make it more GPU friendly).
The parser typically visits 2*N states for a sentence of length N (although it may visit more, if it back-tracks
with a non-monotonic transition). A naive implementation would require 2*N (B, 13*T) @ (13*T, H) matrix multiplications
for a batch of size B. We can instead perform one (B*N, T) @ (T, 13*H) multiplication, to pre-compute the hidden
weights for each positional feature wrt the words in the batch. (Note that our token vectors come from the CNN
-- so we can't play this trick over the vocabulary. That's how Stanford's NN parser works --- and why its model
is so big.)
This pre-computation strategy allows a nice compromise between GPU-friendliness and implementation simplicity.
The CNN and the wide lower layer are computed on the GPU, and then the precomputed hidden weights are moved
to the CPU, before we start the transition-based parsing process. This makes a lot of things much easier.
We don't have to worry about variable-length batch sizes, and we don't have to implement the dynamic oracle
in CUDA to train.
Currently the parser's loss function is multilabel log loss, as the dynamic oracle allows multiple states to
be 0 cost. This is defined as:
(exp(score) / Z) - (exp(score) / gZ)
Where gZ is the sum of the scores assigned to gold classes. I'm very interested in regressing on the cost directly,
but so far this isn't working well.
Machinery is in place for beam-search, which has been working well for the linear model. Beam search should benefit
greatly from the pre-computation trick.
2017-05-12 21:09:15 +00:00
|
|
|
|
2017-05-18 09:29:51 +00:00
|
|
|
cdef int idx = 0
|
Update draft of parser neural network model
Model is good, but code is messy. Currently requires Chainer, which may cause the build to fail on machines without a GPU.
Outline of the model:
We first predict context-sensitive vectors for each word in the input:
(embed_lower | embed_prefix | embed_suffix | embed_shape)
>> Maxout(token_width)
>> convolution ** 4
This convolutional layer is shared between the tagger and the parser. This prevents the parser from needing tag features.
To boost the representation, we make a "super tag" with POS, morphology and dependency label. The tagger predicts this
by adding a softmax layer onto the convolutional layer --- so, we're teaching the convolutional layer to give us a
representation that's one affine transform from this informative lexical information. This is obviously good for the
parser (which backprops to the convolutions too).
The parser model makes a state vector by concatenating the vector representations for its context tokens. Current
results suggest few context tokens works well. Maybe this is a bug.
The current context tokens:
* S0, S1, S2: Top three words on the stack
* B0, B1: First two words of the buffer
* S0L1, S0L2: Leftmost and second leftmost children of S0
* S0R1, S0R2: Rightmost and second rightmost children of S0
* S1L1, S1L2, S1R2, S1R, B0L1, B0L2: Likewise for S1 and B0
This makes the state vector quite long: 13*T, where T is the token vector width (128 is working well). Fortunately,
there's a way to structure the computation to save some expense (and make it more GPU friendly).
The parser typically visits 2*N states for a sentence of length N (although it may visit more, if it back-tracks
with a non-monotonic transition). A naive implementation would require 2*N (B, 13*T) @ (13*T, H) matrix multiplications
for a batch of size B. We can instead perform one (B*N, T) @ (T, 13*H) multiplication, to pre-compute the hidden
weights for each positional feature wrt the words in the batch. (Note that our token vectors come from the CNN
-- so we can't play this trick over the vocabulary. That's how Stanford's NN parser works --- and why its model
is so big.)
This pre-computation strategy allows a nice compromise between GPU-friendliness and implementation simplicity.
The CNN and the wide lower layer are computed on the GPU, and then the precomputed hidden weights are moved
to the CPU, before we start the transition-based parsing process. This makes a lot of things much easier.
We don't have to worry about variable-length batch sizes, and we don't have to implement the dynamic oracle
in CUDA to train.
Currently the parser's loss function is multilabel log loss, as the dynamic oracle allows multiple states to
be 0 cost. This is defined as:
(exp(score) / Z) - (exp(score) / gZ)
Where gZ is the sum of the scores assigned to gold classes. I'm very interested in regressing on the cost directly,
but so far this isn't working well.
Machinery is in place for beam-search, which has been working well for the linear model. Beam search should benefit
greatly from the pre-computation trick.
2017-05-12 21:09:15 +00:00
|
|
|
correct = numpy.zeros((scores.shape[0],), dtype='i')
|
|
|
|
for gold in golds:
|
|
|
|
for tag in gold.tags:
|
|
|
|
correct[idx] = tag_index[tag]
|
|
|
|
idx += 1
|
2017-05-18 13:30:59 +00:00
|
|
|
correct = self.model.ops.xp.array(correct, dtype='i')
|
Update draft of parser neural network model
Model is good, but code is messy. Currently requires Chainer, which may cause the build to fail on machines without a GPU.
Outline of the model:
We first predict context-sensitive vectors for each word in the input:
(embed_lower | embed_prefix | embed_suffix | embed_shape)
>> Maxout(token_width)
>> convolution ** 4
This convolutional layer is shared between the tagger and the parser. This prevents the parser from needing tag features.
To boost the representation, we make a "super tag" with POS, morphology and dependency label. The tagger predicts this
by adding a softmax layer onto the convolutional layer --- so, we're teaching the convolutional layer to give us a
representation that's one affine transform from this informative lexical information. This is obviously good for the
parser (which backprops to the convolutions too).
The parser model makes a state vector by concatenating the vector representations for its context tokens. Current
results suggest few context tokens works well. Maybe this is a bug.
The current context tokens:
* S0, S1, S2: Top three words on the stack
* B0, B1: First two words of the buffer
* S0L1, S0L2: Leftmost and second leftmost children of S0
* S0R1, S0R2: Rightmost and second rightmost children of S0
* S1L1, S1L2, S1R2, S1R, B0L1, B0L2: Likewise for S1 and B0
This makes the state vector quite long: 13*T, where T is the token vector width (128 is working well). Fortunately,
there's a way to structure the computation to save some expense (and make it more GPU friendly).
The parser typically visits 2*N states for a sentence of length N (although it may visit more, if it back-tracks
with a non-monotonic transition). A naive implementation would require 2*N (B, 13*T) @ (13*T, H) matrix multiplications
for a batch of size B. We can instead perform one (B*N, T) @ (T, 13*H) multiplication, to pre-compute the hidden
weights for each positional feature wrt the words in the batch. (Note that our token vectors come from the CNN
-- so we can't play this trick over the vocabulary. That's how Stanford's NN parser works --- and why its model
is so big.)
This pre-computation strategy allows a nice compromise between GPU-friendliness and implementation simplicity.
The CNN and the wide lower layer are computed on the GPU, and then the precomputed hidden weights are moved
to the CPU, before we start the transition-based parsing process. This makes a lot of things much easier.
We don't have to worry about variable-length batch sizes, and we don't have to implement the dynamic oracle
in CUDA to train.
Currently the parser's loss function is multilabel log loss, as the dynamic oracle allows multiple states to
be 0 cost. This is defined as:
(exp(score) / Z) - (exp(score) / gZ)
Where gZ is the sum of the scores assigned to gold classes. I'm very interested in regressing on the cost directly,
but so far this isn't working well.
Machinery is in place for beam-search, which has been working well for the linear model. Beam search should benefit
greatly from the pre-computation trick.
2017-05-12 21:09:15 +00:00
|
|
|
d_scores = scores - to_categorical(correct, nb_classes=scores.shape[1])
|
2017-05-18 09:29:51 +00:00
|
|
|
loss = (d_scores**2).sum()
|
2017-05-18 13:30:59 +00:00
|
|
|
d_scores = self.model.ops.asarray(d_scores, dtype='f')
|
|
|
|
return float(loss), d_scores
|
2016-10-15 23:47:12 +00:00
|
|
|
|
2017-05-17 10:04:50 +00:00
|
|
|
def begin_training(self, gold_tuples, pipeline=None):
|
2017-05-18 13:30:59 +00:00
|
|
|
orig_tag_map = dict(self.vocab.morphology.tag_map)
|
|
|
|
new_tag_map = {}
|
2017-05-17 10:04:50 +00:00
|
|
|
for raw_text, annots_brackets in gold_tuples:
|
|
|
|
for annots, brackets in annots_brackets:
|
|
|
|
ids, words, tags, heads, deps, ents = annots
|
|
|
|
for tag in tags:
|
2017-05-18 13:30:59 +00:00
|
|
|
if tag in orig_tag_map:
|
|
|
|
new_tag_map[tag] = orig_tag_map[tag]
|
|
|
|
else:
|
|
|
|
new_tag_map[tag] = {POS: X}
|
2017-05-17 10:04:50 +00:00
|
|
|
cdef Vocab vocab = self.vocab
|
2017-05-18 13:30:59 +00:00
|
|
|
vocab.morphology = Morphology(vocab.strings, new_tag_map,
|
2017-05-18 09:29:51 +00:00
|
|
|
vocab.morphology.lemmatizer)
|
2017-05-17 10:04:50 +00:00
|
|
|
self.model = Softmax(self.vocab.morphology.n_tags)
|
2017-05-18 13:30:59 +00:00
|
|
|
print("Tagging", self.model.nO, "tags")
|
|
|
|
|
|
|
|
def use_params(self, params):
|
|
|
|
with self.model.use_params(params):
|
|
|
|
yield
|
|
|
|
|
2017-05-17 10:04:50 +00:00
|
|
|
|
|
|
|
|
2017-05-16 09:21:59 +00:00
|
|
|
cdef class EntityRecognizer(LinearParser):
|
2017-04-15 09:59:21 +00:00
|
|
|
"""
|
|
|
|
Annotate named entities on Doc objects.
|
|
|
|
"""
|
2016-10-16 19:34:57 +00:00
|
|
|
TransitionSystem = BiluoPushDown
|
2017-03-11 13:00:20 +00:00
|
|
|
|
2016-10-16 19:34:57 +00:00
|
|
|
feature_templates = get_feature_templates('ner')
|
2016-10-15 23:47:12 +00:00
|
|
|
|
2016-10-23 15:45:44 +00:00
|
|
|
def add_label(self, label):
|
2017-05-16 09:21:59 +00:00
|
|
|
LinearParser.add_label(self, label)
|
2016-10-23 15:45:44 +00:00
|
|
|
if isinstance(label, basestring):
|
|
|
|
label = self.vocab.strings[label]
|
|
|
|
|
2016-10-15 23:47:12 +00:00
|
|
|
|
2017-03-15 14:27:41 +00:00
|
|
|
cdef class BeamEntityRecognizer(BeamParser):
|
2017-04-15 09:59:21 +00:00
|
|
|
"""
|
|
|
|
Annotate named entities on Doc objects.
|
|
|
|
"""
|
2017-03-15 14:27:41 +00:00
|
|
|
TransitionSystem = BiluoPushDown
|
|
|
|
|
|
|
|
feature_templates = get_feature_templates('ner')
|
2017-04-15 10:05:47 +00:00
|
|
|
|
2017-03-15 14:27:41 +00:00
|
|
|
def add_label(self, label):
|
2017-05-16 09:21:59 +00:00
|
|
|
LinearParser.add_label(self, label)
|
2017-03-15 14:27:41 +00:00
|
|
|
if isinstance(label, basestring):
|
|
|
|
label = self.vocab.strings[label]
|
|
|
|
|
|
|
|
|
2017-05-16 09:21:59 +00:00
|
|
|
cdef class DependencyParser(LinearParser):
|
2016-10-16 19:34:57 +00:00
|
|
|
TransitionSystem = ArcEager
|
|
|
|
feature_templates = get_feature_templates('basic')
|
2016-10-23 15:45:44 +00:00
|
|
|
|
|
|
|
def add_label(self, label):
|
2017-05-16 09:21:59 +00:00
|
|
|
LinearParser.add_label(self, label)
|
2016-10-23 15:45:44 +00:00
|
|
|
if isinstance(label, basestring):
|
|
|
|
label = self.vocab.strings[label]
|
|
|
|
|
2016-10-15 23:47:12 +00:00
|
|
|
|
2017-05-16 09:21:59 +00:00
|
|
|
cdef class NeuralDependencyParser(NeuralParser):
|
|
|
|
name = 'parser'
|
|
|
|
TransitionSystem = ArcEager
|
|
|
|
|
|
|
|
|
|
|
|
cdef class NeuralEntityRecognizer(NeuralParser):
|
|
|
|
name = 'entity'
|
|
|
|
TransitionSystem = BiluoPushDown
|
|
|
|
|
2017-05-17 10:04:50 +00:00
|
|
|
nr_feature = 6
|
|
|
|
|
|
|
|
def get_token_ids(self, states):
|
|
|
|
cdef StateClass state
|
|
|
|
cdef int n_tokens = 6
|
|
|
|
ids = numpy.zeros((len(states), n_tokens), dtype='i', order='c')
|
|
|
|
for i, state in enumerate(states):
|
|
|
|
ids[i, 0] = state.c.B(0)-1
|
|
|
|
ids[i, 1] = state.c.B(0)
|
|
|
|
ids[i, 2] = state.c.B(1)
|
|
|
|
ids[i, 3] = state.c.E(0)
|
|
|
|
ids[i, 4] = state.c.E(0)-1
|
|
|
|
ids[i, 5] = state.c.E(0)+1
|
|
|
|
for j in range(6):
|
|
|
|
if ids[i, j] >= state.c.length:
|
|
|
|
ids[i, j] = -1
|
|
|
|
if ids[i, j] != -1:
|
|
|
|
ids[i, j] += state.c.offset
|
|
|
|
return ids
|
|
|
|
|
|
|
|
|
|
|
|
|
2017-05-16 09:21:59 +00:00
|
|
|
|
2017-03-15 14:27:41 +00:00
|
|
|
cdef class BeamDependencyParser(BeamParser):
|
|
|
|
TransitionSystem = ArcEager
|
|
|
|
|
|
|
|
feature_templates = get_feature_templates('basic')
|
|
|
|
|
|
|
|
def add_label(self, label):
|
2017-04-14 21:52:17 +00:00
|
|
|
Parser.add_label(self, label)
|
2017-03-15 14:27:41 +00:00
|
|
|
if isinstance(label, basestring):
|
|
|
|
label = self.vocab.strings[label]
|
|
|
|
|
|
|
|
|
2017-05-13 23:10:23 +00:00
|
|
|
__all__ = ['Tagger', 'DependencyParser', 'EntityRecognizer', 'BeamDependencyParser',
|
|
|
|
'BeamEntityRecognizer', 'TokenVectorEnoder']
|