Class FeedforwardDependencyTrainer

java.lang.Object
opennlp.tools.depparse.FeedforwardDependencyTrainer

public final class FeedforwardDependencyTrainer extends Object
Trains the 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
  • Field Details

    • EMBEDDING_SIZE_PARAM

      public static final String EMBEDDING_SIZE_PARAM
      The training parameter key of the embedding dimensionality; default 50.
      See Also:
    • HIDDEN_SIZE_PARAM

      public static final String HIDDEN_SIZE_PARAM
      The training parameter key of the hidden layer width; default 200.
      See Also:
    • BATCH_SIZE_PARAM

      public static final String BATCH_SIZE_PARAM
      The training parameter key of the minibatch size; default 256.
      See Also:
    • LEARNING_RATE_PARAM

      public static final String LEARNING_RATE_PARAM
      The training parameter key of the AdaGrad step size; default 0.02.
      See Also:
    • DROPOUT_PARAM

      public static final String DROPOUT_PARAM
      The training parameter key of the hidden dropout probability; default 0.5.
      See Also:
    • SEED_PARAM

      public static final String SEED_PARAM
      The training parameter key of the random seed, read as an int; default 17.
      See Also:
    • DEFAULT_EMBEDDING_SIZE

      public static final int DEFAULT_EMBEDDING_SIZE
      The default embedding dimensionality.
      See Also:
    • DEFAULT_HIDDEN_SIZE

      public static final int DEFAULT_HIDDEN_SIZE
      The default hidden layer width.
      See Also:
    • DEFAULT_EPOCHS

      public static final int DEFAULT_EPOCHS
      The default number of epochs.
      See Also:
    • DEFAULT_BATCH_SIZE

      public static final int DEFAULT_BATCH_SIZE
      The default minibatch size.
      See Also:
    • DEFAULT_LEARNING_RATE

      public static final double DEFAULT_LEARNING_RATE
      The default AdaGrad step size.
      See Also:
    • DEFAULT_L2

      public static final double DEFAULT_L2
      The default L2 penalty.
      See Also:
    • DEFAULT_DROPOUT

      public static final double DEFAULT_DROPOUT
      The default hidden dropout probability.
      See Also:
    • DEFAULT_WORD_CUTOFF

      public static final int DEFAULT_WORD_CUTOFF
      The default minimum word frequency for an embedding row.
      See Also:
    • DEFAULT_SEED

      public static final int DEFAULT_SEED
      The default random seed.
      See Also:
    • DEFAULT_BEAM_SIZE

      public static final int DEFAULT_BEAM_SIZE
      The default refinement beam size.
      See Also:
    • MAX_EMBEDDING_SIZE

      static final int MAX_EMBEDDING_SIZE
      The maximum embedding width.
      See Also:
    • MAX_HIDDEN_SIZE

      static final int MAX_HIDDEN_SIZE
      The maximum hidden-layer width.
      See Also:
    • logger

      private static final org.slf4j.Logger logger
    • ADAGRAD_EPSILON

      private static final double ADAGRAD_EPSILON
      The AdaGrad denominator offset that keeps the first steps finite.
      See Also:
    • CUBE_DERIVATIVE_FACTOR

      private static final double CUBE_DERIVATIVE_FACTOR
      The derivative factor of the cube activation, d/dx x^3 = 3x^2.
      See Also:
    • GLOROT_NUMERATOR

      private static final double GLOROT_NUMERATOR
      The numerator of the Glorot uniform bound, sqrt(6 / (fanIn + fanOut)).
      See Also:
    • EMBEDDING_INIT_SCALE

      private static final double EMBEDDING_INIT_SCALE
      The half-width of the uniform range embeddings are drawn from.
      See Also:
    • LOSS_PROBABILITY_FLOOR

      private static final double LOSS_PROBABILITY_FLOOR
      The smallest probability the reported training loss takes the log of.
      See Also:
    • MIN_TRANSITIONS

      private static final int MIN_TRANSITIONS
      SHIFT 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_SIZE
      The 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 be null.
      samples - The training samples. Must not be null.
      parameters - The TrainingParameters. Must not be null.
      Returns:
      A trained FeedforwardDependencyModel. Never null.
      Throws:
      IOException - Thrown if reading the samples fails.
      IllegalArgumentException - Thrown if a parameter is null, a hyperparameter is out of range, no trainable example can be derived from the samples, a vocabulary or the three vocabularies together exceed ResourceLimits.MAX_ENTRIES entries or a symbol as many UTF-8 bytes, or the network would store more than ResourceLimits.MAX_MATRIX_CELLS values.
      IllegalStateException - Thrown if an epoch produces a non-finite parameter.
    • refine

      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_PARAM sets the number of passes and BeamSearch.BEAM_SIZE_PARAMETER the beam width, which the manifest of the result names as the beam size to parse it with. The vocabularies and the transition inventory of model are not extended, so the refined model carries the word cutoff of model.

      Parameters:
      model - The locally trained model. Not modified. Must not be null.
      samples - The training samples. Must not be null.
      parameters - The TrainingParameters; the epochs, learning rate, L2 penalty, seed, and beam size apply. Must not be null.
      Returns:
      A new refined model, distinct from model. Never null.
      Throws:
      IOException - Thrown if reading the samples fails.
      IllegalArgumentException - Thrown if a parameter is null, a hyperparameter is out of range, the beam size is below 2, no trainable sample can be derived, or a sample requires a transition model does 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

      private static Map<String,String> manifestEntries(FeedforwardDependencyTrainer.Settings settings)
      Parameters:
      settings - The hyperparameters of the run.
      Returns:
      The manifest entries recording the run. Never null.
    • derive

      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

      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 exceed ResourceLimits.MAX_ENTRIES entries, a symbol exceeds as many UTF-8 bytes, or the network would store more than ResourceLimits.MAX_MATRIX_CELLS values.
    • 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 exceeds ResourceLimits.MAX_ENTRIES entries 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 exceed ResourceLimits.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 than ResourceLimits.MAX_MATRIX_CELLS float 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, updating network in 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; learningRate and l2 apply.
    • 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; learningRate applies.
    • checkFinite

      private static void checkFinite(FeedforwardNetwork network)
      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

      private static float[][] uniform(Random random, int rows, int columns, double scale)
      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]. Never null.
    • 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

      private static void shuffle(int[] order, Random random)
      Fisher-Yates shuffle of the visit order.
      Parameters:
      order - The permutation to shuffle in place.
      random - The source of randomness.