Class FeedforwardNetwork
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 ClassesModifier and TypeClassDescription(package private) static final classReads and writes a network as aFeedforwardDependencyModelartifact: a four-byte magic, anintformat version, the three vocabularies, the transition inventory, the embedding size, and the weight matrices and vectors. -
Field Summary
FieldsModifier and TypeFieldDescriptionprivate final Transition[]private final float[][]private final intprivate final intprivate final intprivate final intThe first embedding row of each vocabulary, indexed like the vocabularies above.private static final intU+03A3, GREEK CAPITAL LETTER SIGMA, the one code point whose lowering depends on context.private static final intU+03C2, GREEK SMALL LETTER FINAL SIGMA, the lowering of the capital at the end of a word.private final float[]private final float[][]private static final intThe 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 intThe 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 intThe embedding row of the root symbol in the word and tag blocks.private final Map<Transition, Integer> private final String[](package private) static final StringThe vocabulary key of every word, tag, or label the network has no embedding row for.private static final intThe embedding row of the unknown symbol in each vocabulary block. -
Constructor Summary
ConstructorsConstructorDescriptionFeedforwardNetwork(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 TypeMethodDescription(package private) voidaddContribution(int position, int row, double[] out) Adds the hidden-layer contribution of one embedding row at one feature position.private static StringapplyFinalSigma(String word, String lowered) Replaces each word-final sigma of a lowered word with the final form.(package private) FeedforwardNetworkcopy()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 longfloatValues(long vocabularyRows, long transitionCount, long embeddingSize, long hiddenSize) (package private) float[](package private) int(package private) float[][]private static booleanisCased(int cp) private static booleanisCaseIgnorable(int cp) private static booleanisFinalSigma(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 booleanisReservedSymbol(String symbol) labelIds()(package private) int(package private) static voidlogSoftmaxInPlace(double[] scores) Turns finite raw scores into log-probabilities in place.private static intResolves 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 StringLowercases a word symbol withStringUtil.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) voidoutputScores(double[] hidden, double[] scores) Applies the output layer to hidden activations.(package private) float[][](package private) voidpreActivations(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 voidrequireColumns(float[][] matrix, int columns, String label) (package private) static voidrequireStorable(String symbol, String label) Checks that a symbol fits the length theFeedforwardNetwork.Serializerreads 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.tagIds()(package private) int[]Resolves the tags of a sentence to their tag rows once.(package private) inttransitionIndex(Transition transition) (package private) String[]private static intChecks that one vocabulary starts with its reserved symbols and occupies one consecutive block of embedding rows that no other vocabulary uses.wordIds()(package private) int[]Resolves the tokens of a sentence to their word rows once, so that extracting the features of every configuration only indexes.
-
Field Details
-
UNKNOWN
The vocabulary key of every word, tag, or label the network has no embedding row for.- See Also:
-
RESERVED_WORD_SYMBOLS
The reserved word symbols, in the order of their embedding rows. -
RESERVED_TAG_SYMBOLS
The reserved tag symbols, in the order of their embedding rows. -
RESERVED_LABEL_SYMBOLS
The reserved label symbols, in the order of their embedding rows. -
GREEK_CAPITAL_SIGMA
private static final int GREEK_CAPITAL_SIGMAU+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_SIGMAU+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_ROWSThe embedding rows the reserved symbols of all three vocabularies take. -
UNKNOWN_OFFSET
private static final int UNKNOWN_OFFSETThe embedding row of the unknown symbol in each vocabulary block.- See Also:
-
NONE_OFFSET
private static final int NONE_OFFSETThe embedding row of the absent-position symbol in each vocabulary block.- See Also:
-
ROOT_OFFSET
private static final int ROOT_OFFSETThe embedding row of the root symbol in the word and tag blocks.- See Also:
-
wordIds
-
tagIds
-
labelIds
-
firstWordRow
private final int firstWordRowThe first embedding row of each vocabulary, indexed like the vocabularies above. -
firstTagRow
private final int firstTagRow -
firstLabelRow
private final int firstLabelRow -
transitions
-
decodedTransitions
-
transitionIds
-
embeddingSize
private final int embeddingSize -
embeddings
private final float[][] embeddings -
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
- 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
Scores every transition for a configuration described by embedding rows.- Parameters:
features- The embedding rows of the configuration, as produced byFeedforwardContext.featureIds(opennlp.tools.depparse.ArcStandardState). Must not benull.cache- The contribution cache to read, ornullto compute every contribution.hidden- Scratch space for the hidden layer,hiddenSize()entries; overwritten.scores- Receives one unnormalized score per transition, indexed liketransitions(); overwritten.- Returns:
scores. Nevernull.- Throws:
IllegalArgumentException- Thrown iffeaturesisnull, does not have the required length, or contains an invalid embedding row.IllegalStateException- Thrown if the network produces a non-finite score.
-
preActivations
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, ornullto 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
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 containnull.- Returns:
- The word row per token. Never
null.
-
tagRows
Resolves the tags of a sentence to their tag rows once.- Parameters:
tags- The part-of-speech tags. Must not containnull.- Returns:
- The tag row per tag. Never
null.
-
labelRow
- Parameters:
relation- The arc label of an attached dependent, ornullfor 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
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, ornullfor an absent position.firstRow- The first row of the vocabulary block.- Returns:
- The embedding row of the symbol or of its fallback.
-
normalize
Lowercases a word symbol withStringUtil.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 benull.- Returns:
- The vocabulary key of
word, ornullifwordisnull.
-
applyFinalSigma
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:
loweredwith the Final_Sigma context applied. Nevernull.
-
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:
trueif the sigma atindexis word-final.
-
isCased
private static boolean isCased(int cp) - Parameters:
cp- The code point to test.- Returns:
trueif 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:
trueif 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
- Parameters:
symbol- The symbol to test. May benull.- Returns:
trueifsymbolis one of the reserved feature values.
-
requireStorable
Checks that a symbol fits the length theFeedforwardNetwork.Serializerreads back.- Parameters:
symbol- The symbol to check.label- The vocabulary name used in error messages.- Throws:
IllegalArgumentException- Thrown if the UTF-8 form ofsymbolis longer thanResourceLimits.MAX_ENTRIESbytes.
-
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
- Parameters:
transition- The transition to look up.- Returns:
- Its output index, or
-1if the inventory lacks it.
-
copy
FeedforwardNetwork 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. Nevernull.
-
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
- Returns:
- The immutable map from a normalized word to its embedding row. Never
null.
-
tagIds
- Returns:
- The immutable map from a tag to its embedding row. Never
null.
-
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.
-
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.
-
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.
-