Class FeedforwardDependencyTrainer
FeedforwardDependencyModel: oracle-derived transition examples,
minibatch AdaGrad over a softmax cross-entropy loss, cube activation, and inverted
dropout on the hidden layer, the training recipe of
Chen and Manning (2014).
The hyperparameters are read from TrainingParameters: the keys of this
class plus Parameters.ITERATIONS_PARAM for the number of epochs,
Parameters.CUTOFF_PARAM for the minimum word frequency,
QNTrainer.L2COST_PARAM for the L2 penalty on the dense weights (default
1.0E-8), and BeamSearch.BEAM_SIZE_PARAMETER for the refinement
beam. Other keys are ignored.
Words below the frequency cutoff share the reserved unknown row, which is
therefore trained only when such words exist; the unknown rows of the tag and label
vocabularies keep their random initialization. Absent template positions share a
trained padding row. Non-projective samples have no arc-standard derivation and are
skipped. Training is deterministic for a fixed SEED_PARAM.
- Since:
- 3.0.0
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprivate static final recordA projective training sample with its arc-standard oracle derivation.private static final classThe forward pass, backward pass, gradient buffers, and AdaGrad state shared by local training and beam refinement.(package private) static final recordThe parsed hyperparameters of one training or refinement run. -
Field Summary
FieldsModifier and TypeFieldDescriptionprivate static final doubleThe AdaGrad denominator offset that keeps the first steps finite.static final StringThe training parameter key of the minibatch size; default 256.private static final doubleThe derivative factor of the cube activation,d/dx x^3 = 3x^2.static final intThe default minibatch size.static final intThe default refinement beam size.static final doubleThe default hidden dropout probability.static final intThe default embedding dimensionality.static final intThe default number of epochs.static final intThe default hidden layer width.static final doubleThe default L2 penalty.static final doubleThe default AdaGrad step size.static final intThe default random seed.static final intThe default minimum word frequency for an embedding row.static final StringThe training parameter key of the hidden dropout probability; default 0.5.private static final doubleThe half-width of the uniform range embeddings are drawn from.static final StringThe training parameter key of the embedding dimensionality; default 50.private static final doubleThe numerator of the Glorot uniform bound,sqrt(6 / (fanIn + fanOut)).static final StringThe training parameter key of the hidden layer width; default 200.static final StringThe training parameter key of the AdaGrad step size; default 0.02.private static final org.slf4j.Loggerprivate static final doubleThe smallest probability the reported training loss takes the log of.(package private) static final intThe maximum embedding width.(package private) static final intThe maximum hidden-layer width.private static final intThe smallest beam that can lose the gold derivation to another path.private static final intSHIFT and at least one RIGHT_ARC are required to parse a sentence.static final StringThe training parameter key of the random seed, read as anint; default 17. -
Constructor Summary
ConstructorsModifierConstructorDescriptionprivatePrevents construction of this utility class. -
Method Summary
Modifier and TypeMethodDescriptionprivate static intassignRows(Map<String, Integer> ids, int row, String[] reserved, List<String> observed, String label) Assigns the next embedding rows of one vocabulary: the reserved symbols first, then the observed symbols in sorted order, skipping observed symbols that spell a reserved one.private static voidcheckFinite(float[] vector) private static voidcheckFinite(float[][] matrix) private static voidcheckFinite(FeedforwardNetwork network) Rejects numerical overflow before returning or continuing to train a network.private static voidcollectExamples(List<FeedforwardDependencyTrainer.Derivation> derivations, FeedforwardNetwork network, int[][] features, int[] gold) Replays the oracle over every derivation, emitting one example per step.private static List<FeedforwardDependencyTrainer.Derivation> derive(ObjectStream<DependencySample> samples) Reads a sample stream into memory and derives the oracle of every projective sample once; the trainer passes over the derivations repeatedly.private static int[]identity(int size) private static FeedforwardNetworkinitialize(List<FeedforwardDependencyTrainer.Derivation> derivations, FeedforwardDependencyTrainer.Settings settings) Builds the vocabularies and randomly initialized weights.private static voidoptimize(FeedforwardNetwork network, int[][] features, int[] gold, FeedforwardDependencyTrainer.Settings settings) Minibatch AdaGrad over softmax cross-entropy with cube activation and dropout, updatingnetworkin place.static FeedforwardDependencyModelrefine(FeedforwardDependencyModel model, ObjectStream<DependencySample> samples, TrainingParameters parameters) Refines a locally trained model with beam search and the early-update method of Collins and Roark (2004).(package private) static voidrequireCombinedVocabularySize(int words, int tags, int labels) Checks the combined vocabulary size the network loader allows, so a trained model always loads.private static voidrequireWithinCellLimit(int vocabularyRows, int transitionCount, int embeddingSize, int hiddenSize) private static voidFisher-Yates shuffle of the visit order.private static voidsoftmaxInPlace(double[] scores) Turns finite raw scores into probabilities in place.static FeedforwardDependencyModeltrain(String languageCode, ObjectStream<DependencySample> samples, TrainingParameters parameters) Trains a model from dependency samples.private static float[][]private static voidupdate(float[][] weights, double[][] gradients, double[][] accumulators, int batch, FeedforwardDependencyTrainer.Settings settings) One AdaGrad step on a weight matrix, with the L2 penalty folded into the gradient.private static voidupdateVector(float[] weights, double[] gradients, double[] accumulators, int batch, FeedforwardDependencyTrainer.Settings settings) One AdaGrad step on a vector without an L2 penalty: a bias or an embedding row.private static voidzero(double[][] matrix) Fills a matrix with zeros.
-
Field Details
-
EMBEDDING_SIZE_PARAM
The training parameter key of the embedding dimensionality; default 50.- See Also:
-
HIDDEN_SIZE_PARAM
The training parameter key of the hidden layer width; default 200.- See Also:
-
BATCH_SIZE_PARAM
The training parameter key of the minibatch size; default 256.- See Also:
-
LEARNING_RATE_PARAM
The training parameter key of the AdaGrad step size; default 0.02.- See Also:
-
DROPOUT_PARAM
The training parameter key of the hidden dropout probability; default 0.5.- See Also:
-
SEED_PARAM
The training parameter key of the random seed, read as anint; default 17.- See Also:
-
DEFAULT_EMBEDDING_SIZE
public static final int DEFAULT_EMBEDDING_SIZEThe default embedding dimensionality.- See Also:
-
DEFAULT_HIDDEN_SIZE
public static final int DEFAULT_HIDDEN_SIZEThe default hidden layer width.- See Also:
-
DEFAULT_EPOCHS
public static final int DEFAULT_EPOCHSThe default number of epochs.- See Also:
-
DEFAULT_BATCH_SIZE
public static final int DEFAULT_BATCH_SIZEThe default minibatch size.- See Also:
-
DEFAULT_LEARNING_RATE
public static final double DEFAULT_LEARNING_RATEThe default AdaGrad step size.- See Also:
-
DEFAULT_L2
public static final double DEFAULT_L2The default L2 penalty.- See Also:
-
DEFAULT_DROPOUT
public static final double DEFAULT_DROPOUTThe default hidden dropout probability.- See Also:
-
DEFAULT_WORD_CUTOFF
public static final int DEFAULT_WORD_CUTOFFThe default minimum word frequency for an embedding row.- See Also:
-
DEFAULT_SEED
public static final int DEFAULT_SEEDThe default random seed.- See Also:
-
DEFAULT_BEAM_SIZE
public static final int DEFAULT_BEAM_SIZEThe default refinement beam size.- See Also:
-
MAX_EMBEDDING_SIZE
static final int MAX_EMBEDDING_SIZEThe maximum embedding width.- See Also:
-
MAX_HIDDEN_SIZE
static final int MAX_HIDDEN_SIZEThe maximum hidden-layer width.- See Also:
-
logger
private static final org.slf4j.Logger logger -
ADAGRAD_EPSILON
private static final double ADAGRAD_EPSILONThe AdaGrad denominator offset that keeps the first steps finite.- See Also:
-
CUBE_DERIVATIVE_FACTOR
private static final double CUBE_DERIVATIVE_FACTORThe derivative factor of the cube activation,d/dx x^3 = 3x^2.- See Also:
-
GLOROT_NUMERATOR
private static final double GLOROT_NUMERATORThe numerator of the Glorot uniform bound,sqrt(6 / (fanIn + fanOut)).- See Also:
-
EMBEDDING_INIT_SCALE
private static final double EMBEDDING_INIT_SCALEThe half-width of the uniform range embeddings are drawn from.- See Also:
-
LOSS_PROBABILITY_FLOOR
private static final double LOSS_PROBABILITY_FLOORThe smallest probability the reported training loss takes the log of.- See Also:
-
MIN_TRANSITIONS
private static final int MIN_TRANSITIONSSHIFT and at least one RIGHT_ARC are required to parse a sentence.- See Also:
-
MIN_REFINE_BEAM_SIZE
private static final int MIN_REFINE_BEAM_SIZEThe smallest beam that can lose the gold derivation to another path.- See Also:
-
-
Constructor Details
-
FeedforwardDependencyTrainer
private FeedforwardDependencyTrainer()Prevents construction of this utility class.
-
-
Method Details
-
train
public static FeedforwardDependencyModel train(String languageCode, ObjectStream<DependencySample> samples, TrainingParameters parameters) throws IOException Trains a model from dependency samples.- Parameters:
languageCode- The ISO language code of the training data. Must not benull.samples- The training samples. Must not benull.parameters- TheTrainingParameters. Must not benull.- Returns:
- A trained
FeedforwardDependencyModel. Nevernull. - Throws:
IOException- Thrown if reading the samples fails.IllegalArgumentException- Thrown if a parameter isnull, a hyperparameter is out of range, no trainable example can be derived from the samples, a vocabulary or the three vocabularies together exceedResourceLimits.MAX_ENTRIESentries or a symbol as many UTF-8 bytes, or the network would store more thanResourceLimits.MAX_MATRIX_CELLSvalues.IllegalStateException- Thrown if an epoch produces a non-finite parameter.
-
refine
public static FeedforwardDependencyModel refine(FeedforwardDependencyModel model, ObjectStream<DependencySample> samples, TrainingParameters parameters) throws IOException Refines a locally trained model with beam search and the early-update method of Collins and Roark (2004). The loss is conditional likelihood over candidate paths scored by summed log-probabilities.Refinement trains a copy with per-sentence AdaGrad steps and no dropout.
Parameters.ITERATIONS_PARAMsets the number of passes andBeamSearch.BEAM_SIZE_PARAMETERthe beam width, which the manifest of the result names as the beam size to parse it with. The vocabularies and the transition inventory ofmodelare not extended, so the refined model carries the word cutoff ofmodel.- Parameters:
model- The locally trained model. Not modified. Must not benull.samples- The training samples. Must not benull.parameters- TheTrainingParameters; the epochs, learning rate, L2 penalty, seed, and beam size apply. Must not benull.- Returns:
- A new refined model, distinct from
model. Nevernull. - Throws:
IOException- Thrown if reading the samples fails.IllegalArgumentException- Thrown if a parameter isnull, a hyperparameter is out of range, the beam size is below 2, no trainable sample can be derived, or a sample requires a transitionmodeldoes not know.IllegalStateException- Thrown if an epoch produces a non-finite parameter, or the network produces a non-finite transition score while a sentence is decoded.
-
manifestEntries
- Parameters:
settings- The hyperparameters of the run.- Returns:
- The manifest entries recording the run. Never
null.
-
derive
private static List<FeedforwardDependencyTrainer.Derivation> derive(ObjectStream<DependencySample> samples) throws IOException Reads a sample stream into memory and derives the oracle of every projective sample once; the trainer passes over the derivations repeatedly.- Parameters:
samples- The stream to drain.- Returns:
- The derivations in stream order, without the non-projective samples.
Never
null. - Throws:
IOException- Thrown if reading the samples fails.
-
initialize
private static FeedforwardNetwork initialize(List<FeedforwardDependencyTrainer.Derivation> derivations, FeedforwardDependencyTrainer.Settings settings) Builds the vocabularies and randomly initialized weights. Symbols are assigned rows in sorted order after the reserved symbols, so the network depends only on the samples and the settings. A word, tag, or label in the training data that spells a reserved symbol shares the reserved row, as an unknown symbol does.- Parameters:
derivations- The projective training samples with their oracles.settings- The hyperparameters.- Returns:
- The untrained network. Never
null. - Throws:
IllegalArgumentException- Thrown if a vocabulary, the three vocabularies together, or the transition inventory exceedResourceLimits.MAX_ENTRIESentries, a symbol exceeds as many UTF-8 bytes, or the network would store more thanResourceLimits.MAX_MATRIX_CELLSvalues.
-
assignRows
private static int assignRows(Map<String, Integer> ids, int row, String[] reserved, List<String> observed, String label) Assigns the next embedding rows of one vocabulary: the reserved symbols first, then the observed symbols in sorted order, skipping observed symbols that spell a reserved one.- Parameters:
ids- The vocabulary to fill.row- The next free embedding row.reserved- The reserved symbols, in the order they take their rows.observed- The symbols seen in the training data; sorted in place.label- The vocabulary name used in error messages.- Returns:
- The next free embedding row after the vocabulary.
- Throws:
IllegalArgumentException- Thrown if the vocabulary exceedsResourceLimits.MAX_ENTRIESentries or a symbol as many UTF-8 bytes.
-
requireCombinedVocabularySize
static void requireCombinedVocabularySize(int words, int tags, int labels) Checks the combined vocabulary size the network loader allows, so a trained model always loads.- Parameters:
words- The word vocabulary size.tags- The tag vocabulary size.labels- The label vocabulary size.- Throws:
IllegalArgumentException- Thrown if the three sizes together exceedResourceLimits.MAX_ENTRIES.
-
requireWithinCellLimit
private static void requireWithinCellLimit(int vocabularyRows, int transitionCount, int embeddingSize, int hiddenSize) - Parameters:
vocabularyRows- The combined word, tag, and label row count.transitionCount- The output layer width.embeddingSize- The embedding dimensionality.hiddenSize- The hidden layer width.- Throws:
IllegalArgumentException- Thrown if a network of that shape stores more thanResourceLimits.MAX_MATRIX_CELLSfloat values.
-
collectExamples
private static void collectExamples(List<FeedforwardDependencyTrainer.Derivation> derivations, FeedforwardNetwork network, int[][] features, int[] gold) Replays the oracle over every derivation, emitting one example per step.- Parameters:
derivations- The projective training samples with their oracles.network- The initialized network whose vocabularies map the features.features- Receives the embedding rows of each configuration.gold- Receives the gold transition index of each configuration.
-
optimize
private static void optimize(FeedforwardNetwork network, int[][] features, int[] gold, FeedforwardDependencyTrainer.Settings settings) Minibatch AdaGrad over softmax cross-entropy with cube activation and dropout, updatingnetworkin place.- Parameters:
network- The initialized network.features- The embedding rows of every example.gold- The gold transition index of every example.settings- The hyperparameters.- Throws:
IllegalStateException- Thrown if an epoch produces a non-finite parameter.
-
softmaxInPlace
private static void softmaxInPlace(double[] scores) Turns finite raw scores into probabilities in place.- Parameters:
scores- The raw scores, overwritten with their softmax. Must not be empty.
-
update
private static void update(float[][] weights, double[][] gradients, double[][] accumulators, int batch, FeedforwardDependencyTrainer.Settings settings) One AdaGrad step on a weight matrix, with the L2 penalty folded into the gradient.- Parameters:
weights- The weights, updated in place.gradients- The summed gradients of the batch.accumulators- The AdaGrad squared-gradient sums, updated in place.batch- The number of examples the gradients sum over.settings- The hyperparameters;learningRateandl2apply.
-
updateVector
private static void updateVector(float[] weights, double[] gradients, double[] accumulators, int batch, FeedforwardDependencyTrainer.Settings settings) One AdaGrad step on a vector without an L2 penalty: a bias or an embedding row.- Parameters:
weights- The values, updated in place.gradients- The summed gradients of the batch.accumulators- The AdaGrad squared-gradient sums, updated in place.batch- The number of examples the gradients sum over.settings- The hyperparameters;learningRateapplies.
-
checkFinite
Rejects numerical overflow before returning or continuing to train a network.- Parameters:
network- The network to check.- Throws:
IllegalStateException- Thrown if any parameter is NaN or infinite.
-
checkFinite
private static void checkFinite(float[][] matrix) - Parameters:
matrix- The matrix to check.- Throws:
IllegalStateException- Thrown if any value is NaN or infinite.
-
checkFinite
private static void checkFinite(float[] vector) - Parameters:
vector- The vector to check.- Throws:
IllegalStateException- Thrown if any value is NaN or infinite.
-
uniform
- Parameters:
random- The source of randomness.rows- The row count.columns- The column count.scale- The half-width of the uniform range.- Returns:
- A matrix drawn uniformly from
[-scale, scale]. Nevernull.
-
zero
private static void zero(double[][] matrix) Fills a matrix with zeros.- Parameters:
matrix- The matrix to clear in place.
-
identity
private static int[] identity(int size) - Parameters:
size- The permutation length.- Returns:
- The identity permutation. Never
null.
-
shuffle
Fisher-Yates shuffle of the visit order.- Parameters:
order- The permutation to shuffle in place.random- The source of randomness.
-