You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@opennlp.apache.org by rz...@apache.org on 2026/10/02 08:37:28 UTC

(opennlp) 01/01: Minor: Share BERT tokens and softmax in opennlp-dl, skip empty vocab lines

This is an automated email from the ASF dual-hosted git repository.

rzo1 pushed a commit to branch minor-dedup-dl-tokens-softmax-vocab
in repository https://gitbox.apache.org/repos/asf/opennlp.git

commit d669472c62efe15795c2dc86559645ceb117053c
Author: Richard Zowalla <rz...@apache.org>
AuthorDate: Fri Oct 2 10:25:25 2026 +0200

    Minor: Share BERT tokens and softmax in opennlp-dl, skip empty vocab lines
    
    NameFinderDL SEPARATOR, CLS_TOKEN and SPECIAL_TOKENS use WordpieceTokenizer constants.
    DocumentCategorizerDL.softmax delegates to AbstractDL.softmaxProbabilities and
    NameFinderDL.labelProbability to the allocation-free AbstractDL.softmaxProbability;
    both share one documented non-finite score rule.
    Plain-text vocab loading skips empty lines but keeps line-based ids.
---
 .../src/main/java/opennlp/dl/AbstractDL.java       | 149 ++++++++++++++++++++-
 .../opennlp/dl/doccat/DocumentCategorizerDL.java   |  35 +----
 .../java/opennlp/dl/namefinder/NameFinderDL.java   |  48 ++-----
 .../java/opennlp/dl/AbstractDLSoftmaxTest.java     | 105 +++++++++++++++
 .../src/test/java/opennlp/dl/LoadVocabTest.java    |  26 ++++
 5 files changed, 290 insertions(+), 73 deletions(-)

diff --git a/opennlp-core/opennlp-ml/opennlp-dl/src/main/java/opennlp/dl/AbstractDL.java b/opennlp-core/opennlp-ml/opennlp-dl/src/main/java/opennlp/dl/AbstractDL.java
index 919bc5155..1b05d0607 100644
--- a/opennlp-core/opennlp-ml/opennlp-dl/src/main/java/opennlp/dl/AbstractDL.java
+++ b/opennlp-core/opennlp-ml/opennlp-dl/src/main/java/opennlp/dl/AbstractDL.java
@@ -34,6 +34,7 @@ import ai.onnxruntime.OrtEnvironment;
 import ai.onnxruntime.OrtException;
 import ai.onnxruntime.OrtSession;
 
+import opennlp.tools.commons.Internal;
 import opennlp.tools.tokenize.SubwordPiece;
 import opennlp.tools.tokenize.SubwordTokenizer;
 import opennlp.tools.tokenize.WordpieceEncoder;
@@ -162,8 +163,9 @@ public abstract class AbstractDL implements AutoCloseable {
    * Loads a vocabulary {@link File} from disk. A file with an opening brace as its first
    * non-whitespace character is read as JSON: one object that maps each token to a non-negative
    * integer ID, as in {@code vocab.json}. Any other file is read as plain text with one token
-   * per line, the line number being the ID, as in {@code vocab.txt}. A byte order mark at the
-   * start of the file is not content in either format. The JSON layout is that of
+   * per line, the line number being the ID, as in {@code vocab.txt}. An empty line in a plain
+   * text file is skipped but still counts toward the IDs of the lines after it. A byte order
+   * mark at the start of the file is not content in either format. The JSON layout is that of
    * {@link #loadJsonVocab(String)}.
    *
    * @param vocabFile The vocabulary file.
@@ -210,9 +212,12 @@ public abstract class AbstractDL implements AutoCloseable {
     final AtomicInteger counter =
         new AtomicInteger(0);
 
-    content.lines().forEach(line ->
-        vocab.put(line, counter.getAndIncrement())
-    );
+    content.lines().forEach(line -> {
+      final int id = counter.getAndIncrement();
+      if (!line.isEmpty()) {
+        vocab.put(line, id);
+      }
+    });
 
     return vocab;
   }
@@ -578,6 +583,140 @@ public abstract class AbstractDL implements AutoCloseable {
     }
   }
 
+  /**
+   * Converts model scores into a probability distribution with a softmax that subtracts the
+   * largest score before exponentiating, so large finite scores do not overflow.
+   *
+   * <p>Non-finite scores follow one rule: if any score is {@code +Infinity}, those entries share
+   * the probability mass equally and all others get {@code 0}. Otherwise {@code NaN} scores are
+   * left out of the normalization and get {@code NaN}, and {@code -Infinity} scores get
+   * {@code 0}. If no score is finite or {@code +Infinity}, every entry gets
+   * {@code 1 / scores.length}.</p>
+   *
+   * @param scores The raw model scores. Must not be {@code null}.
+   * @return The probabilities, in the order of {@code scores}.
+   * @throws IllegalArgumentException Thrown if {@code scores} is {@code null}.
+   */
+  @Internal(since = "3.0.0")
+  protected static double[] softmaxProbabilities(final float[] scores) {
+    requireNonNullArg(scores, "scores");
+
+    final int positiveInfinityCount = countPositiveInfinity(scores);
+    final double max = maxNonNaNScore(scores);
+    final double denominator = softmaxDenominator(scores, positiveInfinityCount, max);
+
+    final double[] probabilities = new double[scores.length];
+    for (int i = 0; i < scores.length; i++) {
+      probabilities[i] =
+          softmaxProbability(scores[i], scores.length, positiveInfinityCount, max, denominator);
+    }
+    return probabilities;
+  }
+
+  /**
+   * Computes the probability of one entry of
+   * {@link #softmaxProbabilities(float[])} without allocating the full distribution.
+   *
+   * @param scores The raw model scores. Must not be {@code null}.
+   * @param index The index of the score whose probability is returned. Must be a valid index
+   *     into {@code scores}.
+   * @return The probability at {@code index}, following the non-finite score rule of
+   *     {@link #softmaxProbabilities(float[])}.
+   * @throws IllegalArgumentException Thrown if {@code scores} is {@code null} or {@code index}
+   *     is out of range.
+   */
+  @Internal(since = "3.0.0")
+  protected static double softmaxProbability(final float[] scores, final int index) {
+    requireNonNullArg(scores, "scores");
+    if (index < 0 || index >= scores.length) {
+      throw new IllegalArgumentException("The index " + index
+          + " is out of range for " + scores.length + " scores.");
+    }
+
+    final int positiveInfinityCount = countPositiveInfinity(scores);
+    final double max = maxNonNaNScore(scores);
+    final double denominator = softmaxDenominator(scores, positiveInfinityCount, max);
+    return softmaxProbability(scores[index], scores.length, positiveInfinityCount, max,
+        denominator);
+  }
+
+  /**
+   * Counts the {@code +Infinity} entries of {@code scores}.
+   *
+   * @param scores The raw model scores.
+   * @return The number of {@code +Infinity} scores.
+   */
+  private static int countPositiveInfinity(final float[] scores) {
+    int count = 0;
+    for (final float score : scores) {
+      if (score == Float.POSITIVE_INFINITY) {
+        count++;
+      }
+    }
+    return count;
+  }
+
+  /**
+   * Finds the largest score that is neither {@code NaN} nor {@code +Infinity}.
+   *
+   * @param scores The raw model scores.
+   * @return The largest such score, or {@code -Infinity} if there is none.
+   */
+  private static double maxNonNaNScore(final float[] scores) {
+    double max = Double.NEGATIVE_INFINITY;
+    for (final float score : scores) {
+      if (score != Float.POSITIVE_INFINITY && !Float.isNaN(score) && score > max) {
+        max = score;
+      }
+    }
+    return max;
+  }
+
+  /**
+   * Sums {@code exp(score - max)} over the non-{@code NaN} scores.
+   *
+   * @param scores The raw model scores.
+   * @param positiveInfinityCount The number of {@code +Infinity} scores.
+   * @param max The result of {@link #maxNonNaNScore(float[])}.
+   * @return The softmax denominator, or {@code 0} if the distribution does not need one because
+   *     a score is {@code +Infinity} or no score is finite.
+   */
+  private static double softmaxDenominator(final float[] scores, final int positiveInfinityCount,
+                                           final double max) {
+    if (positiveInfinityCount > 0 || max == Double.NEGATIVE_INFINITY) {
+      return 0d;
+    }
+    double denominator = 0d;
+    for (final float score : scores) {
+      if (!Float.isNaN(score)) {
+        denominator += Math.exp(score - max);
+      }
+    }
+    return denominator;
+  }
+
+  /**
+   * Applies the softmax rule of {@link #softmaxProbabilities(float[])} to one score.
+   *
+   * @param score The score to normalize.
+   * @param length The number of scores.
+   * @param positiveInfinityCount The number of {@code +Infinity} scores.
+   * @param max The result of {@link #maxNonNaNScore(float[])}.
+   * @param denominator The result of {@link #softmaxDenominator(float[], int, double)}.
+   * @return The probability of {@code score}.
+   */
+  private static double softmaxProbability(final float score, final int length,
+                                           final int positiveInfinityCount, final double max,
+                                           final double denominator) {
+    if (positiveInfinityCount > 0) {
+      return score == Float.POSITIVE_INFINITY ? 1d / positiveInfinityCount : 0d;
+    }
+    if (max == Double.NEGATIVE_INFINITY) {
+      return 1d / length;
+    }
+    return Math.exp(score - max) / denominator;
+  }
+
   // Null parameters report IllegalArgumentException rather than requireNonNull's
   // NullPointerException, matching the parameter contract of the engine and tokenizer layers.
   protected static void requireNonNullArg(Object value, String name) {
diff --git a/opennlp-core/opennlp-ml/opennlp-dl/src/main/java/opennlp/dl/doccat/DocumentCategorizerDL.java b/opennlp-core/opennlp-ml/opennlp-dl/src/main/java/opennlp/dl/doccat/DocumentCategorizerDL.java
index 208cb573e..19acddb0a 100644
--- a/opennlp-core/opennlp-ml/opennlp-dl/src/main/java/opennlp/dl/doccat/DocumentCategorizerDL.java
+++ b/opennlp-core/opennlp-ml/opennlp-dl/src/main/java/opennlp/dl/doccat/DocumentCategorizerDL.java
@@ -390,46 +390,21 @@ public class DocumentCategorizerDL extends AbstractDL implements DocumentCategor
   }
 
   /**
-   * Applies softmax to an array of values.
+   * Applies {@link AbstractDL#softmaxProbabilities(float[])} to the logits of one document chunk.
    *
-   * @param input An array of values.
-   * @return The output array.
+   * @param input The logits produced by the model.
+   * @return The classification distribution, in the order of {@code input}.
+   * @throws IllegalStateException Thrown if any logit is {@code NaN} or infinite.
    */
   static double[] softmax(final float[] input) {
-
-    // Subtract the maximum before exponentiating (numerically stable softmax): exp() of a
-    // large logit otherwise overflows to +Infinity, yielding NaN scores. Mathematically
-    // identical to the naive form. Results are kept in double precision throughout.
-    double max = Double.NEGATIVE_INFINITY;
     for (final float value : input) {
-      // Reject any non-finite logit, not just NaN: a +Infinity logit makes max == +Inf, so
-      // value - max is Inf - Inf == NaN and the whole distribution silently goes NaN. Subtracting
-      // the maximum already handles merely-large finite logits, so only NaN/Infinity reach here.
       if (!Float.isFinite(value)) {
         throw new IllegalStateException(
             "The model produced a non-finite logit (NaN or Infinity); cannot compute a "
                 + "classification distribution");
       }
-      max = Math.max(max, value);
     }
-
-    final double[] t = new double[input.length];
-    double sum = 0.0;
-
-    for (int x = 0; x < input.length; x++) {
-      final double val = Math.exp(input[x] - max);
-      sum += val;
-      t[x] = val;
-    }
-
-    final double[] output = new double[input.length];
-
-    for (int x = 0; x < output.length; x++) {
-      output[x] = t[x] / sum;
-    }
-
-    return output;
-
+    return softmaxProbabilities(input);
   }
 
   private int maxIndex(double[] arr) {
diff --git a/opennlp-core/opennlp-ml/opennlp-dl/src/main/java/opennlp/dl/namefinder/NameFinderDL.java b/opennlp-core/opennlp-ml/opennlp-dl/src/main/java/opennlp/dl/namefinder/NameFinderDL.java
index 877b15c2d..6553042d0 100644
--- a/opennlp-core/opennlp-ml/opennlp-dl/src/main/java/opennlp/dl/namefinder/NameFinderDL.java
+++ b/opennlp-core/opennlp-ml/opennlp-dl/src/main/java/opennlp/dl/namefinder/NameFinderDL.java
@@ -70,12 +70,14 @@ import opennlp.tools.util.normalizer.Alignment;
 @ThreadSafe
 public class NameFinderDL extends AbstractDL implements OffsetMappingNameFinder {
 
-  public static final String SEPARATOR = "[SEP]";
-  public static final String CLS_TOKEN = "[CLS]";
+  /** The BERT separator token, equal to {@link WordpieceTokenizer#BERT_SEP_TOKEN}. */
+  public static final String SEPARATOR = WordpieceTokenizer.BERT_SEP_TOKEN;
+  /** The BERT classification token, equal to {@link WordpieceTokenizer#BERT_CLS_TOKEN}. */
+  public static final String CLS_TOKEN = WordpieceTokenizer.BERT_CLS_TOKEN;
 
   // Tokenizer-added markers (BERT and RoBERTa) that must never appear in a reconstructed span.
   private static final Set<String> SPECIAL_TOKENS = Set.of(
-      CLS_TOKEN, SEPARATOR,
+      WordpieceTokenizer.BERT_CLS_TOKEN, WordpieceTokenizer.BERT_SEP_TOKEN,
       WordpieceTokenizer.ROBERTA_CLS_TOKEN, WordpieceTokenizer.ROBERTA_SEP_TOKEN);
 
   /** Prefix used by BIO labels for the first token in an entity span. */
@@ -568,46 +570,16 @@ public class NameFinderDL extends AbstractDL implements OffsetMappingNameFinder
   }
 
   /**
-   * Normalizes model scores into a probability for one label index using a numerically stable
-   * softmax.
+   * Normalizes model scores into a probability for one label index with
+   * {@link AbstractDL#softmaxProbability(float[], int)}.
    *
    * @param scores The raw model scores for one token.
    * @param labelIndex The label index whose probability should be returned.
-   * @return The normalized probability in {@code [0, 1]}.
+   * @return The normalized probability, following the non-finite score rule of
+   *     {@link AbstractDL#softmaxProbabilities(float[])}.
    */
   static double labelProbability(float[] scores, int labelIndex) {
-
-    int positiveInfinityCount = 0;
-    double max = Float.NEGATIVE_INFINITY;
-
-    for (float score : scores) {
-      if (score == Float.POSITIVE_INFINITY) {
-        positiveInfinityCount++;
-      } else if (!Float.isNaN(score) && score > max) {
-        max = score;
-      }
-    }
-
-    if (positiveInfinityCount > 0) {
-      // From decodeSpans, labelIndex is always the argmax, so when any +Inf is present the chosen
-      // score is +Inf and this returns 1/(number of +Inf). The 0d arm covers a direct caller
-      // asking for a non-+Inf label's probability while a +Inf label exists (exercised by tests).
-      return scores[labelIndex] == Float.POSITIVE_INFINITY ? 1d / positiveInfinityCount : 0d;
-    }
-
-    if (max == Float.NEGATIVE_INFINITY) {
-      return 1d / scores.length;
-    }
-
-    double denominator = 0;
-    for (float score : scores) {
-      if (!Float.isNaN(score)) {
-        denominator += Math.exp(score - max);
-      }
-    }
-
-    return Math.exp(scores[labelIndex] - max) / denominator;
-
+    return softmaxProbability(scores, labelIndex);
   }
 
   /**
diff --git a/opennlp-core/opennlp-ml/opennlp-dl/src/test/java/opennlp/dl/AbstractDLSoftmaxTest.java b/opennlp-core/opennlp-ml/opennlp-dl/src/test/java/opennlp/dl/AbstractDLSoftmaxTest.java
new file mode 100644
index 000000000..f43527e70
--- /dev/null
+++ b/opennlp-core/opennlp-ml/opennlp-dl/src/test/java/opennlp/dl/AbstractDLSoftmaxTest.java
@@ -0,0 +1,105 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package opennlp.dl;
+
+import java.util.stream.Stream;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+class AbstractDLSoftmaxTest {
+
+  private static final float NAN = Float.NaN;
+  private static final float POS_INF = Float.POSITIVE_INFINITY;
+  private static final float NEG_INF = Float.NEGATIVE_INFINITY;
+
+  static Stream<Arguments> distributions() {
+    return Stream.of(
+        Arguments.of(new float[] {}, new double[] {}),
+        Arguments.of(new float[] {5f}, new double[] {1d}),
+        Arguments.of(new float[] {0f, 0f, 0f}, new double[] {1d / 3, 1d / 3, 1d / 3}),
+        Arguments.of(new float[] {1f, 2f, 3f},
+            new double[] {0.09003057317038046, 0.24472847105479764, 0.6652409557748219}),
+        Arguments.of(new float[] {1000f, 1001f},
+            new double[] {0.2689414213699951, 0.7310585786300049}),
+        Arguments.of(new float[] {0f, NEG_INF, 0f}, new double[] {0.5, 0d, 0.5}),
+        Arguments.of(new float[] {0f, POS_INF, POS_INF, NAN}, new double[] {0d, 0.5, 0.5, 0d}),
+        Arguments.of(new float[] {NEG_INF, NAN}, new double[] {0.5, 0.5}),
+        Arguments.of(new float[] {0f, NAN, 0f}, new double[] {0.5, Double.NaN, 0.5}));
+  }
+
+  @ParameterizedTest
+  @MethodSource("distributions")
+  void testSoftmaxProbabilities(float[] scores, double[] expected) {
+    assertArrayEquals(expected, AbstractDL.softmaxProbabilities(scores), 1e-12);
+  }
+
+  @ParameterizedTest
+  @MethodSource("distributions")
+  void testSoftmaxProbabilityMatchesDistribution(float[] scores, double[] expected) {
+    for (int i = 0; i < scores.length; i++) {
+      assertEquals(expected[i], AbstractDL.softmaxProbability(scores, i), 1e-12);
+    }
+  }
+
+  @Test
+  void testSoftmaxProbabilityRejectsNullScores() {
+    final IllegalArgumentException e =
+        assertThrows(IllegalArgumentException.class, () -> AbstractDL.softmaxProbability(null, 0));
+    assertEquals("The scores must not be null.", e.getMessage());
+  }
+
+  @ParameterizedTest
+  @ValueSource(ints = {-1, 3})
+  void testSoftmaxProbabilityRejectsIndexOutOfRange(int index) {
+    final IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
+        () -> AbstractDL.softmaxProbability(new float[] {1f, 2f, 3f}, index));
+    assertEquals("The index " + index + " is out of range for 3 scores.", e.getMessage());
+  }
+
+  @Test
+  void testSoftmaxProbabilitiesStaysFiniteForLargeScores() {
+    final double[] out =
+        AbstractDL.softmaxProbabilities(new float[] {Float.MAX_VALUE, Float.MAX_VALUE});
+
+    assertArrayEquals(new double[] {0.5, 0.5}, out, 1e-12);
+  }
+
+  @Test
+  void testSoftmaxProbabilitiesDoesNotModifyScores() {
+    final float[] scores = {1f, 2f, 3f};
+
+    AbstractDL.softmaxProbabilities(scores);
+
+    assertArrayEquals(new float[] {1f, 2f, 3f}, scores);
+  }
+
+  @Test
+  void testSoftmaxProbabilitiesRejectsNullScores() {
+    final IllegalArgumentException e =
+        assertThrows(IllegalArgumentException.class, () -> AbstractDL.softmaxProbabilities(null));
+    assertEquals("The scores must not be null.", e.getMessage());
+  }
+}
diff --git a/opennlp-core/opennlp-ml/opennlp-dl/src/test/java/opennlp/dl/LoadVocabTest.java b/opennlp-core/opennlp-ml/opennlp-dl/src/test/java/opennlp/dl/LoadVocabTest.java
index 90940ba4e..8ace1843d 100644
--- a/opennlp-core/opennlp-ml/opennlp-dl/src/test/java/opennlp/dl/LoadVocabTest.java
+++ b/opennlp-core/opennlp-ml/opennlp-dl/src/test/java/opennlp/dl/LoadVocabTest.java
@@ -220,6 +220,32 @@ public class LoadVocabTest {
     assertEquals(Map.of("[CLS]", 0, "[SEP]", 1), AbstractDL.loadVocabFile(tempFile));
   }
 
+  static Stream<Arguments> plainTextVocabWithEmptyLines() {
+    return Stream.of(
+        Arguments.of("[CLS]\n[SEP]\n\n", Map.of("[CLS]", 0, "[SEP]", 1)),
+        Arguments.of("[CLS]\n\n[SEP]\n", Map.of("[CLS]", 0, "[SEP]", 2)),
+        Arguments.of("\n[CLS]\r\n\r\n[SEP]\r\n", Map.of("[CLS]", 1, "[SEP]", 3)),
+        Arguments.of("[CLS]\n \n[SEP]\n", Map.of("[CLS]", 0, " ", 1, "[SEP]", 2)),
+        Arguments.of("\uD835\uDC00\n\n[SEP]\n", Map.of("\uD835\uDC00", 0, "[SEP]", 2)));
+  }
+
+  @ParameterizedTest
+  @MethodSource("plainTextVocabWithEmptyLines")
+  void testPlainTextVocabFileSkipsEmptyLinesAndKeepsLineIds(String content,
+                                                           Map<String, Integer> expected)
+      throws IOException {
+    final File tempFile = vocabFile("vocab-empty-lines.txt", content);
+
+    assertEquals(expected, AbstractDL.loadVocabFile(tempFile));
+  }
+
+  @Test
+  void testPlainTextVocabFileWithATrailingEmptyLineBuildsAnEncoder() throws IOException {
+    final File tempFile = vocabFile("vocab-trailing.txt", "[PAD]\n[UNK]\n[CLS]\n[SEP]\nhello\n\n");
+
+    assertNotNull(AbstractDL.createWordpieceEncoder(AbstractDL.loadVocabFile(tempFile), true));
+  }
+
   @ParameterizedTest
   @ValueSource(strings = {"2147483648", "4294967296", "9223372036854775808",
       "12345678901234567890"})