Class FeedforwardNetwork

java.lang.Object
opennlp.tools.depparse.FeedforwardNetwork

final class FeedforwardNetwork extends Object
The weights of the feedforward transition parser: embeddings for words, tags, and arc labels, one hidden layer with cube activation, and a transition output layer, after Chen and Manning (2014).

The network holds every forward computation the parser and the trainer share: addContribution(int, int, double[]) is the per-position hidden sum, outputScores(double[], double[]) the output layer, score(int[], opennlp.tools.depparse.ContributionCache, double[], double[]) the complete inference pass, and logSoftmaxInPlace(double[]) the normalization of beam decoding. The trainer writes its updates into the live arrays the accessors return; the parser never modifies them, so a network that is not being trained can be shared between threads.

Each vocabulary occupies one consecutive block of embedding rows and starts with its reserved symbols, so unknown symbols, absent positions, and the artificial root always have a row. Words are matched after normalization.

Since:
3.0.0
See Also:
  • Nested Class Summary

    Nested Classes
    Modifier and Type
    Class
    Description
    (package private) static final class 
    Reads and writes a network as a FeedforwardDependencyModel artifact: a four-byte magic, an int format version, the three vocabularies, the transition inventory, the embedding size, and the weight matrices and vectors.
  • Field Summary

    Fields
    Modifier and Type
    Field
    Description
    private final Transition[]
     
    private final float[][]
     
    private final int
     
    private final int
     
    private final int
     
    private final int
    The first embedding row of each vocabulary, indexed like the vocabularies above.
    private static final int
    U+03A3, GREEK CAPITAL LETTER SIGMA, the one code point whose lowering depends on context.
    private static final int
    U+03C2, GREEK SMALL LETTER FINAL SIGMA, the lowering of the capital at the end of a word.
    private final float[]
     
    private final float[][]
     
    private final Map<String,Integer>
     
    private static final int
    The embedding row of the absent-position symbol in each vocabulary block.
    private final float[]
     
    private final float[][]
     
    (package private) static final String[]
    The reserved label symbols, in the order of their embedding rows.
    (package private) static final int
    The embedding rows the reserved symbols of all three vocabularies take.
    (package private) static final String[]
    The reserved tag symbols, in the order of their embedding rows.
    (package private) static final String[]
    The reserved word symbols, in the order of their embedding rows.
    private static final int
    The embedding row of the root symbol in the word and tag blocks.
    private final Map<String,Integer>
     
    private final Map<Transition,Integer>
     
    private final String[]
     
    (package private) static final String
    The vocabulary key of every word, tag, or label the network has no embedding row for.
    private static final int
    The embedding row of the unknown symbol in each vocabulary block.
    private final Map<String,Integer>
     
  • Constructor Summary

    Constructors
    Constructor
    Description
    FeedforwardNetwork(Map<String,Integer> wordIds, Map<String,Integer> tagIds, Map<String,Integer> labelIds, String[] transitions, int embeddingSize, float[][] embeddings, float[][] hiddenWeights, float[] hiddenBias, float[][] outputWeights, float[] outputBias)
    Assembles a network from its vocabularies and weights, copying the maps so later changes by the caller do not reach the network.
  • Method Summary

    Modifier and Type
    Method
    Description
    (package private) void
    addContribution(int position, int row, double[] out)
    Adds the hidden-layer contribution of one embedding row at one feature position.
    private static String
    applyFinalSigma(String word, String lowered)
    Replaces each word-final sigma of a lowered word with the final form.
    (package private) FeedforwardNetwork
    Creates an independent copy of this network: the weights are deep-copied and the vocabularies are shared because their maps are immutable.
    private static float[][]
    copyOf(float[][] matrix)
    Deep-copies a matrix, row by row.
    (package private) Transition[]
     
    (package private) float[][]
     
    (package private) int
     
    (package private) int
     
    (package private) int
     
    (package private) int
     
    (package private) static long
    floatValues(long vocabularyRows, long transitionCount, long embeddingSize, long hiddenSize)
     
    (package private) float[]
     
    (package private) int
     
    (package private) float[][]
     
    private static boolean
    isCased(int cp)
     
    private static boolean
     
    private static boolean
    isFinalSigma(int[] cp, int index)
    The Final_Sigma condition of the Unicode SpecialCasing data: the code point is preceded by a cased letter and then zero or more case-ignorable code points, and is not followed by zero or more case-ignorable code points and then a cased letter.
    (package private) static boolean
     
    (package private) Map<String,Integer>
     
    (package private) int
    labelRow(String relation)
     
    (package private) static void
    logSoftmaxInPlace(double[] scores)
    Turns finite raw scores into log-probabilities in place.
    private static int
    lookup(Map<String,Integer> ids, String symbol, int firstRow)
    Resolves a symbol to its embedding row: absences map to the reserved absent symbol, symbols without a row of their own to the reserved unknown symbol.
    (package private) int
     
    (package private) int
     
    (package private) static String
    Lowercases a word symbol with StringUtil.toLowerCase(CharSequence), which maps per code point, and applies the one contextual rule of the Unicode SpecialCasing data: a Greek capital sigma at the end of a word, after a cased letter and before no further cased letter, becomes the final sigma U+03C2.
    (package private) float[]
     
    (package private) void
    outputScores(double[] hidden, double[] scores)
    Applies the output layer to hidden activations.
    (package private) float[][]
     
    (package private) void
    preActivations(int[] features, ContributionCache cache, double[] pre)
    Computes the hidden pre-activations of a configuration: the bias plus the contribution of every feature position.
    private static void
    requireColumns(float[][] matrix, int columns, String label)
     
    (package private) static void
    requireStorable(String symbol, String label)
    Checks that a symbol fits the length the FeedforwardNetwork.Serializer reads back.
    (package private) int
     
    (package private) int
     
    (package private) double[]
    score(int[] features, ContributionCache cache, double[] hidden, double[] scores)
    Scores every transition for a configuration described by embedding rows.
    (package private) Map<String,Integer>
     
    (package private) int[]
    tagRows(String[] tags)
    Resolves the tags of a sentence to their tag rows once.
    (package private) int
     
    (package private) String[]
     
    private static int
    validateVocabulary(Map<String,Integer> ids, boolean[] taken, String label, String[] reserved)
    Checks that one vocabulary starts with its reserved symbols and occupies one consecutive block of embedding rows that no other vocabulary uses.
    (package private) Map<String,Integer>
     
    (package private) int[]
    wordRows(String[] tokens)
    Resolves the tokens of a sentence to their word rows once, so that extracting the features of every configuration only indexes.

    Methods inherited from class java.lang.Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Field Details

    • UNKNOWN

      static final String UNKNOWN
      The vocabulary key of every word, tag, or label the network has no embedding row for.
      See Also:
    • RESERVED_WORD_SYMBOLS

      static final String[] RESERVED_WORD_SYMBOLS
      The reserved word symbols, in the order of their embedding rows.
    • RESERVED_TAG_SYMBOLS

      static final String[] RESERVED_TAG_SYMBOLS
      The reserved tag symbols, in the order of their embedding rows.
    • RESERVED_LABEL_SYMBOLS

      static final String[] RESERVED_LABEL_SYMBOLS
      The reserved label symbols, in the order of their embedding rows.
    • GREEK_CAPITAL_SIGMA

      private static final int GREEK_CAPITAL_SIGMA
      U+03A3, GREEK CAPITAL LETTER SIGMA, the one code point whose lowering depends on context.
      See Also:
    • GREEK_SMALL_FINAL_SIGMA

      private static final int GREEK_SMALL_FINAL_SIGMA
      U+03C2, GREEK SMALL LETTER FINAL SIGMA, the lowering of the capital at the end of a word.
      See Also:
    • RESERVED_ROWS

      static final int RESERVED_ROWS
      The embedding rows the reserved symbols of all three vocabularies take.
    • UNKNOWN_OFFSET

      private static final int UNKNOWN_OFFSET
      The embedding row of the unknown symbol in each vocabulary block.
      See Also:
    • NONE_OFFSET

      private static final int NONE_OFFSET
      The embedding row of the absent-position symbol in each vocabulary block.
      See Also:
    • ROOT_OFFSET

      private static final int ROOT_OFFSET
      The embedding row of the root symbol in the word and tag blocks.
      See Also:
    • wordIds

      private final Map<String,Integer> wordIds
    • tagIds

      private final Map<String,Integer> tagIds
    • labelIds

      private final Map<String,Integer> labelIds
    • firstWordRow

      private final int firstWordRow
      The first embedding row of each vocabulary, indexed like the vocabularies above.
    • firstTagRow

      private final int firstTagRow
    • firstLabelRow

      private final int firstLabelRow
    • transitions

      private final String[] transitions
    • decodedTransitions

      private final Transition[] decodedTransitions
    • transitionIds

      private final Map<Transition,Integer> transitionIds
    • embeddingSize

      private final int embeddingSize
    • embeddings

      private final float[][] embeddings
    • hiddenWeights

      private final float[][] hiddenWeights
    • hiddenBias

      private final float[] hiddenBias
    • outputWeights

      private final float[][] outputWeights
    • outputBias

      private final float[] outputBias
  • Constructor Details

    • FeedforwardNetwork

      FeedforwardNetwork(Map<String,Integer> wordIds, Map<String,Integer> tagIds, Map<String,Integer> labelIds, String[] transitions, int embeddingSize, float[][] embeddings, float[][] hiddenWeights, float[] hiddenBias, float[][] outputWeights, float[] outputBias)
      Assembles a network from its vocabularies and weights, copying the maps so later changes by the caller do not reach the network.
      Parameters:
      wordIds - The word vocabulary, mapping each normalized word to its row.
      tagIds - The tag vocabulary.
      labelIds - The dependency label vocabulary.
      transitions - The transition inventory, indexed by output row.
      embeddingSize - The embedding dimensionality.
      embeddings - The embedding rows for words, tags, and labels.
      hiddenWeights - The hidden layer weights.
      hiddenBias - The hidden layer bias.
      outputWeights - The output layer weights.
      outputBias - The output layer bias.
      Throws:
      IllegalArgumentException - Thrown if a vocabulary lacks a reserved symbol, the vocabularies do not partition the embedding rows into consecutive blocks that start with the reserved symbols, a transition repeats or does not decode, the inventory lacks SHIFT or RIGHT_ARC, or a weight dimension does not match.
  • Method Details

    • validateVocabulary

      private static int validateVocabulary(Map<String,Integer> ids, boolean[] taken, String label, String[] reserved)
      Checks that one vocabulary starts with its reserved symbols and occupies one consecutive block of embedding rows that no other vocabulary uses.
      Parameters:
      ids - The vocabulary to check.
      taken - The rows claimed so far across all vocabularies; updated in place.
      label - The vocabulary name used in error messages.
      reserved - The reserved symbols, in the order of their rows.
      Returns:
      The first row of the block.
      Throws:
      IllegalArgumentException - Thrown if the block is not consecutive, a row is already taken, or a reserved symbol is missing or misplaced.
    • requireColumns

      private static void requireColumns(float[][] matrix, int columns, String label)
      Parameters:
      matrix - The matrix to check.
      columns - The required width of every row.
      label - The matrix name used in error messages.
      Throws:
      IllegalArgumentException - Thrown if a row has another width.
    • score

      double[] score(int[] features, ContributionCache cache, double[] hidden, double[] scores)
      Scores every transition for a configuration described by embedding rows.
      Parameters:
      features - The embedding rows of the configuration, as produced by FeedforwardContext.featureIds(opennlp.tools.depparse.ArcStandardState). Must not be null.
      cache - The contribution cache to read, or null to compute every contribution.
      hidden - Scratch space for the hidden layer, hiddenSize() entries; overwritten.
      scores - Receives one unnormalized score per transition, indexed like transitions(); overwritten.
      Returns:
      scores. Never null.
      Throws:
      IllegalArgumentException - Thrown if features is null, does not have the required length, or contains an invalid embedding row.
      IllegalStateException - Thrown if the network produces a non-finite score.
    • preActivations

      void preActivations(int[] features, ContributionCache cache, double[] pre)
      Computes the hidden pre-activations of a configuration: the bias plus the contribution of every feature position.
      Parameters:
      features - The embedding rows of the configuration, one per position.
      cache - The contribution cache to read, or null to compute every contribution.
      pre - Receives the pre-activations; overwritten.
    • addContribution

      void addContribution(int position, int row, double[] out)
      Adds the hidden-layer contribution of one embedding row at one feature position.
      Parameters:
      position - The feature position.
      row - The embedding row at that position.
      out - The hidden vector to add to.
    • outputScores

      void outputScores(double[] hidden, double[] scores)
      Applies the output layer to hidden activations.
      Parameters:
      hidden - The hidden activations after the cube.
      scores - Receives one raw score per transition; overwritten.
    • logSoftmaxInPlace

      static void logSoftmaxInPlace(double[] scores)
      Turns finite raw scores into log-probabilities in place. The maximum is removed before the sum of exponentials so a large common offset does not lose the normalizer to rounding.
      Parameters:
      scores - The raw scores, overwritten with their log-softmax. Must not be empty.
    • wordRows

      int[] wordRows(String[] tokens)
      Resolves the tokens of a sentence to their word rows once, so that extracting the features of every configuration only indexes.
      Parameters:
      tokens - The sentence tokens. Must not contain null.
      Returns:
      The word row per token. Never null.
    • tagRows

      int[] tagRows(String[] tags)
      Resolves the tags of a sentence to their tag rows once.
      Parameters:
      tags - The part-of-speech tags. Must not contain null.
      Returns:
      The tag row per tag. Never null.
    • labelRow

      int labelRow(String relation)
      Parameters:
      relation - The arc label of an attached dependent, or null for an absent position.
      Returns:
      The label row, falling back to the unknown row.
    • rootWordRow

      int rootWordRow()
      Returns:
      The word row standing for the artificial root.
    • noneWordRow

      int noneWordRow()
      Returns:
      The word row standing for an absent position.
    • rootTagRow

      int rootTagRow()
      Returns:
      The tag row standing for the artificial root.
    • noneTagRow

      int noneTagRow()
      Returns:
      The tag row standing for an absent position.
    • lookup

      private static int lookup(Map<String,Integer> ids, String symbol, int firstRow)
      Resolves a symbol to its embedding row: absences map to the reserved absent symbol, symbols without a row of their own to the reserved unknown symbol.
      Parameters:
      ids - The vocabulary to resolve against.
      symbol - The symbol to resolve, or null for an absent position.
      firstRow - The first row of the vocabulary block.
      Returns:
      The embedding row of the symbol or of its fallback.
    • normalize

      static String normalize(String word)
      Lowercases a word symbol with StringUtil.toLowerCase(CharSequence), which maps per code point, and applies the one contextual rule of the Unicode SpecialCasing data: a Greek capital sigma at the end of a word, after a cased letter and before no further cased letter, becomes the final sigma U+03C2. Reserved symbols and absences pass through.
      Parameters:
      word - The word to normalize. May be null.
      Returns:
      The vocabulary key of word, or null if word is null.
    • applyFinalSigma

      private static String applyFinalSigma(String word, String lowered)
      Replaces each word-final sigma of a lowered word with the final form. The lowering maps one code point to one code point, so both arrays index the same positions.
      Parameters:
      word - The word before lowering.
      lowered - The word lowered per code point.
      Returns:
      lowered with the Final_Sigma context applied. Never null.
    • isFinalSigma

      private static boolean isFinalSigma(int[] cp, int index)
      The Final_Sigma condition of the Unicode SpecialCasing data: the code point is preceded by a cased letter and then zero or more case-ignorable code points, and is not followed by zero or more case-ignorable code points and then a cased letter.
      Parameters:
      cp - The code points of the sequence.
      index - The position of the capital sigma.
      Returns:
      true if the sigma at index is word-final.
    • isCased

      private static boolean isCased(int cp)
      Parameters:
      cp - The code point to test.
      Returns:
      true if the code point has the Unicode Cased property: an upper, lower, or title case letter, including the Other_Uppercase and Other_Lowercase code points.
    • isCaseIgnorable

      private static boolean isCaseIgnorable(int cp)
      Parameters:
      cp - The code point to test.
      Returns:
      true if the code point has the Unicode Case_Ignorable property: the general categories Mn, Me, Cf, Lm, and Sk, and the Word_Break values MidLetter, MidNumLet, and Single_Quote.
    • isReservedSymbol

      static boolean isReservedSymbol(String symbol)
      Parameters:
      symbol - The symbol to test. May be null.
      Returns:
      true if symbol is one of the reserved feature values.
    • requireStorable

      static void requireStorable(String symbol, String label)
      Checks that a symbol fits the length the FeedforwardNetwork.Serializer reads back.
      Parameters:
      symbol - The symbol to check.
      label - The vocabulary name used in error messages.
      Throws:
      IllegalArgumentException - Thrown if the UTF-8 form of symbol is longer than ResourceLimits.MAX_ENTRIES bytes.
    • transitions

      String[] transitions()
      Returns:
      The transition outcome strings by output index. Never null.
    • decodedTransitions

      Transition[] decodedTransitions()
      Returns:
      The decoded transitions by output index. Never null.
    • transitionIndex

      int transitionIndex(Transition transition)
      Parameters:
      transition - The transition to look up.
      Returns:
      Its output index, or -1 if the inventory lacks it.
    • copy

      Creates an independent copy of this network: the weights are deep-copied and the vocabularies are shared because their maps are immutable.
      Returns:
      A copy sharing no mutable state with this network. Never null.
    • copyOf

      private static float[][] copyOf(float[][] matrix)
      Deep-copies a matrix, row by row.
      Parameters:
      matrix - The matrix to copy.
      Returns:
      A copy sharing no rows with matrix. Never null.
    • floatValues

      static long floatValues(long vocabularyRows, long transitionCount, long embeddingSize, long 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.
      Returns:
      The number of float values a network of that shape stores.
    • wordIds

      Map<String,Integer> wordIds()
      Returns:
      The immutable map from a normalized word to its embedding row. Never null.
    • tagIds

      Map<String,Integer> tagIds()
      Returns:
      The immutable map from a tag to its embedding row. Never null.
    • labelIds

      Map<String,Integer> labelIds()
      Returns:
      The immutable map from an arc label to its embedding row. Never null.
    • firstWordRow

      int firstWordRow()
      Returns:
      The first embedding row of the word vocabulary block.
    • firstTagRow

      int firstTagRow()
      Returns:
      The first embedding row of the tag vocabulary block.
    • firstLabelRow

      int firstLabelRow()
      Returns:
      The first embedding row of the label vocabulary block.
    • embeddingSize

      int embeddingSize()
      Returns:
      The width of one embedding row.
    • hiddenSize

      int hiddenSize()
      Returns:
      The hidden layer width.
    • embeddings

      float[][] embeddings()
      Returns:
      The live embedding matrix, one row per vocabulary entry, not a copy: the trainer writes its updates into it. Never null.
    • hiddenWeights

      float[][] hiddenWeights()
      Returns:
      The live hidden layer weights, not a copy. Never null.
    • hiddenBias

      float[] hiddenBias()
      Returns:
      The live hidden layer bias, not a copy. Never null.
    • outputWeights

      float[][] outputWeights()
      Returns:
      The live output layer weights, one row per transition, not a copy. Never null.
    • outputBias

      float[] outputBias()
      Returns:
      The live output layer bias, one entry per transition, not a copy. Never null.