You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@opennlp.apache.org by "krickert (via GitHub)" <gi...@apache.org> on 2026/08/22 01:00:54 UTC

[PR] OPENNLP-547: Add a dependency parser component (opennlp)

krickert opened a new pull request, #1236:
URL: https://github.com/apache/opennlp/pull/1236

   ## Summary
   
   - add a dependency parser API and immutable dependency graph model
   - provide classical transition parsing and a pure Java feedforward training and inference tier
   - add CoNLL-U reading, evaluation, reproducible model persistence, tests, and user documentation
   
   ## Stack
   
   This draft is temporarily based on OPENNLP-1888-DocumentShape so the later Document annotation PRs form a clean review stack. The dependency parser itself does not require the Document API. After #1182 merges, this PR can target main.
   
   ## Verification
   
   The top of the stack passes the relevant Maven reactor with tests, checkstyle, forbidden APIs, Javadocs, documentation generation, and license checks.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opennlp.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OPENNLP-547: Add a transition-based dependency parser (opennlp)

Posted by "rzo1 (via GitHub)" <gi...@apache.org>.
rzo1 commented on code in PR #1236:
URL: https://github.com/apache/opennlp/pull/1236#discussion_r4178546967


##########
opennlp-api/src/main/java/opennlp/tools/depparse/DependencyGraph.java:
##########
@@ -0,0 +1,238 @@
+/*
+ * 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.tools.depparse;
+
+import java.io.Serial;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import opennlp.tools.commons.ThreadSafe;
+import opennlp.tools.util.ArgumentChecks;
+import opennlp.tools.util.StringUtil;
+
+/**
+ * An immutable dependency tree over one sentence: for every token, the index of its head
+ * and the label of the relation to that head.
+ *
+ * <p>Token indices are zero-based positions in the sentence the graph was built for.
+ * Exactly one token carries the head value {@link DependencyArc#ROOT_HEAD}, marking it as
+ * the sentence root. Instances are immutable and safe to share between threads.</p>
+ *
+ * @since 3.0.0
+ */
+@ThreadSafe
+public final class DependencyGraph implements Serializable {
+
+  @Serial
+  private static final long serialVersionUID = 5144949884365294061L;
+
+  /** Traversal state of a token whose head chain has not been followed yet. */
+  private static final byte UNVISITED = 0;
+
+  /** Traversal state of a token on the head chain currently being followed. */
+  private static final byte VISITING = 1;
+
+  /** Traversal state of a token whose head chain is known to reach the root. */
+  private static final byte VISITED = 2;
+
+  private final int[] heads;
+  private final String[] relations;
+  private final int root;
+
+  /**
+   * Wraps already validated arrays; instances are created through {@link #of}.
+   *
+   * @param heads The validated head array, owned by the new instance.
+   * @param relations The validated relation array, owned by the new instance.
+   * @param root The index of the single token whose head is {@link DependencyArc#ROOT_HEAD}.
+   */
+  private DependencyGraph(int[] heads, String[] relations, int root) {
+    this.heads = heads;
+    this.relations = relations;
+    this.root = root;
+  }
+
+  /**
+   * Creates a {@link DependencyGraph} from parallel head and relation arrays.
+   *
+   * @param heads For each token, the zero-based index of its head token, or
+   *              {@link DependencyArc#ROOT_HEAD} for the sentence root. Must not be
+   *              {@code null} or empty, every value must be a valid token index or
+   *              {@link DependencyArc#ROOT_HEAD}, no token may head itself, and exactly
+   *              one token must be the root.
+   * @param relations For each token, the label of the relation to its head. Must not be
+   *                  {@code null}, must have the same length as {@code heads}, and no
+   *                  entry may be {@code null} or blank.
+   * @return A validated {@link DependencyGraph}. Never {@code null}.
+   * @throws IllegalArgumentException Thrown if any of the above constraints is violated.
+   */
+  public static DependencyGraph of(int[] heads, String[] relations) {
+    ArgumentChecks.requireNonNullArg(heads, "heads");
+    ArgumentChecks.requireNonNullArg(relations, "relations");
+    if (heads.length == 0) {
+      throw new IllegalArgumentException("a dependency graph needs at least one token");
+    }
+    if (heads.length != relations.length) {
+      throw new IllegalArgumentException("heads and relations must have the same length: "
+          + heads.length + " != " + relations.length);
+    }
+    int roots = 0;
+    int root = DependencyArc.ROOT_HEAD;
+    for (int i = 0; i < heads.length; i++) {
+      if (heads[i] == DependencyArc.ROOT_HEAD) {
+        roots++;
+        root = i;
+      } else if (heads[i] < 0 || heads[i] >= heads.length) {
+        throw new IllegalArgumentException("head of token " + i
+            + " is out of range: " + heads[i]);
+      } else if (heads[i] == i) {
+        throw new IllegalArgumentException("token " + i + " must not head itself");
+      }
+      if (relations[i] == null || StringUtil.isBlank(relations[i])) {
+        throw new IllegalArgumentException("relation of token " + i + " must not be blank");
+      }
+    }
+    if (roots != 1) {
+      throw new IllegalArgumentException("expected exactly one root, found " + roots);
+    }
+    checkAcyclic(heads);
+    return new DependencyGraph(heads.clone(), relations.clone(), root);
+  }
+
+  /**
+   * Rejects a cycle that is disconnected from the single root by following every token's
+   * head chain until it reaches the root or a token already known to reach it.
+   *
+   * @param heads The head array, already checked for range, self-heads, and root count.
+   * @throws IllegalArgumentException Thrown if a head chain returns to a token on that
+   *         same chain.
+   */
+  private static void checkAcyclic(int[] heads) {
+    final byte[] states = new byte[heads.length];
+    for (int start = 0; start < heads.length; start++) {
+      int current = start;
+      while (current != DependencyArc.ROOT_HEAD && states[current] == UNVISITED) {
+        states[current] = VISITING;
+        current = heads[current];
+      }
+      if (current != DependencyArc.ROOT_HEAD && states[current] == VISITING) {
+        throw new IllegalArgumentException(
+            "dependency graph contains a cycle at token " + current);
+      }
+      current = start;
+      while (current != DependencyArc.ROOT_HEAD && states[current] == VISITING) {
+        states[current] = VISITED;
+        current = heads[current];
+      }
+    }
+  }
+
+  /**
+   * @return The number of tokens the graph spans.
+   */
+  public int size() {
+    return heads.length;
+  }
+
+  /**
+   * Retrieves the head of a token.
+   *
+   * @param index The zero-based token index. Must be within {@code [0, size())}.
+   * @return The zero-based index of the head token, or {@link DependencyArc#ROOT_HEAD}
+   *         when the token is the sentence root.
+   * @throws IllegalArgumentException Thrown if {@code index} is out of range.
+   */
+  public int headOf(int index) {
+    checkIndex(index);
+    return heads[index];
+  }
+
+  /**
+   * Retrieves the relation label of a token.
+   *
+   * @param index The zero-based token index. Must be within {@code [0, size())}.
+   * @return The label of the relation between the token and its head. Never {@code null}.
+   * @throws IllegalArgumentException Thrown if {@code index} is out of range.
+   */
+  public String relationOf(int index) {
+    checkIndex(index);
+    return relations[index];
+  }
+
+  /**
+   * @return The zero-based index of the sentence root token.
+   */
+  public int root() {
+    return root;
+  }
+
+  /**
+   * @return All arcs of the graph in token order, one per token. Never {@code null}.

Review Comment:
   Should mention, that this is an unmodifiable list and always allocates a new list.



##########
opennlp-api/src/main/java/opennlp/tools/depparse/DependencyGraph.java:
##########
@@ -0,0 +1,238 @@
+/*
+ * 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.tools.depparse;
+
+import java.io.Serial;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import opennlp.tools.commons.ThreadSafe;
+import opennlp.tools.util.ArgumentChecks;
+import opennlp.tools.util.StringUtil;
+
+/**
+ * An immutable dependency tree over one sentence: for every token, the index of its head
+ * and the label of the relation to that head.
+ *
+ * <p>Token indices are zero-based positions in the sentence the graph was built for.
+ * Exactly one token carries the head value {@link DependencyArc#ROOT_HEAD}, marking it as
+ * the sentence root. Instances are immutable and safe to share between threads.</p>
+ *
+ * @since 3.0.0
+ */
+@ThreadSafe
+public final class DependencyGraph implements Serializable {
+
+  @Serial
+  private static final long serialVersionUID = 5144949884365294061L;
+
+  /** Traversal state of a token whose head chain has not been followed yet. */
+  private static final byte UNVISITED = 0;
+
+  /** Traversal state of a token on the head chain currently being followed. */
+  private static final byte VISITING = 1;
+
+  /** Traversal state of a token whose head chain is known to reach the root. */
+  private static final byte VISITED = 2;
+
+  private final int[] heads;
+  private final String[] relations;
+  private final int root;
+
+  /**
+   * Wraps already validated arrays; instances are created through {@link #of}.
+   *
+   * @param heads The validated head array, owned by the new instance.
+   * @param relations The validated relation array, owned by the new instance.
+   * @param root The index of the single token whose head is {@link DependencyArc#ROOT_HEAD}.
+   */
+  private DependencyGraph(int[] heads, String[] relations, int root) {
+    this.heads = heads;
+    this.relations = relations;
+    this.root = root;
+  }
+
+  /**
+   * Creates a {@link DependencyGraph} from parallel head and relation arrays.
+   *
+   * @param heads For each token, the zero-based index of its head token, or
+   *              {@link DependencyArc#ROOT_HEAD} for the sentence root. Must not be
+   *              {@code null} or empty, every value must be a valid token index or
+   *              {@link DependencyArc#ROOT_HEAD}, no token may head itself, and exactly
+   *              one token must be the root.
+   * @param relations For each token, the label of the relation to its head. Must not be
+   *                  {@code null}, must have the same length as {@code heads}, and no
+   *                  entry may be {@code null} or blank.
+   * @return A validated {@link DependencyGraph}. Never {@code null}.
+   * @throws IllegalArgumentException Thrown if any of the above constraints is violated.
+   */
+  public static DependencyGraph of(int[] heads, String[] relations) {
+    ArgumentChecks.requireNonNullArg(heads, "heads");
+    ArgumentChecks.requireNonNullArg(relations, "relations");
+    if (heads.length == 0) {
+      throw new IllegalArgumentException("a dependency graph needs at least one token");
+    }
+    if (heads.length != relations.length) {
+      throw new IllegalArgumentException("heads and relations must have the same length: "
+          + heads.length + " != " + relations.length);
+    }
+    int roots = 0;
+    int root = DependencyArc.ROOT_HEAD;
+    for (int i = 0; i < heads.length; i++) {
+      if (heads[i] == DependencyArc.ROOT_HEAD) {
+        roots++;
+        root = i;
+      } else if (heads[i] < 0 || heads[i] >= heads.length) {
+        throw new IllegalArgumentException("head of token " + i
+            + " is out of range: " + heads[i]);
+      } else if (heads[i] == i) {
+        throw new IllegalArgumentException("token " + i + " must not head itself");
+      }
+      if (relations[i] == null || StringUtil.isBlank(relations[i])) {
+        throw new IllegalArgumentException("relation of token " + i + " must not be blank");
+      }
+    }
+    if (roots != 1) {
+      throw new IllegalArgumentException("expected exactly one root, found " + roots);
+    }
+    checkAcyclic(heads);
+    return new DependencyGraph(heads.clone(), relations.clone(), root);
+  }
+
+  /**
+   * Rejects a cycle that is disconnected from the single root by following every token's
+   * head chain until it reaches the root or a token already known to reach it.
+   *
+   * @param heads The head array, already checked for range, self-heads, and root count.
+   * @throws IllegalArgumentException Thrown if a head chain returns to a token on that
+   *         same chain.
+   */
+  private static void checkAcyclic(int[] heads) {
+    final byte[] states = new byte[heads.length];
+    for (int start = 0; start < heads.length; start++) {
+      int current = start;
+      while (current != DependencyArc.ROOT_HEAD && states[current] == UNVISITED) {
+        states[current] = VISITING;
+        current = heads[current];
+      }
+      if (current != DependencyArc.ROOT_HEAD && states[current] == VISITING) {
+        throw new IllegalArgumentException(
+            "dependency graph contains a cycle at token " + current);
+      }
+      current = start;
+      while (current != DependencyArc.ROOT_HEAD && states[current] == VISITING) {
+        states[current] = VISITED;
+        current = heads[current];
+      }
+    }
+  }
+
+  /**
+   * @return The number of tokens the graph spans.
+   */
+  public int size() {
+    return heads.length;
+  }
+
+  /**
+   * Retrieves the head of a token.
+   *
+   * @param index The zero-based token index. Must be within {@code [0, size())}.
+   * @return The zero-based index of the head token, or {@link DependencyArc#ROOT_HEAD}
+   *         when the token is the sentence root.
+   * @throws IllegalArgumentException Thrown if {@code index} is out of range.
+   */
+  public int headOf(int index) {
+    checkIndex(index);
+    return heads[index];
+  }
+
+  /**
+   * Retrieves the relation label of a token.
+   *
+   * @param index The zero-based token index. Must be within {@code [0, size())}.
+   * @return The label of the relation between the token and its head. Never {@code null}.
+   * @throws IllegalArgumentException Thrown if {@code index} is out of range.
+   */
+  public String relationOf(int index) {
+    checkIndex(index);
+    return relations[index];
+  }
+
+  /**
+   * @return The zero-based index of the sentence root token.
+   */
+  public int root() {
+    return root;
+  }
+
+  /**
+   * @return All arcs of the graph in token order, one per token. Never {@code null}.
+   */
+  public List<DependencyArc> arcs() {
+    final List<DependencyArc> arcs = new ArrayList<>(heads.length);
+    for (int i = 0; i < heads.length; i++) {
+      arcs.add(new DependencyArc(heads[i], i, relations[i]));
+    }
+    return Collections.unmodifiableList(arcs);
+  }
+
+  /**
+   * Rejects a token index outside {@code [0, size())}.
+   *
+   * @param index The zero-based token index to check.
+   * @throws IllegalArgumentException Thrown if {@code index} is out of range.
+   */
+  private void checkIndex(int index) {
+    if (index < 0 || index >= heads.length) {
+      throw new IllegalArgumentException("token index out of range: " + index
+          + ", size: " + heads.length);
+    }
+  }
+
+  @Override

Review Comment:
   inheritDoc



##########
opennlp-api/src/main/java/opennlp/tools/depparse/DependencySample.java:
##########
@@ -0,0 +1,153 @@
+/*
+ * 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.tools.depparse;
+
+import java.io.Serial;
+import java.util.Arrays;
+import java.util.Objects;
+
+import opennlp.tools.commons.Sample;
+import opennlp.tools.commons.ThreadSafe;
+import opennlp.tools.util.ArgumentChecks;
+
+/**
+ * One dependency-annotated sentence: tokens, their part-of-speech tags, and the gold
+ * {@link DependencyGraph} over them. Used for training and evaluating a
+ * {@link DependencyParser}.
+ *
+ * <p>Instances are immutable and safe to share between threads.</p>
+ *
+ * @since 3.0.0
+ */
+@ThreadSafe
+public final class DependencySample implements Sample {
+
+  @Serial
+  private static final long serialVersionUID = 3074843369898695370L;
+
+  private final String[] tokens;
+  private final String[] tags;
+  private final DependencyGraph graph;
+
+  /**
+   * Initializes a {@link DependencySample}.
+   *
+   * @param tokens The input tokens. Must not be {@code null} or empty and must
+   *               not contain {@code null} entries.
+   * @param tags The part-of-speech tags aligned with {@code tokens}. Must not be
+   *             {@code null}, must have the same length as {@code tokens}, and must not
+   *             contain {@code null} entries.
+   * @param graph The dependency graph over the tokens. Must not be {@code null} and its
+   *              {@link DependencyGraph#size()} must equal the number of tokens.
+   * @throws IllegalArgumentException Thrown if any parameter is {@code null},
+   *         {@code tokens} is empty, {@code tokens} or {@code tags} contains a
+   *         {@code null} entry, or the lengths of tokens, tags and graph disagree.
+   */
+  public DependencySample(String[] tokens, String[] tags, DependencyGraph graph) {
+    ArgumentChecks.requireNonNullArg(graph, "graph");
+    checkTokensAndTags(tokens, tags);
+    if (tokens.length != graph.size()) {
+      throw new IllegalArgumentException("tokens, tags and graph must agree in length: "
+          + tokens.length + ", " + tags.length + ", " + graph.size());
+    }
+    this.tokens = tokens.clone();
+    this.tags = tags.clone();
+    this.graph = graph;
+  }
+
+  /**
+   * Validates token and tag arrays for this sample and
+   * {@link DependencyParser#parse(String[], String[])}.
+   *
+   * @param tokens The token array. Must not be {@code null} or empty and must not
+   *               contain {@code null} entries.
+   * @param tags The part-of-speech tags aligned with {@code tokens}. Must not be
+   *             {@code null}, must have the same length as {@code tokens}, and must not
+   *             contain {@code null} entries.
+   * @throws IllegalArgumentException Thrown if an array is {@code null}, {@code tokens}
+   *         is empty, the lengths do not match, or an entry is {@code null}.
+   */
+  public static void checkTokensAndTags(String[] tokens, String[] tags) {
+    ArgumentChecks.requireNonNullArg(tokens, "tokens");
+    ArgumentChecks.requireNonNullArg(tags, "tags");
+    if (tokens.length == 0) {
+      throw new IllegalArgumentException("tokens must not be empty");
+    }
+    if (tokens.length != tags.length) {
+      throw new IllegalArgumentException("tokens and tags must have the same length: "
+          + tokens.length + " != " + tags.length);
+    }
+    for (int i = 0; i < tokens.length; i++) {
+      if (tokens[i] == null) {
+        throw new IllegalArgumentException("token must not be null at index " + i);
+      }
+      if (tags[i] == null) {
+        throw new IllegalArgumentException("tag must not be null at index " + i);
+      }
+    }
+  }
+
+  /**
+   * @return The tokens of the sentence. Never {@code null}.
+   */
+  public String[] getTokens() {
+    return tokens.clone();
+  }
+
+  /**
+   * @return The part-of-speech tags aligned with the tokens. Never {@code null}.
+   */
+  public String[] getTags() {
+    return tags.clone();
+  }
+
+  /**
+   * @return The dependency graph over the tokens. Never {@code null}.
+   */
+  public DependencyGraph getGraph() {
+    return graph;
+  }
+
+  @Override
+  public boolean equals(Object obj) {
+    if (this == obj) {
+      return true;
+    }
+    if (!(obj instanceof DependencySample other)) {
+      return false;
+    }
+    return Arrays.equals(tokens, other.tokens) && Arrays.equals(tags, other.tags)
+        && graph.equals(other.graph);
+  }
+
+  @Override
+  public int hashCode() {
+    return Objects.hash(Arrays.hashCode(tokens), Arrays.hashCode(tags), graph);
+  }
+
+  @Override
+  public String toString() {

Review Comment:
   inerhitcDoc



##########
opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/depparse/ArcStandardState.java:
##########
@@ -0,0 +1,295 @@
+/*
+ * 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.tools.depparse;
+
+import java.util.Arrays;
+
+import opennlp.tools.util.ArgumentChecks;
+
+/**
+ * The mutable configuration of an arc-standard parse: a stack, a buffer of remaining

Review Comment:
   similar to above. perhaps reword in a nicer way.



##########
opennlp-api/src/main/java/opennlp/tools/depparse/DependencySample.java:
##########
@@ -0,0 +1,153 @@
+/*
+ * 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.tools.depparse;
+
+import java.io.Serial;
+import java.util.Arrays;
+import java.util.Objects;
+
+import opennlp.tools.commons.Sample;
+import opennlp.tools.commons.ThreadSafe;
+import opennlp.tools.util.ArgumentChecks;
+
+/**
+ * One dependency-annotated sentence: tokens, their part-of-speech tags, and the gold
+ * {@link DependencyGraph} over them. Used for training and evaluating a
+ * {@link DependencyParser}.
+ *
+ * <p>Instances are immutable and safe to share between threads.</p>
+ *
+ * @since 3.0.0
+ */
+@ThreadSafe
+public final class DependencySample implements Sample {
+
+  @Serial
+  private static final long serialVersionUID = 3074843369898695370L;
+
+  private final String[] tokens;
+  private final String[] tags;
+  private final DependencyGraph graph;
+
+  /**
+   * Initializes a {@link DependencySample}.
+   *
+   * @param tokens The input tokens. Must not be {@code null} or empty and must
+   *               not contain {@code null} entries.
+   * @param tags The part-of-speech tags aligned with {@code tokens}. Must not be
+   *             {@code null}, must have the same length as {@code tokens}, and must not
+   *             contain {@code null} entries.
+   * @param graph The dependency graph over the tokens. Must not be {@code null} and its
+   *              {@link DependencyGraph#size()} must equal the number of tokens.
+   * @throws IllegalArgumentException Thrown if any parameter is {@code null},
+   *         {@code tokens} is empty, {@code tokens} or {@code tags} contains a
+   *         {@code null} entry, or the lengths of tokens, tags and graph disagree.
+   */
+  public DependencySample(String[] tokens, String[] tags, DependencyGraph graph) {
+    ArgumentChecks.requireNonNullArg(graph, "graph");
+    checkTokensAndTags(tokens, tags);
+    if (tokens.length != graph.size()) {
+      throw new IllegalArgumentException("tokens, tags and graph must agree in length: "
+          + tokens.length + ", " + tags.length + ", " + graph.size());
+    }
+    this.tokens = tokens.clone();
+    this.tags = tags.clone();
+    this.graph = graph;
+  }
+
+  /**
+   * Validates token and tag arrays for this sample and
+   * {@link DependencyParser#parse(String[], String[])}.
+   *
+   * @param tokens The token array. Must not be {@code null} or empty and must not
+   *               contain {@code null} entries.
+   * @param tags The part-of-speech tags aligned with {@code tokens}. Must not be
+   *             {@code null}, must have the same length as {@code tokens}, and must not
+   *             contain {@code null} entries.
+   * @throws IllegalArgumentException Thrown if an array is {@code null}, {@code tokens}
+   *         is empty, the lengths do not match, or an entry is {@code null}.
+   */
+  public static void checkTokensAndTags(String[] tokens, String[] tags) {
+    ArgumentChecks.requireNonNullArg(tokens, "tokens");
+    ArgumentChecks.requireNonNullArg(tags, "tags");
+    if (tokens.length == 0) {
+      throw new IllegalArgumentException("tokens must not be empty");
+    }
+    if (tokens.length != tags.length) {
+      throw new IllegalArgumentException("tokens and tags must have the same length: "
+          + tokens.length + " != " + tags.length);
+    }
+    for (int i = 0; i < tokens.length; i++) {
+      if (tokens[i] == null) {
+        throw new IllegalArgumentException("token must not be null at index " + i);
+      }
+      if (tags[i] == null) {
+        throw new IllegalArgumentException("tag must not be null at index " + i);
+      }
+    }
+  }
+
+  /**
+   * @return The tokens of the sentence. Never {@code null}.
+   */
+  public String[] getTokens() {
+    return tokens.clone();
+  }
+
+  /**
+   * @return The part-of-speech tags aligned with the tokens. Never {@code null}.
+   */
+  public String[] getTags() {
+    return tags.clone();
+  }
+
+  /**
+   * @return The dependency graph over the tokens. Never {@code null}.
+   */
+  public DependencyGraph getGraph() {
+    return graph;
+  }
+
+  @Override
+  public boolean equals(Object obj) {
+    if (this == obj) {
+      return true;
+    }
+    if (!(obj instanceof DependencySample other)) {
+      return false;
+    }
+    return Arrays.equals(tokens, other.tokens) && Arrays.equals(tags, other.tags)
+        && graph.equals(other.graph);
+  }
+
+  @Override
+  public int hashCode() {
+    return Objects.hash(Arrays.hashCode(tokens), Arrays.hashCode(tags), graph);

Review Comment:
   inerhitcDoc



##########
opennlp-core/opennlp-formats/src/main/java/opennlp/tools/formats/conllu/ConlluTagset.java:
##########
@@ -17,7 +17,43 @@
 
 package opennlp.tools.formats.conllu;
 
+import opennlp.tools.cmdline.TerminateToolException;
+
 public enum ConlluTagset {
   U,
-  X
+  X;
+
+  /**
+   * Resolves the value of a command line {@code tagset} parameter.
+   *
+   * @param parameter {@code u} for the universal tags or {@code x} for the
+   *                  language-specific tags.
+   * @return The matching {@link ConlluTagset}. Never {@code null}.
+   * @throws IllegalArgumentException Thrown if {@code parameter} is neither {@code u}
+   *         nor {@code x}.
+   */
+  public static ConlluTagset fromParameter(String parameter) {

Review Comment:
   Can we add those String constants as ctor arg to the enum and than just use the attrib?



##########
opennlp-api/src/main/java/opennlp/tools/depparse/DependencyGraph.java:
##########
@@ -0,0 +1,238 @@
+/*
+ * 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.tools.depparse;
+
+import java.io.Serial;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import opennlp.tools.commons.ThreadSafe;
+import opennlp.tools.util.ArgumentChecks;
+import opennlp.tools.util.StringUtil;
+
+/**
+ * An immutable dependency tree over one sentence: for every token, the index of its head
+ * and the label of the relation to that head.
+ *
+ * <p>Token indices are zero-based positions in the sentence the graph was built for.
+ * Exactly one token carries the head value {@link DependencyArc#ROOT_HEAD}, marking it as
+ * the sentence root. Instances are immutable and safe to share between threads.</p>
+ *
+ * @since 3.0.0
+ */
+@ThreadSafe
+public final class DependencyGraph implements Serializable {

Review Comment:
   Rename to `DependencyTree`?
   
   Its documented and enforced contract is a single-rooted, acyclic tree with one head per token. Tree communicates those restrictions directly
   



##########
opennlp-api/src/main/java/opennlp/tools/depparse/DependencyGraph.java:
##########
@@ -0,0 +1,238 @@
+/*
+ * 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.tools.depparse;
+
+import java.io.Serial;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import opennlp.tools.commons.ThreadSafe;
+import opennlp.tools.util.ArgumentChecks;
+import opennlp.tools.util.StringUtil;
+
+/**
+ * An immutable dependency tree over one sentence: for every token, the index of its head
+ * and the label of the relation to that head.
+ *
+ * <p>Token indices are zero-based positions in the sentence the graph was built for.
+ * Exactly one token carries the head value {@link DependencyArc#ROOT_HEAD}, marking it as
+ * the sentence root. Instances are immutable and safe to share between threads.</p>
+ *
+ * @since 3.0.0
+ */
+@ThreadSafe
+public final class DependencyGraph implements Serializable {
+
+  @Serial
+  private static final long serialVersionUID = 5144949884365294061L;
+
+  /** Traversal state of a token whose head chain has not been followed yet. */
+  private static final byte UNVISITED = 0;
+
+  /** Traversal state of a token on the head chain currently being followed. */
+  private static final byte VISITING = 1;
+
+  /** Traversal state of a token whose head chain is known to reach the root. */
+  private static final byte VISITED = 2;
+
+  private final int[] heads;
+  private final String[] relations;
+  private final int root;
+
+  /**
+   * Wraps already validated arrays; instances are created through {@link #of}.
+   *
+   * @param heads The validated head array, owned by the new instance.
+   * @param relations The validated relation array, owned by the new instance.
+   * @param root The index of the single token whose head is {@link DependencyArc#ROOT_HEAD}.
+   */
+  private DependencyGraph(int[] heads, String[] relations, int root) {
+    this.heads = heads;
+    this.relations = relations;
+    this.root = root;
+  }
+
+  /**
+   * Creates a {@link DependencyGraph} from parallel head and relation arrays.
+   *
+   * @param heads For each token, the zero-based index of its head token, or
+   *              {@link DependencyArc#ROOT_HEAD} for the sentence root. Must not be
+   *              {@code null} or empty, every value must be a valid token index or
+   *              {@link DependencyArc#ROOT_HEAD}, no token may head itself, and exactly
+   *              one token must be the root.
+   * @param relations For each token, the label of the relation to its head. Must not be
+   *                  {@code null}, must have the same length as {@code heads}, and no
+   *                  entry may be {@code null} or blank.
+   * @return A validated {@link DependencyGraph}. Never {@code null}.
+   * @throws IllegalArgumentException Thrown if any of the above constraints is violated.
+   */
+  public static DependencyGraph of(int[] heads, String[] relations) {
+    ArgumentChecks.requireNonNullArg(heads, "heads");
+    ArgumentChecks.requireNonNullArg(relations, "relations");
+    if (heads.length == 0) {
+      throw new IllegalArgumentException("a dependency graph needs at least one token");
+    }
+    if (heads.length != relations.length) {
+      throw new IllegalArgumentException("heads and relations must have the same length: "
+          + heads.length + " != " + relations.length);
+    }
+    int roots = 0;
+    int root = DependencyArc.ROOT_HEAD;
+    for (int i = 0; i < heads.length; i++) {
+      if (heads[i] == DependencyArc.ROOT_HEAD) {
+        roots++;
+        root = i;
+      } else if (heads[i] < 0 || heads[i] >= heads.length) {
+        throw new IllegalArgumentException("head of token " + i
+            + " is out of range: " + heads[i]);
+      } else if (heads[i] == i) {
+        throw new IllegalArgumentException("token " + i + " must not head itself");
+      }
+      if (relations[i] == null || StringUtil.isBlank(relations[i])) {
+        throw new IllegalArgumentException("relation of token " + i + " must not be blank");
+      }
+    }
+    if (roots != 1) {
+      throw new IllegalArgumentException("expected exactly one root, found " + roots);
+    }
+    checkAcyclic(heads);
+    return new DependencyGraph(heads.clone(), relations.clone(), root);
+  }
+
+  /**
+   * Rejects a cycle that is disconnected from the single root by following every token's
+   * head chain until it reaches the root or a token already known to reach it.
+   *
+   * @param heads The head array, already checked for range, self-heads, and root count.
+   * @throws IllegalArgumentException Thrown if a head chain returns to a token on that
+   *         same chain.
+   */
+  private static void checkAcyclic(int[] heads) {
+    final byte[] states = new byte[heads.length];
+    for (int start = 0; start < heads.length; start++) {
+      int current = start;
+      while (current != DependencyArc.ROOT_HEAD && states[current] == UNVISITED) {
+        states[current] = VISITING;
+        current = heads[current];
+      }
+      if (current != DependencyArc.ROOT_HEAD && states[current] == VISITING) {
+        throw new IllegalArgumentException(
+            "dependency graph contains a cycle at token " + current);
+      }
+      current = start;
+      while (current != DependencyArc.ROOT_HEAD && states[current] == VISITING) {
+        states[current] = VISITED;
+        current = heads[current];
+      }
+    }
+  }
+
+  /**
+   * @return The number of tokens the graph spans.
+   */
+  public int size() {
+    return heads.length;
+  }
+
+  /**
+   * Retrieves the head of a token.
+   *
+   * @param index The zero-based token index. Must be within {@code [0, size())}.
+   * @return The zero-based index of the head token, or {@link DependencyArc#ROOT_HEAD}
+   *         when the token is the sentence root.
+   * @throws IllegalArgumentException Thrown if {@code index} is out of range.
+   */
+  public int headOf(int index) {
+    checkIndex(index);
+    return heads[index];
+  }
+
+  /**
+   * Retrieves the relation label of a token.
+   *
+   * @param index The zero-based token index. Must be within {@code [0, size())}.
+   * @return The label of the relation between the token and its head. Never {@code null}.
+   * @throws IllegalArgumentException Thrown if {@code index} is out of range.
+   */
+  public String relationOf(int index) {
+    checkIndex(index);
+    return relations[index];
+  }
+
+  /**
+   * @return The zero-based index of the sentence root token.
+   */
+  public int root() {
+    return root;
+  }
+
+  /**
+   * @return All arcs of the graph in token order, one per token. Never {@code null}.
+   */
+  public List<DependencyArc> arcs() {
+    final List<DependencyArc> arcs = new ArrayList<>(heads.length);
+    for (int i = 0; i < heads.length; i++) {
+      arcs.add(new DependencyArc(heads[i], i, relations[i]));
+    }
+    return Collections.unmodifiableList(arcs);
+  }
+
+  /**
+   * Rejects a token index outside {@code [0, size())}.
+   *
+   * @param index The zero-based token index to check.
+   * @throws IllegalArgumentException Thrown if {@code index} is out of range.
+   */
+  private void checkIndex(int index) {
+    if (index < 0 || index >= heads.length) {
+      throw new IllegalArgumentException("token index out of range: " + index
+          + ", size: " + heads.length);
+    }
+  }
+
+  @Override
+  public boolean equals(Object obj) {
+    if (this == obj) {
+      return true;
+    }
+    if (!(obj instanceof DependencyGraph other)) {
+      return false;
+    }
+    return Arrays.equals(heads, other.heads) && Arrays.equals(relations, other.relations);
+  }
+
+  @Override

Review Comment:
   inheritDoc



##########
opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/depparse/ArcStandardOracle.java:
##########
@@ -0,0 +1,135 @@
+/*
+ * 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.tools.depparse;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import opennlp.tools.util.ArgumentChecks;
+
+/**
+ * The static oracle for the arc-standard system: derives the transition sequence that

Review Comment:
   Reword this Javadoc to explain for (non familiar) readers what it is.



##########
opennlp-api/src/main/java/opennlp/tools/depparse/DependencyGraph.java:
##########
@@ -0,0 +1,238 @@
+/*
+ * 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.tools.depparse;
+
+import java.io.Serial;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import opennlp.tools.commons.ThreadSafe;
+import opennlp.tools.util.ArgumentChecks;
+import opennlp.tools.util.StringUtil;
+
+/**
+ * An immutable dependency tree over one sentence: for every token, the index of its head
+ * and the label of the relation to that head.
+ *
+ * <p>Token indices are zero-based positions in the sentence the graph was built for.
+ * Exactly one token carries the head value {@link DependencyArc#ROOT_HEAD}, marking it as
+ * the sentence root. Instances are immutable and safe to share between threads.</p>
+ *
+ * @since 3.0.0
+ */
+@ThreadSafe
+public final class DependencyGraph implements Serializable {
+
+  @Serial
+  private static final long serialVersionUID = 5144949884365294061L;
+
+  /** Traversal state of a token whose head chain has not been followed yet. */
+  private static final byte UNVISITED = 0;
+
+  /** Traversal state of a token on the head chain currently being followed. */
+  private static final byte VISITING = 1;
+
+  /** Traversal state of a token whose head chain is known to reach the root. */
+  private static final byte VISITED = 2;
+
+  private final int[] heads;
+  private final String[] relations;
+  private final int root;
+
+  /**
+   * Wraps already validated arrays; instances are created through {@link #of}.
+   *
+   * @param heads The validated head array, owned by the new instance.
+   * @param relations The validated relation array, owned by the new instance.
+   * @param root The index of the single token whose head is {@link DependencyArc#ROOT_HEAD}.
+   */
+  private DependencyGraph(int[] heads, String[] relations, int root) {
+    this.heads = heads;
+    this.relations = relations;
+    this.root = root;
+  }
+
+  /**
+   * Creates a {@link DependencyGraph} from parallel head and relation arrays.
+   *
+   * @param heads For each token, the zero-based index of its head token, or
+   *              {@link DependencyArc#ROOT_HEAD} for the sentence root. Must not be
+   *              {@code null} or empty, every value must be a valid token index or
+   *              {@link DependencyArc#ROOT_HEAD}, no token may head itself, and exactly
+   *              one token must be the root.
+   * @param relations For each token, the label of the relation to its head. Must not be
+   *                  {@code null}, must have the same length as {@code heads}, and no
+   *                  entry may be {@code null} or blank.
+   * @return A validated {@link DependencyGraph}. Never {@code null}.
+   * @throws IllegalArgumentException Thrown if any of the above constraints is violated.
+   */
+  public static DependencyGraph of(int[] heads, String[] relations) {
+    ArgumentChecks.requireNonNullArg(heads, "heads");
+    ArgumentChecks.requireNonNullArg(relations, "relations");
+    if (heads.length == 0) {
+      throw new IllegalArgumentException("a dependency graph needs at least one token");
+    }
+    if (heads.length != relations.length) {
+      throw new IllegalArgumentException("heads and relations must have the same length: "
+          + heads.length + " != " + relations.length);
+    }
+    int roots = 0;
+    int root = DependencyArc.ROOT_HEAD;
+    for (int i = 0; i < heads.length; i++) {
+      if (heads[i] == DependencyArc.ROOT_HEAD) {
+        roots++;
+        root = i;
+      } else if (heads[i] < 0 || heads[i] >= heads.length) {
+        throw new IllegalArgumentException("head of token " + i
+            + " is out of range: " + heads[i]);
+      } else if (heads[i] == i) {
+        throw new IllegalArgumentException("token " + i + " must not head itself");
+      }
+      if (relations[i] == null || StringUtil.isBlank(relations[i])) {
+        throw new IllegalArgumentException("relation of token " + i + " must not be blank");
+      }
+    }
+    if (roots != 1) {
+      throw new IllegalArgumentException("expected exactly one root, found " + roots);
+    }
+    checkAcyclic(heads);
+    return new DependencyGraph(heads.clone(), relations.clone(), root);
+  }
+
+  /**
+   * Rejects a cycle that is disconnected from the single root by following every token's
+   * head chain until it reaches the root or a token already known to reach it.
+   *
+   * @param heads The head array, already checked for range, self-heads, and root count.
+   * @throws IllegalArgumentException Thrown if a head chain returns to a token on that
+   *         same chain.
+   */
+  private static void checkAcyclic(int[] heads) {
+    final byte[] states = new byte[heads.length];
+    for (int start = 0; start < heads.length; start++) {
+      int current = start;
+      while (current != DependencyArc.ROOT_HEAD && states[current] == UNVISITED) {
+        states[current] = VISITING;
+        current = heads[current];
+      }
+      if (current != DependencyArc.ROOT_HEAD && states[current] == VISITING) {
+        throw new IllegalArgumentException(
+            "dependency graph contains a cycle at token " + current);
+      }
+      current = start;
+      while (current != DependencyArc.ROOT_HEAD && states[current] == VISITING) {
+        states[current] = VISITED;
+        current = heads[current];
+      }
+    }
+  }
+
+  /**
+   * @return The number of tokens the graph spans.
+   */
+  public int size() {
+    return heads.length;
+  }
+
+  /**
+   * Retrieves the head of a token.
+   *
+   * @param index The zero-based token index. Must be within {@code [0, size())}.
+   * @return The zero-based index of the head token, or {@link DependencyArc#ROOT_HEAD}
+   *         when the token is the sentence root.
+   * @throws IllegalArgumentException Thrown if {@code index} is out of range.
+   */
+  public int headOf(int index) {
+    checkIndex(index);
+    return heads[index];
+  }
+
+  /**
+   * Retrieves the relation label of a token.
+   *
+   * @param index The zero-based token index. Must be within {@code [0, size())}.
+   * @return The label of the relation between the token and its head. Never {@code null}.
+   * @throws IllegalArgumentException Thrown if {@code index} is out of range.
+   */
+  public String relationOf(int index) {
+    checkIndex(index);
+    return relations[index];
+  }
+
+  /**
+   * @return The zero-based index of the sentence root token.
+   */
+  public int root() {
+    return root;
+  }
+
+  /**
+   * @return All arcs of the graph in token order, one per token. Never {@code null}.
+   */
+  public List<DependencyArc> arcs() {
+    final List<DependencyArc> arcs = new ArrayList<>(heads.length);
+    for (int i = 0; i < heads.length; i++) {
+      arcs.add(new DependencyArc(heads[i], i, relations[i]));
+    }
+    return Collections.unmodifiableList(arcs);
+  }
+
+  /**
+   * Rejects a token index outside {@code [0, size())}.
+   *
+   * @param index The zero-based token index to check.
+   * @throws IllegalArgumentException Thrown if {@code index} is out of range.
+   */
+  private void checkIndex(int index) {
+    if (index < 0 || index >= heads.length) {
+      throw new IllegalArgumentException("token index out of range: " + index
+          + ", size: " + heads.length);
+    }
+  }
+
+  @Override
+  public boolean equals(Object obj) {
+    if (this == obj) {
+      return true;
+    }
+    if (!(obj instanceof DependencyGraph other)) {
+      return false;
+    }
+    return Arrays.equals(heads, other.heads) && Arrays.equals(relations, other.relations);
+  }
+
+  @Override
+  public int hashCode() {
+    return 31 * Arrays.hashCode(heads) + Arrays.hashCode(relations);

Review Comment:
   This hash code impl is usually quite slow. Since it cannot change after creation, perhaps cash the value during creation?



##########
opennlp-api/src/main/java/opennlp/tools/depparse/DependencySample.java:
##########
@@ -0,0 +1,153 @@
+/*
+ * 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.tools.depparse;
+
+import java.io.Serial;
+import java.util.Arrays;
+import java.util.Objects;
+
+import opennlp.tools.commons.Sample;
+import opennlp.tools.commons.ThreadSafe;
+import opennlp.tools.util.ArgumentChecks;
+
+/**
+ * One dependency-annotated sentence: tokens, their part-of-speech tags, and the gold
+ * {@link DependencyGraph} over them. Used for training and evaluating a
+ * {@link DependencyParser}.
+ *
+ * <p>Instances are immutable and safe to share between threads.</p>
+ *
+ * @since 3.0.0
+ */
+@ThreadSafe
+public final class DependencySample implements Sample {
+
+  @Serial
+  private static final long serialVersionUID = 3074843369898695370L;
+
+  private final String[] tokens;
+  private final String[] tags;
+  private final DependencyGraph graph;
+
+  /**
+   * Initializes a {@link DependencySample}.
+   *
+   * @param tokens The input tokens. Must not be {@code null} or empty and must
+   *               not contain {@code null} entries.
+   * @param tags The part-of-speech tags aligned with {@code tokens}. Must not be
+   *             {@code null}, must have the same length as {@code tokens}, and must not
+   *             contain {@code null} entries.
+   * @param graph The dependency graph over the tokens. Must not be {@code null} and its
+   *              {@link DependencyGraph#size()} must equal the number of tokens.
+   * @throws IllegalArgumentException Thrown if any parameter is {@code null},
+   *         {@code tokens} is empty, {@code tokens} or {@code tags} contains a
+   *         {@code null} entry, or the lengths of tokens, tags and graph disagree.
+   */
+  public DependencySample(String[] tokens, String[] tags, DependencyGraph graph) {
+    ArgumentChecks.requireNonNullArg(graph, "graph");
+    checkTokensAndTags(tokens, tags);
+    if (tokens.length != graph.size()) {
+      throw new IllegalArgumentException("tokens, tags and graph must agree in length: "
+          + tokens.length + ", " + tags.length + ", " + graph.size());
+    }
+    this.tokens = tokens.clone();
+    this.tags = tags.clone();
+    this.graph = graph;
+  }
+
+  /**
+   * Validates token and tag arrays for this sample and
+   * {@link DependencyParser#parse(String[], String[])}.
+   *
+   * @param tokens The token array. Must not be {@code null} or empty and must not
+   *               contain {@code null} entries.
+   * @param tags The part-of-speech tags aligned with {@code tokens}. Must not be
+   *             {@code null}, must have the same length as {@code tokens}, and must not
+   *             contain {@code null} entries.
+   * @throws IllegalArgumentException Thrown if an array is {@code null}, {@code tokens}
+   *         is empty, the lengths do not match, or an entry is {@code null}.
+   */
+  public static void checkTokensAndTags(String[] tokens, String[] tags) {

Review Comment:
   Why public? Private + drop static?



##########
opennlp-api/src/main/java/opennlp/tools/depparse/DependencySample.java:
##########
@@ -0,0 +1,153 @@
+/*
+ * 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.tools.depparse;
+
+import java.io.Serial;
+import java.util.Arrays;
+import java.util.Objects;
+
+import opennlp.tools.commons.Sample;
+import opennlp.tools.commons.ThreadSafe;
+import opennlp.tools.util.ArgumentChecks;
+
+/**
+ * One dependency-annotated sentence: tokens, their part-of-speech tags, and the gold
+ * {@link DependencyGraph} over them. Used for training and evaluating a
+ * {@link DependencyParser}.
+ *
+ * <p>Instances are immutable and safe to share between threads.</p>
+ *
+ * @since 3.0.0
+ */
+@ThreadSafe
+public final class DependencySample implements Sample {
+
+  @Serial
+  private static final long serialVersionUID = 3074843369898695370L;
+
+  private final String[] tokens;
+  private final String[] tags;
+  private final DependencyGraph graph;
+
+  /**
+   * Initializes a {@link DependencySample}.
+   *
+   * @param tokens The input tokens. Must not be {@code null} or empty and must
+   *               not contain {@code null} entries.
+   * @param tags The part-of-speech tags aligned with {@code tokens}. Must not be
+   *             {@code null}, must have the same length as {@code tokens}, and must not
+   *             contain {@code null} entries.
+   * @param graph The dependency graph over the tokens. Must not be {@code null} and its
+   *              {@link DependencyGraph#size()} must equal the number of tokens.
+   * @throws IllegalArgumentException Thrown if any parameter is {@code null},
+   *         {@code tokens} is empty, {@code tokens} or {@code tags} contains a
+   *         {@code null} entry, or the lengths of tokens, tags and graph disagree.
+   */
+  public DependencySample(String[] tokens, String[] tags, DependencyGraph graph) {
+    ArgumentChecks.requireNonNullArg(graph, "graph");
+    checkTokensAndTags(tokens, tags);
+    if (tokens.length != graph.size()) {
+      throw new IllegalArgumentException("tokens, tags and graph must agree in length: "
+          + tokens.length + ", " + tags.length + ", " + graph.size());
+    }
+    this.tokens = tokens.clone();
+    this.tags = tags.clone();
+    this.graph = graph;
+  }
+
+  /**
+   * Validates token and tag arrays for this sample and
+   * {@link DependencyParser#parse(String[], String[])}.
+   *
+   * @param tokens The token array. Must not be {@code null} or empty and must not
+   *               contain {@code null} entries.
+   * @param tags The part-of-speech tags aligned with {@code tokens}. Must not be
+   *             {@code null}, must have the same length as {@code tokens}, and must not
+   *             contain {@code null} entries.
+   * @throws IllegalArgumentException Thrown if an array is {@code null}, {@code tokens}
+   *         is empty, the lengths do not match, or an entry is {@code null}.
+   */
+  public static void checkTokensAndTags(String[] tokens, String[] tags) {
+    ArgumentChecks.requireNonNullArg(tokens, "tokens");
+    ArgumentChecks.requireNonNullArg(tags, "tags");
+    if (tokens.length == 0) {
+      throw new IllegalArgumentException("tokens must not be empty");
+    }
+    if (tokens.length != tags.length) {
+      throw new IllegalArgumentException("tokens and tags must have the same length: "
+          + tokens.length + " != " + tags.length);
+    }
+    for (int i = 0; i < tokens.length; i++) {
+      if (tokens[i] == null) {
+        throw new IllegalArgumentException("token must not be null at index " + i);
+      }
+      if (tags[i] == null) {
+        throw new IllegalArgumentException("tag must not be null at index " + i);
+      }
+    }
+  }
+
+  /**
+   * @return The tokens of the sentence. Never {@code null}.
+   */
+  public String[] getTokens() {
+    return tokens.clone();
+  }
+
+  /**
+   * @return The part-of-speech tags aligned with the tokens. Never {@code null}.
+   */
+  public String[] getTags() {
+    return tags.clone();
+  }
+
+  /**
+   * @return The dependency graph over the tokens. Never {@code null}.
+   */
+  public DependencyGraph getGraph() {
+    return graph;
+  }
+
+  @Override

Review Comment:
   inerhitcDoc



##########
opennlp-api/src/main/java/opennlp/tools/depparse/DependencyGraph.java:
##########
@@ -0,0 +1,238 @@
+/*
+ * 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.tools.depparse;
+
+import java.io.Serial;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import opennlp.tools.commons.ThreadSafe;
+import opennlp.tools.util.ArgumentChecks;
+import opennlp.tools.util.StringUtil;
+
+/**
+ * An immutable dependency tree over one sentence: for every token, the index of its head
+ * and the label of the relation to that head.
+ *
+ * <p>Token indices are zero-based positions in the sentence the graph was built for.
+ * Exactly one token carries the head value {@link DependencyArc#ROOT_HEAD}, marking it as
+ * the sentence root. Instances are immutable and safe to share between threads.</p>
+ *
+ * @since 3.0.0
+ */
+@ThreadSafe
+public final class DependencyGraph implements Serializable {
+
+  @Serial
+  private static final long serialVersionUID = 5144949884365294061L;
+
+  /** Traversal state of a token whose head chain has not been followed yet. */
+  private static final byte UNVISITED = 0;
+
+  /** Traversal state of a token on the head chain currently being followed. */
+  private static final byte VISITING = 1;
+
+  /** Traversal state of a token whose head chain is known to reach the root. */
+  private static final byte VISITED = 2;
+
+  private final int[] heads;
+  private final String[] relations;
+  private final int root;
+
+  /**
+   * Wraps already validated arrays; instances are created through {@link #of}.
+   *
+   * @param heads The validated head array, owned by the new instance.
+   * @param relations The validated relation array, owned by the new instance.
+   * @param root The index of the single token whose head is {@link DependencyArc#ROOT_HEAD}.
+   */
+  private DependencyGraph(int[] heads, String[] relations, int root) {
+    this.heads = heads;
+    this.relations = relations;
+    this.root = root;
+  }
+
+  /**
+   * Creates a {@link DependencyGraph} from parallel head and relation arrays.
+   *
+   * @param heads For each token, the zero-based index of its head token, or
+   *              {@link DependencyArc#ROOT_HEAD} for the sentence root. Must not be
+   *              {@code null} or empty, every value must be a valid token index or
+   *              {@link DependencyArc#ROOT_HEAD}, no token may head itself, and exactly
+   *              one token must be the root.
+   * @param relations For each token, the label of the relation to its head. Must not be
+   *                  {@code null}, must have the same length as {@code heads}, and no
+   *                  entry may be {@code null} or blank.
+   * @return A validated {@link DependencyGraph}. Never {@code null}.
+   * @throws IllegalArgumentException Thrown if any of the above constraints is violated.
+   */
+  public static DependencyGraph of(int[] heads, String[] relations) {
+    ArgumentChecks.requireNonNullArg(heads, "heads");
+    ArgumentChecks.requireNonNullArg(relations, "relations");
+    if (heads.length == 0) {
+      throw new IllegalArgumentException("a dependency graph needs at least one token");
+    }
+    if (heads.length != relations.length) {
+      throw new IllegalArgumentException("heads and relations must have the same length: "
+          + heads.length + " != " + relations.length);
+    }
+    int roots = 0;
+    int root = DependencyArc.ROOT_HEAD;
+    for (int i = 0; i < heads.length; i++) {
+      if (heads[i] == DependencyArc.ROOT_HEAD) {
+        roots++;
+        root = i;
+      } else if (heads[i] < 0 || heads[i] >= heads.length) {
+        throw new IllegalArgumentException("head of token " + i
+            + " is out of range: " + heads[i]);
+      } else if (heads[i] == i) {
+        throw new IllegalArgumentException("token " + i + " must not head itself");
+      }
+      if (relations[i] == null || StringUtil.isBlank(relations[i])) {
+        throw new IllegalArgumentException("relation of token " + i + " must not be blank");
+      }
+    }
+    if (roots != 1) {
+      throw new IllegalArgumentException("expected exactly one root, found " + roots);
+    }
+    checkAcyclic(heads);
+    return new DependencyGraph(heads.clone(), relations.clone(), root);
+  }
+
+  /**
+   * Rejects a cycle that is disconnected from the single root by following every token's
+   * head chain until it reaches the root or a token already known to reach it.
+   *
+   * @param heads The head array, already checked for range, self-heads, and root count.
+   * @throws IllegalArgumentException Thrown if a head chain returns to a token on that
+   *         same chain.
+   */
+  private static void checkAcyclic(int[] heads) {
+    final byte[] states = new byte[heads.length];
+    for (int start = 0; start < heads.length; start++) {
+      int current = start;
+      while (current != DependencyArc.ROOT_HEAD && states[current] == UNVISITED) {
+        states[current] = VISITING;
+        current = heads[current];
+      }
+      if (current != DependencyArc.ROOT_HEAD && states[current] == VISITING) {
+        throw new IllegalArgumentException(
+            "dependency graph contains a cycle at token " + current);
+      }
+      current = start;
+      while (current != DependencyArc.ROOT_HEAD && states[current] == VISITING) {
+        states[current] = VISITED;
+        current = heads[current];
+      }
+    }
+  }
+
+  /**
+   * @return The number of tokens the graph spans.
+   */
+  public int size() {
+    return heads.length;
+  }
+
+  /**
+   * Retrieves the head of a token.
+   *
+   * @param index The zero-based token index. Must be within {@code [0, size())}.
+   * @return The zero-based index of the head token, or {@link DependencyArc#ROOT_HEAD}
+   *         when the token is the sentence root.
+   * @throws IllegalArgumentException Thrown if {@code index} is out of range.
+   */
+  public int headOf(int index) {
+    checkIndex(index);
+    return heads[index];
+  }
+
+  /**
+   * Retrieves the relation label of a token.
+   *
+   * @param index The zero-based token index. Must be within {@code [0, size())}.
+   * @return The label of the relation between the token and its head. Never {@code null}.
+   * @throws IllegalArgumentException Thrown if {@code index} is out of range.
+   */
+  public String relationOf(int index) {
+    checkIndex(index);
+    return relations[index];
+  }
+
+  /**
+   * @return The zero-based index of the sentence root token.
+   */
+  public int root() {
+    return root;
+  }
+
+  /**
+   * @return All arcs of the graph in token order, one per token. Never {@code null}.
+   */
+  public List<DependencyArc> arcs() {
+    final List<DependencyArc> arcs = new ArrayList<>(heads.length);
+    for (int i = 0; i < heads.length; i++) {
+      arcs.add(new DependencyArc(heads[i], i, relations[i]));
+    }
+    return Collections.unmodifiableList(arcs);
+  }
+
+  /**
+   * Rejects a token index outside {@code [0, size())}.
+   *
+   * @param index The zero-based token index to check.
+   * @throws IllegalArgumentException Thrown if {@code index} is out of range.
+   */
+  private void checkIndex(int index) {
+    if (index < 0 || index >= heads.length) {
+      throw new IllegalArgumentException("token index out of range: " + index
+          + ", size: " + heads.length);
+    }
+  }
+
+  @Override
+  public boolean equals(Object obj) {
+    if (this == obj) {
+      return true;
+    }
+    if (!(obj instanceof DependencyGraph other)) {
+      return false;
+    }
+    return Arrays.equals(heads, other.heads) && Arrays.equals(relations, other.relations);
+  }
+
+  @Override
+  public int hashCode() {
+    return 31 * Arrays.hashCode(heads) + Arrays.hashCode(relations);
+  }
+
+  @Override
+  public String toString() {

Review Comment:
   inheritcDoc



##########
opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/depparse/ArcStandardOracle.java:
##########
@@ -0,0 +1,135 @@
+/*
+ * 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.tools.depparse;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import opennlp.tools.util.ArgumentChecks;
+
+/**
+ * The static oracle for the arc-standard system: derives the transition sequence that

Review Comment:
   Perhaps something like:
   
   <html><head></head><body><p>Its job is to <strong>turn a known correct dependency tree into the parser actions needed to reconstruct that tree</strong>. Those actions provide the answers used to train the parser.</p>
   <p>The parser maintains a <strong>stack</strong> of tokens being processed and a <strong>buffer</strong> of unread tokens. The oracle selects among three actions:</p>
   
   Action | Effect
   -- | --
   SHIFT | Move the next token from the buffer onto the stack.
   LEFT_ARC(label) | Make the top token the head of the token immediately below it; remove that dependent.
   RIGHT_ARC(label) | Make the second token the head of the top token; remove that dependent.
   
   
   <p>It consults the annotated, or “gold,” tree to choose the correct attachment and relation label.</p>
   </body></html>



##########
opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/depparse/DependencyParserME.java:
##########
@@ -0,0 +1,192 @@
+/*
+ * 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.tools.depparse;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+import opennlp.tools.commons.ThreadSafe;
+import opennlp.tools.ml.EventTrainer;
+import opennlp.tools.ml.TrainerFactory;
+import opennlp.tools.ml.TrainerFactory.TrainerType;
+import opennlp.tools.ml.model.Event;
+import opennlp.tools.ml.model.MaxentModel;
+import opennlp.tools.util.ArgumentChecks;
+import opennlp.tools.util.ObjectStream;
+import opennlp.tools.util.TrainingParameters;
+
+/**
+ * A greedy transition-based {@link DependencyParser}: a classifier picks the next
+ * arc-standard {@link Transition} for each configuration until the parse is
+ * complete, always taking the highest scoring transition that is applicable.
+ *
+ * <p>The parser holds an immutable model and no per-parse state, so one instance can be
+ * shared between threads.</p>
+ *
+ * @see DependencyParser
+ * @since 3.0.0
+ */
+@ThreadSafe
+public class DependencyParserME implements DependencyParser {
+
+  private final MaxentModel model;
+  private final DependencyContextGenerator contextGenerator;
+  private final Transition[] transitions;
+
+  /**
+   * Initializes a {@link DependencyParserME} from a {@link DependencyModel}.
+   *
+   * @param model The model to parse with. Must not be {@code null}.
+   * @throws IllegalArgumentException Thrown if {@code model} is {@code null} or an
+   *         outcome inventory is invalid or cannot parse a sentence.
+   */
+  public DependencyParserME(DependencyModel model) {
+    ArgumentChecks.requireNonNullArg(model, "model");
+    this.model = model.getParserModel();
+    this.contextGenerator = new DependencyContextGenerator();
+    this.transitions = decodeOutcomes(this.model);
+  }
+
+  /**
+   * Decodes the outcome inventory once, so that decoding a sentence indexes it instead
+   * of parsing an outcome string per configuration and outcome.
+   *
+   * @param model The transition classification model.
+   * @return The transitions by outcome index. Never {@code null}.
+   * @throws IllegalArgumentException Thrown if an outcome does not decode to a
+   *         transition, which means the model is not a dependency parser model.
+   */
+  private static Transition[] decodeOutcomes(MaxentModel model) {

Review Comment:
   drop static plz



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opennlp.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OPENNLP-547: Add a transition-based dependency parser (opennlp)

Posted by "krickert (via GitHub)" <gi...@apache.org>.
krickert commented on code in PR #1236:
URL: https://github.com/apache/opennlp/pull/1236#discussion_r4180162290


##########
opennlp-api/src/main/java/opennlp/tools/depparse/DependencyTree.java:
##########
@@ -0,0 +1,238 @@
+/*
+ * 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.tools.depparse;
+
+import java.io.Serial;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import opennlp.tools.commons.ThreadSafe;
+import opennlp.tools.util.ArgumentChecks;
+import opennlp.tools.util.StringUtil;
+
+/**
+ * An immutable dependency tree over one sentence: for every token, the index of its head
+ * and the label of the relation to that head.
+ *
+ * <p>Token indices are zero-based positions in the sentence the graph was built for.
+ * Exactly one token carries the head value {@link DependencyArc#ROOT_HEAD}, marking it as
+ * the sentence root. Instances are immutable and safe to share between threads.</p>
+ *
+ * @since 3.0.0
+ */
+@ThreadSafe
+public final class DependencyGraph implements Serializable {
+
+  @Serial
+  private static final long serialVersionUID = 5144949884365294061L;
+
+  /** Traversal state of a token whose head chain has not been followed yet. */
+  private static final byte UNVISITED = 0;
+
+  /** Traversal state of a token on the head chain currently being followed. */
+  private static final byte VISITING = 1;
+
+  /** Traversal state of a token whose head chain is known to reach the root. */
+  private static final byte VISITED = 2;
+
+  private final int[] heads;
+  private final String[] relations;
+  private final int root;
+
+  /**
+   * Wraps already validated arrays; instances are created through {@link #of}.
+   *
+   * @param heads The validated head array, owned by the new instance.
+   * @param relations The validated relation array, owned by the new instance.
+   * @param root The index of the single token whose head is {@link DependencyArc#ROOT_HEAD}.
+   */
+  private DependencyGraph(int[] heads, String[] relations, int root) {
+    this.heads = heads;
+    this.relations = relations;
+    this.root = root;
+  }
+
+  /**
+   * Creates a {@link DependencyGraph} from parallel head and relation arrays.
+   *
+   * @param heads For each token, the zero-based index of its head token, or
+   *              {@link DependencyArc#ROOT_HEAD} for the sentence root. Must not be
+   *              {@code null} or empty, every value must be a valid token index or
+   *              {@link DependencyArc#ROOT_HEAD}, no token may head itself, and exactly
+   *              one token must be the root.
+   * @param relations For each token, the label of the relation to its head. Must not be
+   *                  {@code null}, must have the same length as {@code heads}, and no
+   *                  entry may be {@code null} or blank.
+   * @return A validated {@link DependencyGraph}. Never {@code null}.
+   * @throws IllegalArgumentException Thrown if any of the above constraints is violated.
+   */
+  public static DependencyGraph of(int[] heads, String[] relations) {
+    ArgumentChecks.requireNonNullArg(heads, "heads");
+    ArgumentChecks.requireNonNullArg(relations, "relations");
+    if (heads.length == 0) {
+      throw new IllegalArgumentException("a dependency graph needs at least one token");
+    }
+    if (heads.length != relations.length) {
+      throw new IllegalArgumentException("heads and relations must have the same length: "
+          + heads.length + " != " + relations.length);
+    }
+    int roots = 0;
+    int root = DependencyArc.ROOT_HEAD;
+    for (int i = 0; i < heads.length; i++) {
+      if (heads[i] == DependencyArc.ROOT_HEAD) {
+        roots++;
+        root = i;
+      } else if (heads[i] < 0 || heads[i] >= heads.length) {
+        throw new IllegalArgumentException("head of token " + i
+            + " is out of range: " + heads[i]);
+      } else if (heads[i] == i) {
+        throw new IllegalArgumentException("token " + i + " must not head itself");
+      }
+      if (relations[i] == null || StringUtil.isBlank(relations[i])) {
+        throw new IllegalArgumentException("relation of token " + i + " must not be blank");
+      }
+    }
+    if (roots != 1) {
+      throw new IllegalArgumentException("expected exactly one root, found " + roots);
+    }
+    checkAcyclic(heads);
+    return new DependencyGraph(heads.clone(), relations.clone(), root);
+  }
+
+  /**
+   * Rejects a cycle that is disconnected from the single root by following every token's
+   * head chain until it reaches the root or a token already known to reach it.
+   *
+   * @param heads The head array, already checked for range, self-heads, and root count.
+   * @throws IllegalArgumentException Thrown if a head chain returns to a token on that
+   *         same chain.
+   */
+  private static void checkAcyclic(int[] heads) {
+    final byte[] states = new byte[heads.length];
+    for (int start = 0; start < heads.length; start++) {
+      int current = start;
+      while (current != DependencyArc.ROOT_HEAD && states[current] == UNVISITED) {
+        states[current] = VISITING;
+        current = heads[current];
+      }
+      if (current != DependencyArc.ROOT_HEAD && states[current] == VISITING) {
+        throw new IllegalArgumentException(
+            "dependency graph contains a cycle at token " + current);
+      }
+      current = start;
+      while (current != DependencyArc.ROOT_HEAD && states[current] == VISITING) {
+        states[current] = VISITED;
+        current = heads[current];
+      }
+    }
+  }
+
+  /**
+   * @return The number of tokens the graph spans.
+   */
+  public int size() {
+    return heads.length;
+  }
+
+  /**
+   * Retrieves the head of a token.
+   *
+   * @param index The zero-based token index. Must be within {@code [0, size())}.
+   * @return The zero-based index of the head token, or {@link DependencyArc#ROOT_HEAD}
+   *         when the token is the sentence root.
+   * @throws IllegalArgumentException Thrown if {@code index} is out of range.
+   */
+  public int headOf(int index) {
+    checkIndex(index);
+    return heads[index];
+  }
+
+  /**
+   * Retrieves the relation label of a token.
+   *
+   * @param index The zero-based token index. Must be within {@code [0, size())}.
+   * @return The label of the relation between the token and its head. Never {@code null}.
+   * @throws IllegalArgumentException Thrown if {@code index} is out of range.
+   */
+  public String relationOf(int index) {
+    checkIndex(index);
+    return relations[index];
+  }
+
+  /**
+   * @return The zero-based index of the sentence root token.
+   */
+  public int root() {
+    return root;
+  }
+
+  /**
+   * @return All arcs of the graph in token order, one per token. Never {@code null}.
+   */
+  public List<DependencyArc> arcs() {
+    final List<DependencyArc> arcs = new ArrayList<>(heads.length);
+    for (int i = 0; i < heads.length; i++) {
+      arcs.add(new DependencyArc(heads[i], i, relations[i]));
+    }
+    return Collections.unmodifiableList(arcs);
+  }
+
+  /**
+   * Rejects a token index outside {@code [0, size())}.
+   *
+   * @param index The zero-based token index to check.
+   * @throws IllegalArgumentException Thrown if {@code index} is out of range.
+   */
+  private void checkIndex(int index) {
+    if (index < 0 || index >= heads.length) {
+      throw new IllegalArgumentException("token index out of range: " + index
+          + ", size: " + heads.length);
+    }
+  }
+
+  @Override

Review Comment:
   done



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opennlp.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OPENNLP-547: Add a dependency parser component (opennlp)

Posted by "krickert (via GitHub)" <gi...@apache.org>.
krickert commented on PR #1236:
URL: https://github.com/apache/opennlp/pull/1236#issuecomment-5547318170

   Rebased on main .. good to go
   
   #1182 merged the diff is the parser alone, 34 new files and no change to existing code. 
   
   Also a run of the review conventions.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opennlp.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OPENNLP-547: Add a transition-based dependency parser (opennlp)

Posted by "krickert (via GitHub)" <gi...@apache.org>.
krickert commented on PR #1236:
URL: https://github.com/apache/opennlp/pull/1236#issuecomment-5884303683

   Thanks. Updated and squashed to one commit. Eval run: [build 88](https://ci-builds.apache.org/job/OpenNLP/job/eval-tests-configurable/88/).
   
   - Removed the factory hook and raw-model parser constructor. The parser takes a `DependencyModel`, which has one constructor: `(lang, MaxentModel, manifest)`.
   - Removed `ParserTrainer`. The cross validator trains the parser itself, following `ChunkerCrossValidator`, and accepts evaluation listeners.
   - Added `DependencyEvaluationMonitor` following the POS equivalent, with `-misclassified` output through `DependencyEvaluationErrorListener`. The tools use the shared evaluation parameters and report invalid fold counts with a message.
   - Shared token/tag validation through `DependencySample.checkTokensAndTags` in opennlp-api, and UAS/LAS calculation through `AttachmentScores`.
   - Moved `ArcStandardState.copy()` and its test to #1323.
   - Applied the Javadoc, constants, helper, test-fixture and manual changes. CoNLL-U ID and HEAD parsing now share an ASCII digit scanner.
   - Set OPENNLP-547 to 3.0.0 and retargeted #1323 to `main`.
   
   The additional tests also caught inconsistent HEAD parsing. The CoNLL-U factory now rejects non-UTF-8 encodings, and the graph and sample serialization IDs have been recomputed.
   
   Feature separator collisions are tracked in #1342 for a separate fix and evaluation before the first 3.0 dependency parser models ship.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opennlp.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OPENNLP-547: Add a transition-based dependency parser (opennlp)

Posted by "rzo1 (via GitHub)" <gi...@apache.org>.
rzo1 commented on PR #1236:
URL: https://github.com/apache/opennlp/pull/1236#issuecomment-5999501142

   Can you trigger an eval run?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opennlp.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OPENNLP-547: Add a dependency parser component (opennlp)

Posted by "jzonthemtn (via GitHub)" <gi...@apache.org>.
jzonthemtn commented on PR #1236:
URL: https://github.com/apache/opennlp/pull/1236#issuecomment-5560506542

   Thanks @krickert. A long open JIRA ticket for sure!
   
   The API and graph validation look solid. I found two issues worth checking into:
   
   * The CoNLL-U reader accepts `DEPREL=_` as a label instead of skipping the incomplete annotation.
   * Training with a tag such as `UNK` overwrites a reserved vocabulary entry, producing a model that serializes successfully but fails to reload.
   
   What do you think about held-out accuracy tests for the neural parser, similar to the treebank evaluation for the classical parser?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opennlp.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OPENNLP-547: Add a dependency parser component (opennlp)

Posted by "krickert (via GitHub)" <gi...@apache.org>.
krickert commented on PR #1236:
URL: https://github.com/apache/opennlp/pull/1236#issuecomment-5561271280

   Thanks Jeff. Both are fixed, each with a failing test committed ahead of the fix. The CoNLL-U reader now skips a sentence whose relation column is the underscore placeholder, the same way it already skipped an underscore head. The feedforward trainer no longer lets a tag or label spelled like a reserved symbol take over that symbol's embedding row; it shares the row, as words already did, so the model reloads.
   
   On held-out accuracy: I added `UniversalDependencyParserEval` in opennlp-eval-tests, following the `AbstractEvalTest` and `OPENNLP_DATA_DIR` pattern. It trains both parsers on the UD 2.0 English train split and pins the dev-split scores: the transition parser at UAS 0.8182 and LAS 0.7861, the feedforward parser at UAS 0.8413 and LAS 0.8174, on 25,148 words. The numbers reproduce exactly across runs. It replaces the property-gated evaluation test that lived in opennlp-formats.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opennlp.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OPENNLP-547: Add a dependency parser component (opennlp)

Posted by "krickert (via GitHub)" <gi...@apache.org>.
krickert commented on PR #1236:
URL: https://github.com/apache/opennlp/pull/1236#issuecomment-5639396719

   Eval ran successfully


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opennlp.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OPENNLP-547: Add a transition-based dependency parser (opennlp)

Posted by "krickert (via GitHub)" <gi...@apache.org>.
krickert commented on code in PR #1236:
URL: https://github.com/apache/opennlp/pull/1236#discussion_r4180907634


##########
opennlp-api/src/main/java/opennlp/tools/depparse/DependencyGraph.java:
##########
@@ -0,0 +1,238 @@
+/*
+ * 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.tools.depparse;
+
+import java.io.Serial;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import opennlp.tools.commons.ThreadSafe;
+import opennlp.tools.util.ArgumentChecks;
+import opennlp.tools.util.StringUtil;
+
+/**
+ * An immutable dependency tree over one sentence: for every token, the index of its head
+ * and the label of the relation to that head.
+ *
+ * <p>Token indices are zero-based positions in the sentence the graph was built for.
+ * Exactly one token carries the head value {@link DependencyArc#ROOT_HEAD}, marking it as
+ * the sentence root. Instances are immutable and safe to share between threads.</p>
+ *
+ * @since 3.0.0
+ */
+@ThreadSafe
+public final class DependencyGraph implements Serializable {

Review Comment:
   Done



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opennlp.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OPENNLP-547: Add a transition-based dependency parser (opennlp)

Posted by "krickert (via GitHub)" <gi...@apache.org>.
krickert commented on PR #1236:
URL: https://github.com/apache/opennlp/pull/1236#issuecomment-6002795114

   Eval build on it's way.
   
   https://ci-builds.apache.org/job/OpenNLP/job/eval-tests-configurable/95/


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opennlp.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OPENNLP-547: Add a transition-based dependency parser (opennlp)

Posted by "krickert (via GitHub)" <gi...@apache.org>.
krickert commented on PR #1236:
URL: https://github.com/apache/opennlp/pull/1236#issuecomment-6007442605

   > Eval build on it's way.
   > 
   > https://ci-builds.apache.org/job/OpenNLP/job/eval-tests-configurable/95/
   
   Eval green


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opennlp.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OPENNLP-547: Add a dependency parser component (opennlp)

Posted by "rzo1 (via GitHub)" <gi...@apache.org>.
rzo1 commented on PR #1236:
URL: https://github.com/apache/opennlp/pull/1236#issuecomment-5581662428

   > Evals passed for this, going to re-run it as I added double precision scoring.
   
   Moved to draft for now. Please re-open as ready for review once all your additional checks and stuff are done. 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opennlp.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OPENNLP-547: Add a dependency parser component (opennlp)

Posted by "krickert (via GitHub)" <gi...@apache.org>.
krickert commented on PR #1236:
URL: https://github.com/apache/opennlp/pull/1236#issuecomment-5593761889

   https://ci-builds.apache.org/job/OpenNLP/job/eval-tests-configurable/76/console
   
   Eval build is running


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opennlp.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OPENNLP-547: Add a dependency parser component (opennlp)

Posted by "krickert (via GitHub)" <gi...@apache.org>.
krickert commented on code in PR #1236:
URL: https://github.com/apache/opennlp/pull/1236#discussion_r4057873620


##########
opennlp-core/opennlp-formats/src/main/java/opennlp/tools/formats/conllu/ConlluDependencySampleStream.java:
##########
@@ -0,0 +1,270 @@
+/*
+ * 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.tools.formats.conllu;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.nio.charset.CodingErrorAction;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import opennlp.tools.depparse.DependencyGraph;
+import opennlp.tools.depparse.DependencySample;
+import opennlp.tools.util.InputStreamFactory;
+import opennlp.tools.util.InvalidFormatException;
+import opennlp.tools.util.ObjectStream;
+import opennlp.tools.util.StringUtil;
+
+/**
+ * Reads {@link DependencySample samples} directly from
+ * <a href="https://universaldependencies.org/format.html">CoNLL-U</a> content, mapping
+ * the {@code HEAD} and {@code DEPREL} columns of the basic dependency annotation.
+ *
+ * <p>This reader does not use {@link ConlluStream}, which merges multiword token ranges
+ * with their syntactic words for token and lemma samples. Dependency samples instead
+ * omit range lines and empty nodes while retaining the syntactic word rows. Sentences
+ * with incomplete or invalid basic dependencies are skipped and counted.</p>
+ *
+ * @since 3.0.0
+ */
+public class ConlluDependencySampleStream implements ObjectStream<DependencySample> {
+
+  private static final Logger logger =
+      LoggerFactory.getLogger(ConlluDependencySampleStream.class);
+
+  /** The number of tab-separated columns of a CoNLL-U word line. */
+  private static final int COLUMNS = 10;
+
+  /** The column holding the word index, a multiword token range, or an empty node id. */
+  private static final int ID = 0;
+
+  /** The column holding the word form. */
+  private static final int FORM = 1;
+
+  /** The column holding the universal part-of-speech tag. */
+  private static final int UPOS = 3;
+
+  /** The column holding the language-specific part-of-speech tag. */
+  private static final int XPOS = 4;
+
+  /** The column holding the one-based index of the head, {@code 0} for the root. */
+  private static final int HEAD = 6;
+
+  /** The column holding the relation label to the head. */
+  private static final int DEPREL = 7;
+
+  /** The CoNLL-U placeholder of a missing value. */
+  private static final String PLACEHOLDER = "_";
+
+  /** The byte order mark some editors prepend to UTF-8 content. */
+  private static final char BOM = '\ufeff';
+
+  /** The first character of a comment line. */
+  private static final char COMMENT = '#';
+
+  private final InputStreamFactory in;
+  private final int tagColumn;
+
+  private BufferedReader reader;
+  private boolean firstLine = true;
+  private int skipped;
+
+  /**
+   * Initializes the stream.
+   *
+   * @param in The CoNLL-U content. Must not be {@code null}.
+   * @param tagset The tagset whose part-of-speech column feeds the sample tags. Must
+   *               not be {@code null}.
+   * @throws IOException Thrown if opening the content fails.
+   * @throws IllegalArgumentException Thrown if any parameter is {@code null}.
+   */
+  public ConlluDependencySampleStream(InputStreamFactory in, ConlluTagset tagset)
+      throws IOException {
+    if (in == null) {
+      throw new IllegalArgumentException("in must not be null");
+    }
+    if (tagset == null) {
+      throw new IllegalArgumentException("tagset must not be null");
+    }
+    this.in = in;
+    this.tagColumn = tagset == ConlluTagset.U ? UPOS : XPOS;
+    this.reader = open();
+  }
+
+  /**
+   * {@inheritDoc}
+   * Sentences without a usable basic dependency annotation are skipped, and their count
+   * is logged once the content is exhausted.
+   */
+  @Override
+  public DependencySample read() throws IOException {
+    List<String[]> words;
+    while (!(words = nextSentence()).isEmpty()) {
+      final DependencySample sample = convert(words);
+      if (sample != null) {
+        return sample;
+      }
+      skipped++;
+    }
+    if (skipped > 0) {
+      logger.warn("Skipped {} sentence(s) without a complete basic dependency annotation.",
+          skipped);
+      skipped = 0;
+    }
+    return null;
+  }
+
+  /**
+   * Reads the syntactic word lines of the next sentence: comments, multiword token
+   * ranges, and empty nodes are dropped; an empty list means the end of the content.
+   *
+   * <p>Sentences are separated by any line {@link StringUtil#isBlank(CharSequence)}
+   * accepts, so a separator carrying a stray no-break space still separates rather than
+   * reaching the word line parser.</p>
+   *
+   * @return The word lines of the next sentence, or an empty list at the end of the
+   *         content. Never {@code null}.
+   * @throws IOException Thrown if reading fails.
+   * @throws InvalidFormatException Thrown if a word line does not have the expected column count.
+   */
+  private List<String[]> nextSentence() throws IOException {
+    final List<String[]> words = new ArrayList<>();
+    String line;
+    while ((line = reader.readLine()) != null) {
+      if (firstLine) {
+        firstLine = false;
+        if (!line.isEmpty() && line.charAt(0) == BOM) {
+          line = line.substring(1);
+        }
+      }
+      if (StringUtil.isBlank(line)) {
+        if (!words.isEmpty()) {
+          return words;
+        }
+        continue;
+      }
+      if (line.charAt(0) == COMMENT) {
+        continue;
+      }
+      final String[] fields = splitFields(line);
+      if (fields.length != COLUMNS) {
+        throw new InvalidFormatException("CoNLL-U word line has " + fields.length
+            + " columns, expected " + COLUMNS + ": " + line);
+      }
+      final String id = fields[ID];
+      if (id.indexOf('-') < 0 && id.indexOf('.') < 0) {
+        words.add(fields);
+      }
+    }
+    return words;
+  }
+
+  /**
+   * Splits a CoNLL-U word line into its tab-delimited fields, retaining empty fields.
+   *
+   * @param line The line to split.
+   * @return The fields in source order. Never {@code null}.
+   */
+  private String[] splitFields(String line) {
+    final List<String> fields = new ArrayList<>();
+    int fieldStart = 0;
+    for (int i = 0; i < line.length(); i++) {
+      if (line.charAt(i) == '\t') {
+        fields.add(line.substring(fieldStart, i));
+        fieldStart = i + 1;
+      }
+    }
+    fields.add(line.substring(fieldStart));
+    return fields.toArray(String[]::new);
+  }
+
+  /**
+   * Converts one sentence into a sample.
+   *
+   * @param words The word lines of the sentence.
+   * @return The converted sample, or {@code null} when the sentence's annotation is
+   *         unusable, for example an underscore head or relation or a graph that is not
+   *         a tree.
+   */
+  private DependencySample convert(List<String[]> words) {
+    final int n = words.size();
+    final String[] tokens = new String[n];
+    final String[] tags = new String[n];
+    final int[] heads = new int[n];
+    final String[] relations = new String[n];
+    for (int i = 0; i < n; i++) {
+      final String[] word = words.get(i);
+      if (!Integer.toString(i + 1).equals(word[ID])) {
+        return null;
+      }
+      tokens[i] = word[FORM];
+      tags[i] = word[tagColumn];

Review Comment:
   fixed.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opennlp.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OPENNLP-547: Add a transition-based dependency parser component (opennlp)

Posted by "mawiesne (via GitHub)" <gi...@apache.org>.
mawiesne merged PR #1236:
URL: https://github.com/apache/opennlp/pull/1236


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opennlp.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OPENNLP-547: Add a dependency parser component (opennlp)

Posted by "rzo1 (via GitHub)" <gi...@apache.org>.
rzo1 commented on code in PR #1236:
URL: https://github.com/apache/opennlp/pull/1236#discussion_r4034847927


##########
opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/depparse/FeedforwardDependencyTrainer.java:
##########
@@ -0,0 +1,1175 @@
+/*
+ * 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.tools.depparse;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Random;
+import java.util.function.Function;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import opennlp.tools.util.ObjectStream;
+
+/**
+ * Trains the {@link FeedforwardDependencyModel} entirely in Java: 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
+ * <a href="https://aclanthology.org/D14-1082/">Chen and Manning (2014)</a>. Training and
+ * inference use Java arrays and require no external training framework.
+ *
+ * <p>Words below the frequency cutoff share a learned unknown embedding; absent
+ * template positions share a learned padding embedding. Non-projective samples have no
+ * arc-standard derivation and are skipped. Training is deterministic for a fixed
+ * {@link Settings#seed()}.</p>
+ *
+ * @since 3.0.0
+ */
+public final class FeedforwardDependencyTrainer {
+
+  private static final Logger logger =
+      LoggerFactory.getLogger(FeedforwardDependencyTrainer.class);
+
+  /** The AdaGrad denominator offset that keeps the first steps finite. */
+  private static final double ADAGRAD_EPSILON = 1e-6;
+
+  /** The derivative factor of the cube activation, {@code d/dx x^3 = 3x^2}. */
+  private static final double CUBE_DERIVATIVE_FACTOR = 3.0;
+
+  /** The numerator of the Glorot uniform bound, {@code sqrt(6 / (fanIn + fanOut))}. */
+  private static final double GLOROT_NUMERATOR = 6.0;
+
+  /** The half-width of the uniform range embeddings are drawn from. */
+  private static final double EMBEDDING_INIT_SCALE = 0.01;
+
+  /** The smallest probability the reported training loss takes the log of. */
+  private static final double LOSS_PROBABILITY_FLOOR = 1e-12;
+
+  /** The sentence loss reported when refinement made no update for a sentence. */
+  private static final double NO_UPDATE = -1.0;
+
+  /** Special-symbol rows present before any training vocabulary is added. */
+  private static final int MIN_VOCABULARY_ROWS = 8;
+
+  /** SHIFT and at least one RIGHT_ARC are required to parse a sentence. */
+  private static final int MIN_TRANSITIONS = 2;
+
+  /** Prevents construction of this utility class. */
+  private FeedforwardDependencyTrainer() {
+  }
+
+  /**
+   * The training hyperparameters.
+   *
+   * @param embeddingSize The embedding dimensionality. Must be positive.
+   * @param hiddenSize The hidden layer width. Must be positive.
+   * @param epochs The number of passes over the examples. Must be positive.
+   * @param batchSize The minibatch size. Must be positive.
+   * @param learningRate The AdaGrad step size. Must be positive.
+   * @param l2 The L2 penalty applied to the dense weights. Must not be negative.
+   * @param dropout The hidden dropout probability. Must be in {@code [0, 1)}.
+   * @param wordCutoff The minimum frequency for a word to get its own embedding. Must
+   *                   not be negative.
+   * @param seed The random seed making a run reproducible.
+   */
+  public record Settings(int embeddingSize, int hiddenSize, int epochs, int batchSize,

Review Comment:
   Please use `TrainingParameters` with named keys instead of a separate `Settings` record.



##########
opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/depparse/FeedforwardDependencyModel.java:
##########
@@ -0,0 +1,951 @@
+/*
+ * 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.tools.depparse;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReferenceArray;
+
+import opennlp.tools.commons.ThreadSafe;
+import opennlp.tools.util.InvalidFormatException;
+import opennlp.tools.util.StringUtil;
+
+/**
+ * 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, stored
+ * in a plain versioned binary format with no serialization framework involved. The
+ * architecture follows
+ * <a href="https://aclanthology.org/D14-1082/">Chen and Manning (2014)</a>.
+ *
+ * <p>The network runs with Java arrays and requires no native runtime. The same class
+ * scores configurations during training and decoding. Unknown words use a learned
+ * fallback row; words are matched case-insensitively after
+ * {@link #normalize(String) normalization}.</p>
+ *
+ * <p>Instances returned by {@link FeedforwardDependencyTrainer} are immutable and safe
+ * to share between threads. {@link FeedforwardDependencyTrainer#refine refine} updates
+ * an independent copy.</p>
+ *
+ * @see FeedforwardDependencyParser
+ * @see FeedforwardDependencyTrainer
+ * @since 3.0.0
+ */
+@ThreadSafe
+public class FeedforwardDependencyModel {

Review Comment:
   Not a `BaseModel`, see the review comment.



##########
opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/depparse/FeedforwardDependencyParser.java:
##########
@@ -0,0 +1,228 @@
+/*
+ * 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.tools.depparse;
+
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.List;
+
+import opennlp.tools.commons.ThreadSafe;
+
+/**
+ * The pure-Java neural {@link DependencyParser}: an arc-standard decoder over the
+ * {@link FeedforwardDependencyModel}, greedy by default and beamed when constructed
+ * with a beam size above one.
+ *
+ * <p>Beam decoding retains the highest scoring transition sequences by summed
+ * log-probability. Complete arc-standard derivations for a sentence have equal length,
+ * so their scores need no length normalization.</p>
+ *
+ * <p>Inference is ordinary array arithmetic with no native runtime involved, so this
+ * parser has the same input and output API as the classical parser while scoring with
+ * learned dense representations instead of sparse feature conjunctions.</p>
+ *
+ * <p>The parser holds an immutable model and no per-parse state, so one instance can be
+ * shared between threads.</p>
+ *
+ * @see FeedforwardDependencyTrainer
+ * @since 3.0.0
+ */
+@ThreadSafe
+public class FeedforwardDependencyParser implements DependencyParser {
+
+  /** The beam size at which decoding is greedy. */
+  private static final int GREEDY_BEAM_SIZE = 1;
+
+  private final FeedforwardDependencyModel model;
+  private final Transition[] transitions;
+  private final int beamSize;
+
+  /**
+   * Initializes a greedy {@link FeedforwardDependencyParser}.
+   *
+   * @param model The model to parse with. Must not be {@code null}.
+   * @throws IllegalArgumentException Thrown if {@code model} is {@code null} or an
+   *         outcome of the model does not decode to a transition.
+   */
+  public FeedforwardDependencyParser(FeedforwardDependencyModel model) {
+    this(model, GREEDY_BEAM_SIZE);
+  }
+
+  /**
+   * Initializes a {@link FeedforwardDependencyParser} with a beam.
+   *
+   * @param model The model to parse with. Must not be {@code null}.
+   * @param beamSize The number of transition sequences to retain. Must be
+   *                 greater than zero; {@code 1} decodes greedily.
+   * @throws IllegalArgumentException Thrown if {@code model} is {@code null},
+   *         {@code beamSize} is not positive, or an outcome of the model does not
+   *         decode to a transition.
+   */
+  public FeedforwardDependencyParser(FeedforwardDependencyModel model, int beamSize) {
+    if (model == null) {
+      throw new IllegalArgumentException("model must not be null");
+    }
+    if (beamSize < GREEDY_BEAM_SIZE) {
+      throw new IllegalArgumentException("beamSize must be positive: " + beamSize);
+    }
+    this.model = model;
+    this.beamSize = beamSize;
+    // Parser instances read immutable models. Training and refinement use uncached copies.
+    model.enableScoringCache();
+    final String[] outcomes = model.transitions();
+    this.transitions = new Transition[outcomes.length];
+    for (int i = 0; i < outcomes.length; i++) {
+      transitions[i] = Transition.decode(outcomes[i]);
+    }
+  }
+
+  /**
+   * {@inheritDoc}
+   *
+   * @throws IllegalStateException If no model outcome is applicable in a configuration
+   *         or the model produces a non-finite transition score.
+   */
+  @Override
+  public DependencyGraph parse(String[] tokens, String[] tags) {
+    ParserInput.check(tokens, tags);
+    if (beamSize == GREEDY_BEAM_SIZE) {
+      return greedyParse(tokens, tags);
+    }
+    return beamParse(tokens, tags);
+  }
+
+  /**
+   * Decodes greedily: the highest scoring applicable transition wins each step.
+   *
+   * @param tokens The sentence tokens.
+   * @param tags The POS tags, aligned with {@code tokens}.
+   * @return The parse. Never {@code null}.
+   * @throws IllegalStateException If no model outcome is applicable in a configuration
+   *         or the model produces a non-finite transition score.
+   */
+  private DependencyGraph greedyParse(String[] tokens, String[] tags) {
+    final ArcStandardState state = new ArcStandardState(tokens.length);
+    while (!state.isTerminal()) {
+      final double[] scores = model.score(
+          model.featureIds(FeedforwardContext.extract(state, tokens, tags)));
+      Transition best = null;
+      double bestScore = Double.NEGATIVE_INFINITY;
+      for (int i = 0; i < scores.length; i++) {
+        if (scores[i] > bestScore && state.canApply(transitions[i])) {
+          best = transitions[i];
+          bestScore = scores[i];
+        }
+      }
+      if (best == null) {
+        throw new IllegalStateException(
+            "no applicable transition among the model outcomes in " + state);
+      }
+      state.apply(best);
+    }
+    return state.toGraph();
+  }
+
+  /**
+   * One search alternative of the beam.
+   *
+   * @param state The configuration reached so far.
+   * @param score The summed log-probability of the transitions taken to reach it.
+   * @param next The transition that would advance {@code state}, or {@code null} once
+   *             it has been applied or the state is complete.
+   */
+  private record Alternative(ArcStandardState state, double score, Transition next) {
+  }
+
+  /**
+   * Decodes with a beam and returns its highest scoring complete sequence.
+   *
+   * @param tokens The sentence tokens.
+   * @param tags The POS tags, aligned with {@code tokens}.
+   * @return The parse. Never {@code null}.
+   * @throws IllegalStateException If no beam alternative can be advanced by a model
+   *         outcome or the model produces a non-finite transition score.
+   */
+  private DependencyGraph beamParse(String[] tokens, String[] tags) {
+    List<Alternative> beam =
+        List.of(new Alternative(new ArcStandardState(tokens.length), 0.0, null));
+    while (true) {
+      boolean advanced = false;
+      final List<Alternative> expansions = new ArrayList<>();
+      for (final Alternative alternative : beam) {
+        if (alternative.state().isTerminal()) {
+          expansions.add(alternative);
+          continue;
+        }
+        advanced = true;
+        final double[] logProbabilities = logSoftmax(model.score(
+            model.featureIds(FeedforwardContext.extract(alternative.state(), tokens, tags))));
+        for (int i = 0; i < logProbabilities.length; i++) {
+          if (alternative.state().canApply(transitions[i])) {
+            expansions.add(new Alternative(alternative.state(),
+                alternative.score() + logProbabilities[i], transitions[i]));
+          }
+        }
+      }
+      if (!advanced) {
+        break;
+      }
+      expansions.sort(Comparator.comparingDouble(Alternative::score).reversed());
+      final List<Alternative> survivors =
+          new ArrayList<>(Math.min(beamSize, expansions.size()));
+      for (int i = 0; i < expansions.size() && survivors.size() < beamSize; i++) {
+        final Alternative expansion = expansions.get(i);
+        if (expansion.next() == null) {
+          survivors.add(expansion);
+        } else {
+          final ArcStandardState state = expansion.state().copy();
+          state.apply(expansion.next());
+          survivors.add(new Alternative(state, expansion.score(), null));
+        }
+      }
+      if (survivors.isEmpty()) {
+        throw new IllegalStateException(
+            "no applicable transition among the model outcomes in the beam");
+      }
+      beam = survivors;
+    }
+    return beam.get(0).state().toGraph();
+  }
+
+  /**
+   * Normalizes raw transition scores to log-probabilities.
+   *
+   * @param scores The finite, non-empty raw output scores.
+   * @return The log-softmax of {@code scores}. Never {@code null}.
+   */
+  private double[] logSoftmax(double[] scores) {

Review Comment:
   `logSoftmax` also exists in `FeedforwardDependencyTrainer:647`, and the test reaches both through reflection. Please make one shared package-private helper and test that directly.



##########
opennlp-api/src/main/java/opennlp/tools/depparse/DependencySample.java:
##########
@@ -0,0 +1,145 @@
+/*
+ * 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.tools.depparse;
+
+import java.util.Arrays;
+import java.util.Objects;
+
+import opennlp.tools.commons.ThreadSafe;
+
+/**
+ * One dependency-annotated sentence: tokens, their part-of-speech tags, and the gold
+ * {@link DependencyGraph} over them. Used for training and evaluating a
+ * {@link DependencyParser}.
+ *
+ * <p>Instances are immutable and safe to share between threads.</p>
+ *
+ * @since 3.0.0
+ */
+@ThreadSafe
+public class DependencySample {

Review Comment:
   All other samples implement `opennlp.tools.commons.Sample`. Please do the same and add `serialVersionUID` (also `DependencyGraph`).



##########
opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/depparse/DependencyCrossValidator.java:
##########
@@ -0,0 +1,186 @@
+/*
+ * 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.tools.depparse;
+
+import java.io.IOException;
+import java.util.function.Predicate;
+
+import opennlp.tools.util.ObjectStream;
+import opennlp.tools.util.eval.CrossValidationPartitioner;
+import opennlp.tools.util.eval.Mean;
+
+/**
+ * Cross validator for a {@link DependencyParser}.
+ *
+ * <p>The samples are split into {@code k} folds. For each fold a parser is trained on the
+ * other {@code k - 1} folds through the supplied {@link Trainer} and scored on the
+ * held-out fold with a {@link DependencyEvaluator}. The unlabeled and labeled attachment
+ * scores are accumulated over all evaluated tokens, so every token of the input counts
+ * once, in the fold it was held out from. Both parser implementations of this package can
+ * be validated, because the trainer is supplied by the caller.</p>
+ *
+ * @see DependencyEvaluator
+ * @see CrossValidationPartitioner
+ * @since 3.0.0
+ */
+public class DependencyCrossValidator {
+
+  /** The smallest fold count that leaves training data for every fold. */
+  private static final int MIN_FOLDS = 2;
+
+  /**
+   * Trains a {@link DependencyParser} on the samples of the folds that are not held out.
+   */
+  @FunctionalInterface
+  public interface Trainer {

Review Comment:
   `Trainer` collides with `opennlp.tools.commons.Trainer`. Please rename.



##########
opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/depparse/ParserInput.java:
##########
@@ -0,0 +1,59 @@
+/*
+ * 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.tools.depparse;
+
+/**
+ * Validates the token and tag arrays a parser receives. The checks match the ones a
+ * {@link DependencySample} applies to its arrays; keeping a copy here avoids a call
+ * into a package-private member of another module.
+ */
+final class ParserInput {

Review Comment:
   Copy of `DependencySample.java:76-95`, and the Javadoc says so. Please remove the duplicate.



##########
opennlp-core/opennlp-formats/src/main/java/opennlp/tools/formats/conllu/ConlluDependencySampleStream.java:
##########
@@ -0,0 +1,270 @@
+/*
+ * 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.tools.formats.conllu;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.nio.charset.CodingErrorAction;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import opennlp.tools.depparse.DependencyGraph;
+import opennlp.tools.depparse.DependencySample;
+import opennlp.tools.util.InputStreamFactory;
+import opennlp.tools.util.InvalidFormatException;
+import opennlp.tools.util.ObjectStream;
+import opennlp.tools.util.StringUtil;
+
+/**
+ * Reads {@link DependencySample samples} directly from
+ * <a href="https://universaldependencies.org/format.html">CoNLL-U</a> content, mapping
+ * the {@code HEAD} and {@code DEPREL} columns of the basic dependency annotation.
+ *
+ * <p>This reader does not use {@link ConlluStream}, which merges multiword token ranges
+ * with their syntactic words for token and lemma samples. Dependency samples instead
+ * omit range lines and empty nodes while retaining the syntactic word rows. Sentences
+ * with incomplete or invalid basic dependencies are skipped and counted.</p>
+ *
+ * @since 3.0.0
+ */
+public class ConlluDependencySampleStream implements ObjectStream<DependencySample> {
+
+  private static final Logger logger =
+      LoggerFactory.getLogger(ConlluDependencySampleStream.class);
+
+  /** The number of tab-separated columns of a CoNLL-U word line. */
+  private static final int COLUMNS = 10;
+
+  /** The column holding the word index, a multiword token range, or an empty node id. */
+  private static final int ID = 0;
+
+  /** The column holding the word form. */
+  private static final int FORM = 1;
+
+  /** The column holding the universal part-of-speech tag. */
+  private static final int UPOS = 3;
+
+  /** The column holding the language-specific part-of-speech tag. */
+  private static final int XPOS = 4;
+
+  /** The column holding the one-based index of the head, {@code 0} for the root. */
+  private static final int HEAD = 6;
+
+  /** The column holding the relation label to the head. */
+  private static final int DEPREL = 7;
+
+  /** The CoNLL-U placeholder of a missing value. */
+  private static final String PLACEHOLDER = "_";
+
+  /** The byte order mark some editors prepend to UTF-8 content. */
+  private static final char BOM = '\ufeff';
+
+  /** The first character of a comment line. */
+  private static final char COMMENT = '#';
+
+  private final InputStreamFactory in;
+  private final int tagColumn;
+
+  private BufferedReader reader;
+  private boolean firstLine = true;
+  private int skipped;
+
+  /**
+   * Initializes the stream.
+   *
+   * @param in The CoNLL-U content. Must not be {@code null}.
+   * @param tagset The tagset whose part-of-speech column feeds the sample tags. Must
+   *               not be {@code null}.
+   * @throws IOException Thrown if opening the content fails.
+   * @throws IllegalArgumentException Thrown if any parameter is {@code null}.
+   */
+  public ConlluDependencySampleStream(InputStreamFactory in, ConlluTagset tagset)
+      throws IOException {
+    if (in == null) {
+      throw new IllegalArgumentException("in must not be null");
+    }
+    if (tagset == null) {
+      throw new IllegalArgumentException("tagset must not be null");
+    }
+    this.in = in;
+    this.tagColumn = tagset == ConlluTagset.U ? UPOS : XPOS;
+    this.reader = open();
+  }
+
+  /**
+   * {@inheritDoc}
+   * Sentences without a usable basic dependency annotation are skipped, and their count
+   * is logged once the content is exhausted.
+   */
+  @Override
+  public DependencySample read() throws IOException {
+    List<String[]> words;
+    while (!(words = nextSentence()).isEmpty()) {
+      final DependencySample sample = convert(words);
+      if (sample != null) {
+        return sample;
+      }
+      skipped++;
+    }
+    if (skipped > 0) {
+      logger.warn("Skipped {} sentence(s) without a complete basic dependency annotation.",
+          skipped);
+      skipped = 0;
+    }
+    return null;
+  }
+
+  /**
+   * Reads the syntactic word lines of the next sentence: comments, multiword token
+   * ranges, and empty nodes are dropped; an empty list means the end of the content.
+   *
+   * <p>Sentences are separated by any line {@link StringUtil#isBlank(CharSequence)}
+   * accepts, so a separator carrying a stray no-break space still separates rather than
+   * reaching the word line parser.</p>
+   *
+   * @return The word lines of the next sentence, or an empty list at the end of the
+   *         content. Never {@code null}.
+   * @throws IOException Thrown if reading fails.
+   * @throws InvalidFormatException Thrown if a word line does not have the expected column count.
+   */
+  private List<String[]> nextSentence() throws IOException {
+    final List<String[]> words = new ArrayList<>();
+    String line;
+    while ((line = reader.readLine()) != null) {
+      if (firstLine) {
+        firstLine = false;
+        if (!line.isEmpty() && line.charAt(0) == BOM) {
+          line = line.substring(1);
+        }
+      }
+      if (StringUtil.isBlank(line)) {
+        if (!words.isEmpty()) {
+          return words;
+        }
+        continue;
+      }
+      if (line.charAt(0) == COMMENT) {
+        continue;
+      }
+      final String[] fields = splitFields(line);
+      if (fields.length != COLUMNS) {
+        throw new InvalidFormatException("CoNLL-U word line has " + fields.length
+            + " columns, expected " + COLUMNS + ": " + line);
+      }
+      final String id = fields[ID];
+      if (id.indexOf('-') < 0 && id.indexOf('.') < 0) {
+        words.add(fields);
+      }
+    }
+    return words;
+  }
+
+  /**
+   * Splits a CoNLL-U word line into its tab-delimited fields, retaining empty fields.
+   *
+   * @param line The line to split.
+   * @return The fields in source order. Never {@code null}.
+   */
+  private String[] splitFields(String line) {

Review Comment:
   `StringUtil.split` is on main now. Please use it.



##########
opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/depparse/FeedforwardDependencyModel.java:
##########
@@ -0,0 +1,951 @@
+/*
+ * 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.tools.depparse;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReferenceArray;
+
+import opennlp.tools.commons.ThreadSafe;
+import opennlp.tools.util.InvalidFormatException;
+import opennlp.tools.util.StringUtil;
+
+/**
+ * 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, stored
+ * in a plain versioned binary format with no serialization framework involved. The
+ * architecture follows
+ * <a href="https://aclanthology.org/D14-1082/">Chen and Manning (2014)</a>.
+ *
+ * <p>The network runs with Java arrays and requires no native runtime. The same class
+ * scores configurations during training and decoding. Unknown words use a learned
+ * fallback row; words are matched case-insensitively after
+ * {@link #normalize(String) normalization}.</p>
+ *
+ * <p>Instances returned by {@link FeedforwardDependencyTrainer} are immutable and safe
+ * to share between threads. {@link FeedforwardDependencyTrainer#refine refine} updates
+ * an independent copy.</p>
+ *
+ * @see FeedforwardDependencyParser
+ * @see FeedforwardDependencyTrainer
+ * @since 3.0.0
+ */
+@ThreadSafe
+public class FeedforwardDependencyModel {
+
+  /** The format header written before every serialized model; it carries the format version. */
+  private static final String MAGIC = "ONLP-FFDP-1";
+
+  /** The vocabulary label used in load errors for the word map. */
+  private static final String WORD_VOCABULARY = "word vocabulary";
+
+  /** The vocabulary label used in load errors for the tag map. */
+  private static final String TAG_VOCABULARY = "tag vocabulary";
+
+  /** The vocabulary label used in load errors for the label map. */
+  private static final String LABEL_VOCABULARY = "label vocabulary";
+
+  /** Maximum combined entries across the word, tag, and label maps. */
+  private static final int MAX_VOCABULARY_ENTRIES = 2_000_000;
+
+  /** Maximum transitions accepted from a serialized model. */
+  private static final int MAX_TRANSITIONS = 100_000;
+
+  /** Maximum embedding width accepted from a serialized model. */
+  static final int MAX_EMBEDDING_SIZE = 4_096;
+
+  /** Maximum hidden-layer width accepted from a serialized model. */
+  static final int MAX_HIDDEN_SIZE = 65_536;
+
+  /** Maximum float values allocated while loading a serialized model. */
+  static final long MAX_MODEL_FLOAT_VALUES = 100_000_000L;
+
+  /** U+03A3, GREEK CAPITAL LETTER SIGMA, the one code point with a contextual lowering. */
+  private static final int GREEK_CAPITAL_SIGMA = 0x03A3;
+
+  /** U+03C2, GREEK SMALL LETTER FINAL SIGMA, the word-final lowering of the capital. */
+  private static final char GREEK_SMALL_FINAL_SIGMA = '\u03C2';
+
+  /** The vocabulary key of every word, tag, or label the model has no embedding row for. */
+  static final String UNKNOWN = "*UNK*";
+
+  /** The vocabulary key of a template position that does not exist in a configuration. */
+  static final String ABSENT = "*NULL*";
+
+  /** The vocabulary key of the artificial root node. */
+  static final String ROOT_SYMBOL = "*ROOT*";
+
+  /** The lazy scoring cache; {@code null} until {@link #enableScoringCache()}. */
+  private volatile ContributionCache cache;
+
+  private final Map<String, Integer> wordIds;
+  private final Map<String, Integer> tagIds;
+  private final Map<String, Integer> labelIds;
+  private final String[] transitions;
+
+  private final int embeddingSize;
+  private final float[][] embeddings;
+  private final float[][] hiddenWeights;
+  private final float[] hiddenBias;
+  private final float[][] outputWeights;
+  private final float[] outputBias;
+
+  /**
+   * Assembles a model from its vocabularies and weights, copying the maps so later
+   * changes by the caller do not reach the model.
+   *
+   * @param wordIds The word vocabulary, mapping each normalized word to its row.
+   * @param tagIds The tag vocabulary.
+   * @param labelIds The dependency label vocabulary.
+   * @param transitions The transition inventory, indexed by output row.
+   * @param embeddingSize The embedding dimensionality.
+   * @param embeddings The embedding rows for words, tags, and labels.
+   * @param hiddenWeights The hidden layer weights.
+   * @param hiddenBias The hidden layer bias.
+   * @param outputWeights The output layer weights.
+   * @param outputBias The output layer bias.
+   */
+  FeedforwardDependencyModel(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) {
+    this.wordIds = Map.copyOf(wordIds);
+    this.tagIds = Map.copyOf(tagIds);
+    this.labelIds = Map.copyOf(labelIds);
+    this.transitions = transitions;
+    this.embeddingSize = embeddingSize;
+    this.embeddings = embeddings;
+    this.hiddenWeights = hiddenWeights;
+    this.hiddenBias = hiddenBias;
+    this.outputWeights = outputWeights;
+    this.outputBias = outputBias;
+  }
+
+  /**
+   * Scores every transition for a configuration described by embedding row indices.
+   *
+   * @param features The embedding rows of the configuration, as produced by
+   *                 {@link #featureIds(String[])}. Must not be {@code null}.
+   * @return One unnormalized score per transition, indexed like
+   *         {@link #transitions()}. Never {@code null}.
+   * @throws IllegalArgumentException Thrown if {@code features} is {@code null}, does not
+   *         have the required length, or contains an invalid embedding index.
+   * @throws IllegalStateException If the model produces a non-finite transition score.
+   */
+  double[] score(int[] features) {
+    if (features == null) {
+      throw new IllegalArgumentException("features must not be null");
+    }
+    if (features.length != FeedforwardContext.FEATURE_COUNT) {
+      throw new IllegalArgumentException("features must contain "
+          + FeedforwardContext.FEATURE_COUNT + " embedding indices");
+    }
+    for (int i = 0; i < features.length; i++) {
+      if (features[i] < 0 || features[i] >= embeddings.length) {
+        throw new IllegalArgumentException(
+            "feature embedding out of range at index " + i + ": " + features[i]);
+      }
+    }
+    final int hidden = hiddenBias.length;
+    final double[] h = new double[hidden];
+    for (int j = 0; j < hidden; j++) {
+      h[j] = hiddenBias[j];
+    }
+    final ContributionCache cache = this.cache;
+    for (int f = 0; f < features.length; f++) {
+      final int row = features[f];
+      final double[] contribution = cache == null ? null : cache.contribution(this, f, row);
+      if (contribution != null) {
+        for (int j = 0; j < hidden; j++) {
+          h[j] += contribution[j];
+        }
+      } else {
+        final float[] embedding = embeddings[row];

Review Comment:
   Same hidden-layer computation as 286-297.



##########
opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/depparse/FeedforwardDependencyParser.java:
##########
@@ -0,0 +1,228 @@
+/*
+ * 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.tools.depparse;
+
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.List;
+
+import opennlp.tools.commons.ThreadSafe;
+
+/**
+ * The pure-Java neural {@link DependencyParser}: an arc-standard decoder over the
+ * {@link FeedforwardDependencyModel}, greedy by default and beamed when constructed
+ * with a beam size above one.
+ *
+ * <p>Beam decoding retains the highest scoring transition sequences by summed
+ * log-probability. Complete arc-standard derivations for a sentence have equal length,
+ * so their scores need no length normalization.</p>
+ *
+ * <p>Inference is ordinary array arithmetic with no native runtime involved, so this
+ * parser has the same input and output API as the classical parser while scoring with
+ * learned dense representations instead of sparse feature conjunctions.</p>
+ *
+ * <p>The parser holds an immutable model and no per-parse state, so one instance can be
+ * shared between threads.</p>
+ *
+ * @see FeedforwardDependencyTrainer
+ * @since 3.0.0
+ */
+@ThreadSafe
+public class FeedforwardDependencyParser implements DependencyParser {
+
+  /** The beam size at which decoding is greedy. */
+  private static final int GREEDY_BEAM_SIZE = 1;
+
+  private final FeedforwardDependencyModel model;
+  private final Transition[] transitions;
+  private final int beamSize;
+
+  /**
+   * Initializes a greedy {@link FeedforwardDependencyParser}.
+   *
+   * @param model The model to parse with. Must not be {@code null}.
+   * @throws IllegalArgumentException Thrown if {@code model} is {@code null} or an
+   *         outcome of the model does not decode to a transition.
+   */
+  public FeedforwardDependencyParser(FeedforwardDependencyModel model) {
+    this(model, GREEDY_BEAM_SIZE);
+  }
+
+  /**
+   * Initializes a {@link FeedforwardDependencyParser} with a beam.
+   *
+   * @param model The model to parse with. Must not be {@code null}.
+   * @param beamSize The number of transition sequences to retain. Must be
+   *                 greater than zero; {@code 1} decodes greedily.
+   * @throws IllegalArgumentException Thrown if {@code model} is {@code null},
+   *         {@code beamSize} is not positive, or an outcome of the model does not
+   *         decode to a transition.
+   */
+  public FeedforwardDependencyParser(FeedforwardDependencyModel model, int beamSize) {
+    if (model == null) {
+      throw new IllegalArgumentException("model must not be null");
+    }
+    if (beamSize < GREEDY_BEAM_SIZE) {
+      throw new IllegalArgumentException("beamSize must be positive: " + beamSize);
+    }
+    this.model = model;
+    this.beamSize = beamSize;
+    // Parser instances read immutable models. Training and refinement use uncached copies.

Review Comment:
   The constructor modifies a model documented as immutable and thread-safe, and attaches a cache of up to ~50 MiB with no way to release it. The parser should own the cache.



##########
opennlp-core/opennlp-formats/src/main/java/opennlp/tools/formats/conllu/ConlluDependencySampleStream.java:
##########
@@ -0,0 +1,270 @@
+/*
+ * 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.tools.formats.conllu;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.nio.charset.CodingErrorAction;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import opennlp.tools.depparse.DependencyGraph;
+import opennlp.tools.depparse.DependencySample;
+import opennlp.tools.util.InputStreamFactory;
+import opennlp.tools.util.InvalidFormatException;
+import opennlp.tools.util.ObjectStream;
+import opennlp.tools.util.StringUtil;
+
+/**
+ * Reads {@link DependencySample samples} directly from
+ * <a href="https://universaldependencies.org/format.html">CoNLL-U</a> content, mapping
+ * the {@code HEAD} and {@code DEPREL} columns of the basic dependency annotation.
+ *
+ * <p>This reader does not use {@link ConlluStream}, which merges multiword token ranges
+ * with their syntactic words for token and lemma samples. Dependency samples instead
+ * omit range lines and empty nodes while retaining the syntactic word rows. Sentences
+ * with incomplete or invalid basic dependencies are skipped and counted.</p>
+ *
+ * @since 3.0.0
+ */
+public class ConlluDependencySampleStream implements ObjectStream<DependencySample> {
+
+  private static final Logger logger =
+      LoggerFactory.getLogger(ConlluDependencySampleStream.class);
+
+  /** The number of tab-separated columns of a CoNLL-U word line. */
+  private static final int COLUMNS = 10;
+
+  /** The column holding the word index, a multiword token range, or an empty node id. */
+  private static final int ID = 0;
+
+  /** The column holding the word form. */
+  private static final int FORM = 1;
+
+  /** The column holding the universal part-of-speech tag. */
+  private static final int UPOS = 3;
+
+  /** The column holding the language-specific part-of-speech tag. */
+  private static final int XPOS = 4;
+
+  /** The column holding the one-based index of the head, {@code 0} for the root. */
+  private static final int HEAD = 6;
+
+  /** The column holding the relation label to the head. */
+  private static final int DEPREL = 7;
+
+  /** The CoNLL-U placeholder of a missing value. */
+  private static final String PLACEHOLDER = "_";
+
+  /** The byte order mark some editors prepend to UTF-8 content. */
+  private static final char BOM = '\ufeff';
+
+  /** The first character of a comment line. */
+  private static final char COMMENT = '#';
+
+  private final InputStreamFactory in;
+  private final int tagColumn;
+
+  private BufferedReader reader;
+  private boolean firstLine = true;
+  private int skipped;
+
+  /**
+   * Initializes the stream.
+   *
+   * @param in The CoNLL-U content. Must not be {@code null}.
+   * @param tagset The tagset whose part-of-speech column feeds the sample tags. Must
+   *               not be {@code null}.
+   * @throws IOException Thrown if opening the content fails.
+   * @throws IllegalArgumentException Thrown if any parameter is {@code null}.
+   */
+  public ConlluDependencySampleStream(InputStreamFactory in, ConlluTagset tagset)
+      throws IOException {
+    if (in == null) {
+      throw new IllegalArgumentException("in must not be null");
+    }
+    if (tagset == null) {
+      throw new IllegalArgumentException("tagset must not be null");
+    }
+    this.in = in;
+    this.tagColumn = tagset == ConlluTagset.U ? UPOS : XPOS;
+    this.reader = open();
+  }
+
+  /**
+   * {@inheritDoc}
+   * Sentences without a usable basic dependency annotation are skipped, and their count
+   * is logged once the content is exhausted.
+   */
+  @Override
+  public DependencySample read() throws IOException {
+    List<String[]> words;
+    while (!(words = nextSentence()).isEmpty()) {
+      final DependencySample sample = convert(words);
+      if (sample != null) {
+        return sample;
+      }
+      skipped++;
+    }
+    if (skipped > 0) {
+      logger.warn("Skipped {} sentence(s) without a complete basic dependency annotation.",
+          skipped);
+      skipped = 0;
+    }
+    return null;
+  }
+
+  /**
+   * Reads the syntactic word lines of the next sentence: comments, multiword token
+   * ranges, and empty nodes are dropped; an empty list means the end of the content.
+   *
+   * <p>Sentences are separated by any line {@link StringUtil#isBlank(CharSequence)}
+   * accepts, so a separator carrying a stray no-break space still separates rather than
+   * reaching the word line parser.</p>
+   *
+   * @return The word lines of the next sentence, or an empty list at the end of the
+   *         content. Never {@code null}.
+   * @throws IOException Thrown if reading fails.
+   * @throws InvalidFormatException Thrown if a word line does not have the expected column count.
+   */
+  private List<String[]> nextSentence() throws IOException {
+    final List<String[]> words = new ArrayList<>();
+    String line;
+    while ((line = reader.readLine()) != null) {
+      if (firstLine) {
+        firstLine = false;
+        if (!line.isEmpty() && line.charAt(0) == BOM) {
+          line = line.substring(1);
+        }
+      }
+      if (StringUtil.isBlank(line)) {
+        if (!words.isEmpty()) {
+          return words;
+        }
+        continue;
+      }
+      if (line.charAt(0) == COMMENT) {
+        continue;
+      }
+      final String[] fields = splitFields(line);
+      if (fields.length != COLUMNS) {
+        throw new InvalidFormatException("CoNLL-U word line has " + fields.length
+            + " columns, expected " + COLUMNS + ": " + line);
+      }
+      final String id = fields[ID];
+      if (id.indexOf('-') < 0 && id.indexOf('.') < 0) {
+        words.add(fields);
+      }
+    }
+    return words;
+  }
+
+  /**
+   * Splits a CoNLL-U word line into its tab-delimited fields, retaining empty fields.
+   *
+   * @param line The line to split.
+   * @return The fields in source order. Never {@code null}.
+   */
+  private String[] splitFields(String line) {
+    final List<String> fields = new ArrayList<>();
+    int fieldStart = 0;
+    for (int i = 0; i < line.length(); i++) {
+      if (line.charAt(i) == '\t') {
+        fields.add(line.substring(fieldStart, i));
+        fieldStart = i + 1;
+      }
+    }
+    fields.add(line.substring(fieldStart));
+    return fields.toArray(String[]::new);
+  }
+
+  /**
+   * Converts one sentence into a sample.
+   *
+   * @param words The word lines of the sentence.
+   * @return The converted sample, or {@code null} when the sentence's annotation is
+   *         unusable, for example an underscore head or relation or a graph that is not
+   *         a tree.
+   */
+  private DependencySample convert(List<String[]> words) {
+    final int n = words.size();
+    final String[] tokens = new String[n];
+    final String[] tags = new String[n];
+    final int[] heads = new int[n];
+    final String[] relations = new String[n];
+    for (int i = 0; i < n; i++) {
+      final String[] word = words.get(i);
+      if (!Integer.toString(i + 1).equals(word[ID])) {
+        return null;
+      }
+      tokens[i] = word[FORM];
+      tags[i] = word[tagColumn];

Review Comment:
   XPOS `_` is accepted as a tag, the same issue as `DEPREL=_`.



##########
opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/depparse/DependencyContextGenerator.java:
##########
@@ -0,0 +1,207 @@
+/*
+ * 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.tools.depparse;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import opennlp.tools.commons.ThreadSafe;
+
+/**
+ * Generates the classification features for one arc-standard configuration: words and
+ * tags of the topmost stack and frontmost buffer positions, their pairings, the partial
+ * structure built so far (tags and relations of the leftmost and rightmost dependents,
+ * valency counts), and a bucketed distance between stack top and buffer front.
+ *
+ * <p>Instances hold no state and are safe to share between threads.</p>
+ *
+ * @since 3.0.0
+ */
+@ThreadSafe
+class DependencyContextGenerator {
+
+  /** The feature value standing for the artificial root position. */
+  private static final String ROOT_VALUE = "*ROOT*";
+
+  /** The feature value standing for a position that does not exist. */
+  private static final String NONE_VALUE = "*NULL*";
+
+  /** Separates a word from the tag of the same position within one feature. */
+  private static final char WORD_TAG_SEPARATOR = '/';
+
+  /** Separates the parts of a feature combining several positions. */
+  private static final char POSITION_SEPARATOR = '|';
+
+  /** The number of features {@link #getContext(ArcStandardState, String[], String[])} emits. */
+  private static final int FEATURE_COUNT = 37;
+
+  /** Valency counts at or above this bound share one feature value. */
+  private static final int MAX_VALENCY = 3;
+
+  /** Distances at or above this bound share the {@link #LONG_DISTANCE} feature value. */
+  private static final int MAX_DISTANCE = 4;
+
+  /** The feature value standing for every distance of {@link #MAX_DISTANCE} or more. */
+  private static final String LONG_DISTANCE = "4+";
+
+  /**
+   * Generates the features of the current configuration.
+   *
+   * @param state The configuration to describe. Must not be {@code null}.
+   * @param tokens The input tokens. Must satisfy the token contract of
+   *               {@link DependencyParser#parse(String[], String[])} and match the state.
+   * @param tags The part-of-speech tags aligned with {@code tokens}. Must not be
+   *             {@code null} and must match the state.
+   * @return The feature strings. Never {@code null}.
+   * @throws IllegalArgumentException Thrown if a parameter is invalid or the arrays do
+   *         not match the state.
+   */
+  String[] getContext(ArcStandardState state, String[] tokens, String[] tags) {
+    if (state == null) {
+      throw new IllegalArgumentException("state must not be null");
+    }
+    ParserInput.check(tokens, tags);

Review Comment:
   Validates the full arrays again per configuration, O(n²). `DependencyParserME:129` already does this.



##########
opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/depparse/FeedforwardDependencyTrainer.java:
##########
@@ -0,0 +1,1175 @@
+/*
+ * 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.tools.depparse;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Random;
+import java.util.function.Function;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import opennlp.tools.util.ObjectStream;
+
+/**
+ * Trains the {@link FeedforwardDependencyModel} entirely in Java: 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
+ * <a href="https://aclanthology.org/D14-1082/">Chen and Manning (2014)</a>. Training and
+ * inference use Java arrays and require no external training framework.
+ *
+ * <p>Words below the frequency cutoff share a learned unknown embedding; absent
+ * template positions share a learned padding embedding. Non-projective samples have no
+ * arc-standard derivation and are skipped. Training is deterministic for a fixed
+ * {@link Settings#seed()}.</p>
+ *
+ * @since 3.0.0
+ */
+public final class FeedforwardDependencyTrainer {
+
+  private static final Logger logger =
+      LoggerFactory.getLogger(FeedforwardDependencyTrainer.class);
+
+  /** The AdaGrad denominator offset that keeps the first steps finite. */
+  private static final double ADAGRAD_EPSILON = 1e-6;
+
+  /** The derivative factor of the cube activation, {@code d/dx x^3 = 3x^2}. */
+  private static final double CUBE_DERIVATIVE_FACTOR = 3.0;
+
+  /** The numerator of the Glorot uniform bound, {@code sqrt(6 / (fanIn + fanOut))}. */
+  private static final double GLOROT_NUMERATOR = 6.0;
+
+  /** The half-width of the uniform range embeddings are drawn from. */
+  private static final double EMBEDDING_INIT_SCALE = 0.01;
+
+  /** The smallest probability the reported training loss takes the log of. */
+  private static final double LOSS_PROBABILITY_FLOOR = 1e-12;
+
+  /** The sentence loss reported when refinement made no update for a sentence. */
+  private static final double NO_UPDATE = -1.0;
+
+  /** Special-symbol rows present before any training vocabulary is added. */
+  private static final int MIN_VOCABULARY_ROWS = 8;
+
+  /** SHIFT and at least one RIGHT_ARC are required to parse a sentence. */
+  private static final int MIN_TRANSITIONS = 2;
+
+  /** Prevents construction of this utility class. */
+  private FeedforwardDependencyTrainer() {
+  }
+
+  /**
+   * The training hyperparameters.
+   *
+   * @param embeddingSize The embedding dimensionality. Must be positive.
+   * @param hiddenSize The hidden layer width. Must be positive.
+   * @param epochs The number of passes over the examples. Must be positive.
+   * @param batchSize The minibatch size. Must be positive.
+   * @param learningRate The AdaGrad step size. Must be positive.
+   * @param l2 The L2 penalty applied to the dense weights. Must not be negative.
+   * @param dropout The hidden dropout probability. Must be in {@code [0, 1)}.
+   * @param wordCutoff The minimum frequency for a word to get its own embedding. Must
+   *                   not be negative.
+   * @param seed The random seed making a run reproducible.
+   */
+  public record Settings(int embeddingSize, int hiddenSize, int epochs, int batchSize,
+      double learningRate, double l2, double dropout, int wordCutoff, long seed) {
+
+    /** The default embedding dimensionality. */
+    private static final int DEFAULT_EMBEDDING_SIZE = 50;
+
+    /** The default hidden layer width. */
+    private static final int DEFAULT_HIDDEN_SIZE = 200;
+
+    /** The default number of epochs. */
+    private static final int DEFAULT_EPOCHS = 10;
+
+    /** The default minibatch size. */
+    private static final int DEFAULT_BATCH_SIZE = 256;
+
+    /** The default AdaGrad step size. */
+    private static final double DEFAULT_LEARNING_RATE = 0.02;
+
+    /** The default L2 penalty. */
+    private static final double DEFAULT_L2 = 1e-8;
+
+    /** The default hidden dropout probability. */
+    private static final double DEFAULT_DROPOUT = 0.5;
+
+    /** The default minimum word frequency for an embedding row. */
+    private static final int DEFAULT_WORD_CUTOFF = 2;
+
+    /** The default random seed. */
+    private static final long DEFAULT_SEED = 17L;
+
+    /**
+     * Validates the hyperparameters.
+     *
+     * @throws IllegalArgumentException Thrown if a value is outside its documented
+     *         range.
+     */
+    public Settings {
+      if (embeddingSize <= 0 || hiddenSize <= 0 || epochs <= 0 || batchSize <= 0) {
+        throw new IllegalArgumentException("sizes, epochs and batch must be positive");
+      }
+      if (embeddingSize > FeedforwardDependencyModel.MAX_EMBEDDING_SIZE) {
+        throw new IllegalArgumentException("embeddingSize exceeds the model format limit: "
+            + embeddingSize);
+      }
+      if (hiddenSize > FeedforwardDependencyModel.MAX_HIDDEN_SIZE) {
+        throw new IllegalArgumentException("hiddenSize exceeds the model format limit: "
+            + hiddenSize);
+      }
+      final long minimumModelValues = modelFloatValues(MIN_VOCABULARY_ROWS,
+          MIN_TRANSITIONS, embeddingSize, hiddenSize);
+      if (minimumModelValues > FeedforwardDependencyModel.MAX_MODEL_FLOAT_VALUES) {
+        throw new IllegalArgumentException("embeddingSize and hiddenSize exceed the model "
+            + "format allocation limit");
+      }
+      if (!Double.isFinite(learningRate) || learningRate <= 0.0
+          || !Double.isFinite(l2) || l2 < 0.0) {
+        throw new IllegalArgumentException(
+            "learningRate must be finite and positive, l2 finite and not negative");
+      }
+      if (!(dropout >= 0.0 && dropout < 1.0)) {
+        throw new IllegalArgumentException("dropout must be in [0, 1): " + dropout);
+      }
+      if (wordCutoff < 0) {
+        throw new IllegalArgumentException("wordCutoff must not be negative");
+      }
+    }
+
+    /**
+     * @return The default hyperparameters. Never {@code null}.
+     */
+    public static Settings defaults() {
+      return new Settings(DEFAULT_EMBEDDING_SIZE, DEFAULT_HIDDEN_SIZE, DEFAULT_EPOCHS,
+          DEFAULT_BATCH_SIZE, DEFAULT_LEARNING_RATE, DEFAULT_L2, DEFAULT_DROPOUT,
+          DEFAULT_WORD_CUTOFF, DEFAULT_SEED);
+    }
+  }
+
+  /**
+   * Trains a model from dependency samples.
+   *
+   * @param samples The training samples. Must not be {@code null}.
+   * @param settings The hyperparameters. Must not be {@code null}.
+   * @return A trained {@link FeedforwardDependencyModel}. Never {@code null}.
+   * @throws IOException Thrown if reading the samples fails.
+   * @throws IllegalArgumentException Thrown if a parameter is {@code null} or no
+   *         trainable example can be derived from the samples.
+   */
+  public static FeedforwardDependencyModel train(ObjectStream<DependencySample> samples,
+      Settings settings) throws IOException {
+    return train(samples, settings, null);
+  }
+
+  /**
+   * Trains a model from dependency samples, seeding word embeddings from a pretrained
+   * source.
+   *
+   * <p>The provider is consulted once per vocabulary word during initialization; words
+   * it returns {@code null} for keep their random initialization, and all embeddings
+   * remain trainable afterwards. The pretrained source is a training-time ingredient
+   * only: the learned embeddings ship inside the model, so parsing carries no
+   * dependency on the source.</p>
+   *
+   * @param samples The training samples. Must not be {@code null}.
+   * @param settings The hyperparameters. Must not be {@code null}.
+   * @param pretrained Maps a normalized word to its pretrained vector of exactly
+   *                   {@link Settings#embeddingSize()} dimensions, or {@code null} for
+   *                   unknown words. May be {@code null} to disable seeding.
+   * @return A trained {@link FeedforwardDependencyModel}. Never {@code null}.
+   * @throws IOException Thrown if reading the samples fails.
+   * @throws IllegalArgumentException Thrown if {@code samples} or {@code settings} is
+   *         {@code null}, no trainable example can be derived, or a pretrained vector
+   *         has the wrong dimensionality.
+   */
+  public static FeedforwardDependencyModel train(ObjectStream<DependencySample> samples,
+      Settings settings, Function<String, float[]> pretrained)
+      throws IOException {
+    if (samples == null) {
+      throw new IllegalArgumentException("samples must not be null");
+    }
+    if (settings == null) {
+      throw new IllegalArgumentException("settings must not be null");
+    }
+    final List<DependencySample> corpus = readAll(samples);
+    final FeedforwardDependencyModel model = initialize(corpus, settings);
+    if (pretrained != null) {
+      seed(model, pretrained, settings);
+    }
+    final List<int[]> featureList = new ArrayList<>();
+    final List<Integer> goldList = new ArrayList<>();
+    collectExamples(corpus, model, featureList, goldList);
+    if (featureList.isEmpty()) {
+      throw new IllegalArgumentException("no trainable examples in the samples");
+    }
+    optimize(model, featureList, goldList, settings);
+    return model;
+  }
+
+  /**
+   * Refines a locally trained model with beam search and the early-update method of
+   * <a href="https://aclanthology.org/P04-1015/">Collins and Roark (2004)</a>. The loss
+   * is conditional likelihood over candidate paths scored by summed log-probabilities.
+   *
+   * <p>Refinement updates a copy with per-sentence AdaGrad steps and no dropout.
+   * {@link Settings#epochs()} sets the number of refinement passes. Use the same beam
+   * size for parsing the result.</p>
+   *
+   * <p>The transition inventory comes from {@code model} and is not extended, because
+   * its size is the width of the trained output layer. A refinement corpus using a
+   * relation label the original training set lacked is therefore rejected rather than
+   * silently ignored.</p>
+   *
+   * @param model The locally trained model to refine. Left untouched. Must not be
+   *              {@code null}.
+   * @param samples The training samples. Must not be {@code null}.
+   * @param settings The hyperparameters; {@code epochs}, {@code learningRate},
+   *                 {@code l2}, and {@code seed} apply. Must not be {@code null}.
+   * @param beamSize The beam width to track the gold derivation in. Must be at least 2.
+   * @return A new refined model, distinct from {@code model}. Never {@code null}.
+   * @throws IOException Thrown if reading the samples fails.
+   * @throws IllegalArgumentException Thrown if a parameter is {@code null},
+   *         {@code beamSize} is below 2, no trainable sample can be derived, or a sample
+   *         requires a transition {@code model} does not know.
+   */
+  public static FeedforwardDependencyModel refine(FeedforwardDependencyModel model,
+      ObjectStream<DependencySample> samples, Settings settings, int beamSize)
+      throws IOException {
+    if (model == null) {
+      throw new IllegalArgumentException("model must not be null");
+    }
+    if (samples == null) {
+      throw new IllegalArgumentException("samples must not be null");
+    }
+    if (settings == null) {
+      throw new IllegalArgumentException("settings must not be null");
+    }
+    if (beamSize < 2) {
+      throw new IllegalArgumentException("beamSize must be at least 2: " + beamSize);
+    }
+    final List<DependencySample> corpus = readAll(samples);
+    final String[] outcomes = model.transitions();
+    final Map<String, Integer> transitionIds = new HashMap<>();
+    final Transition[] transitions = new Transition[outcomes.length];
+    for (int i = 0; i < transitions.length; i++) {
+      transitionIds.put(outcomes[i], i);
+      transitions[i] = Transition.decode(outcomes[i]);
+    }
+
+    final List<DependencySample> trainable = new ArrayList<>();
+    final List<int[]> oracles = new ArrayList<>();
+    for (final DependencySample s : corpus) {
+      if (!ArcStandardOracle.isProjective(s.getGraph())) {
+        continue;
+      }
+      final List<Transition> oracle = ArcStandardOracle.transitions(s.getGraph());
+      final int[] encoded = new int[oracle.size()];
+      for (int i = 0; i < encoded.length; i++) {
+        final String outcome = oracle.get(i).encode();
+        final Integer id = transitionIds.get(outcome);
+        if (id == null) {
+          // The outcome space was fixed by the original training set, so a relation
+          // label it never saw has no output unit to push probability onto.
+          throw new IllegalArgumentException(
+              "unknown transition in the refinement samples: " + outcome);
+        }
+        encoded[i] = id;
+      }
+      trainable.add(s);
+      oracles.add(encoded);
+    }
+    if (trainable.isEmpty()) {
+      throw new IllegalArgumentException("no trainable samples for refinement");
+    }
+
+    final FeedforwardDependencyModel refined = model.copy();
+    final GlobalOptimizer optimizer = new GlobalOptimizer(refined, settings);
+    final Random random = new Random(settings.seed());
+    final int[] order = new int[trainable.size()];
+    for (int i = 0; i < order.length; i++) {
+      order[i] = i;
+    }
+    for (int epoch = 1; epoch <= settings.epochs(); epoch++) {
+      final long epochStart = System.currentTimeMillis();
+      shuffle(order, random);
+      double loss = 0.0;
+      int updates = 0;
+      for (final int index : order) {
+        final double sentenceLoss = optimizer.refineSentence(trainable.get(index),
+            oracles.get(index), transitions, beamSize);
+        if (sentenceLoss >= 0.0) {
+          loss += sentenceLoss;
+          updates++;
+        }
+      }
+      checkFinite(refined);
+      logger.info("refine epoch {}: loss {} over {} updates in {} ms", epoch,
+          loss / Math.max(updates, 1), updates, System.currentTimeMillis() - epochStart);
+    }
+    return refined;
+  }
+
+  /** One candidate path in the refinement beam: the parent link forms the history. */
+  private static final class BeamNode {
+    private final BeamNode parent;
+    private final int[] features;
+    private final int transition;
+    private final double score;
+    private final boolean gold;
+    private ArcStandardState state;
+
+    /**
+     * Extends {@code parent} by one transition; the start node passes {@code null}.
+     *
+     * @param parent The node this one extends, or {@code null} for the start node.
+     * @param features The embedding rows the transition was scored on.
+     * @param transition The transition index taken from {@code parent}.
+     * @param score The summed log-probability of the path.
+     * @param gold Whether the path is the gold derivation so far.
+     */
+    private BeamNode(BeamNode parent, int[] features, int transition, double score,
+        boolean gold) {
+      this.parent = parent;
+      this.features = features;
+      this.transition = transition;
+      this.score = score;
+      this.gold = gold;
+    }
+  }
+
+  /** The forward, backward, and AdaGrad state for global refinement. */
+  private static final class GlobalOptimizer {
+    private final FeedforwardDependencyModel model;
+    private final Settings settings;
+    private final int embeddingSize;
+    private final int hiddenSize;
+    private final int outputSize;
+    private final int inputSize;
+
+    private final double[][] embeddingAccumulator;
+    private final double[][] hiddenAccumulator;
+    private final double[] hiddenBiasAccumulator;
+    private final double[][] outputAccumulator;
+    private final double[] outputBiasAccumulator;
+
+    private final double[][] hiddenGradient;
+    private final double[] hiddenBiasGradient;
+    private final double[][] outputGradient;
+    private final double[] outputBiasGradient;
+    private final Map<Integer, double[]> embeddingGradients = new HashMap<>();
+
+    private final double[] x;
+    private final double[] pre;
+    private final double[] hidden;
+    private final double[] probabilities;
+    private final double[] hiddenDelta;
+    private final double[] inputDelta;
+
+    /**
+     * Sizes the accumulators and scratch buffers for one refinement run.
+     *
+     * @param model The model copy the run updates in place.
+     * @param settings The hyperparameters; {@code learningRate} and {@code l2} apply.
+     */
+    private GlobalOptimizer(FeedforwardDependencyModel model, Settings settings) {
+      this.model = model;
+      this.settings = settings;
+      this.embeddingSize = model.embeddings()[0].length;
+      this.hiddenSize = model.hiddenBias().length;
+      this.outputSize = model.outputBias().length;
+      this.inputSize = FeedforwardContext.FEATURE_COUNT * embeddingSize;
+      this.embeddingAccumulator =
+          new double[model.embeddings().length][embeddingSize];
+      this.hiddenAccumulator = new double[hiddenSize][inputSize];
+      this.hiddenBiasAccumulator = new double[hiddenSize];
+      this.outputAccumulator = new double[outputSize][hiddenSize];
+      this.outputBiasAccumulator = new double[outputSize];
+      this.hiddenGradient = new double[hiddenSize][inputSize];
+      this.hiddenBiasGradient = new double[hiddenSize];
+      this.outputGradient = new double[outputSize][hiddenSize];
+      this.outputBiasGradient = new double[outputSize];
+      this.x = new double[inputSize];
+      this.pre = new double[hiddenSize];
+      this.hidden = new double[hiddenSize];
+      this.probabilities = new double[outputSize];
+      this.hiddenDelta = new double[hiddenSize];
+      this.inputDelta = new double[inputSize];
+    }
+
+    /**
+     * Decodes one sentence with the beam, updating on the early-update point or the
+     * final beam.
+     *
+     * @param sample The sentence.
+     * @param oracle The gold transition indexes.
+     * @param transitions The decoded transition inventory.
+     * @param beamSize The beam width.
+     * @return The sentence loss, or {@link FeedforwardDependencyTrainer#NO_UPDATE} when the
+     *         sentence produced no update.
+     */
+    private double refineSentence(DependencySample sample, int[] oracle,
+        Transition[] transitions, int beamSize) {
+      final String[] tokens = sample.getTokens();
+      final String[] tags = sample.getTags();
+      final BeamNode root = new BeamNode(null, null, -1, 0.0, true);
+      root.state = new ArcStandardState(tokens.length);
+      List<BeamNode> beam = List.of(root);
+
+      for (int step = 0; step < oracle.length; step++) {
+        final List<BeamNode> expansions = new ArrayList<>();
+        BeamNode goldChild = null;
+        for (final BeamNode node : beam) {
+          final int[] features =
+              model.featureIds(FeedforwardContext.extract(node.state, tokens, tags));
+          forward(features);
+          logSoftmaxInPlace(probabilities);
+          for (int i = 0; i < outputSize; i++) {
+            if (node.state.canApply(transitions[i])) {
+              final boolean goldNext = node.gold && i == oracle[step];
+              final BeamNode child = new BeamNode(node, features, i,
+                  node.score + probabilities[i], goldNext);
+              expansions.add(child);
+              if (goldNext) {
+                goldChild = child;
+              }
+            }
+          }
+        }
+        expansions.sort((a, b) -> Double.compare(b.score, a.score));
+        final List<BeamNode> survivors =
+            new ArrayList<>(expansions.subList(0, Math.min(beamSize, expansions.size())));
+        boolean goldRetained = false;
+        for (final BeamNode survivor : survivors) {
+          if (survivor.gold) {
+            goldRetained = true;
+            break;
+          }
+        }
+        if (!goldRetained) {
+          if (goldChild == null) {
+            // The gold transition was not applicable in the gold configuration, so
+            // this sentence yields no update.
+            return NO_UPDATE;
+          }
+          survivors.add(goldChild);
+          return updateFromCandidates(survivors);
+        }
+        if (step == oracle.length - 1) {
+          return updateFromCandidates(survivors);
+        }
+        for (final BeamNode survivor : survivors) {
+          survivor.state = survivor.parent.state.copy();
+          survivor.state.apply(transitions[survivor.transition]);
+        }
+        beam = survivors;
+      }
+      return NO_UPDATE;
+    }
+
+    /**
+     * Applies the conditional-likelihood update over the candidate paths.
+     *
+     * @param candidates The surviving paths plus, on early update, the gold path.
+     * @return The negative log-probability of the gold path under the candidates.
+     */
+    private double updateFromCandidates(List<BeamNode> candidates) {
+      double max = Double.NEGATIVE_INFINITY;
+      double goldScore = Double.NEGATIVE_INFINITY;
+      for (final BeamNode candidate : candidates) {
+        max = Math.max(max, candidate.score);
+        if (candidate.gold) {
+          goldScore = candidate.score;
+        }
+      }
+      double normalizer = 0.0;
+      for (final BeamNode candidate : candidates) {
+        normalizer += Math.exp(candidate.score - max);
+      }
+      final double logNormalizer = max + Math.log(normalizer);
+
+      zero(hiddenGradient);
+      Arrays.fill(hiddenBiasGradient, 0.0);
+      zero(outputGradient);
+      Arrays.fill(outputBiasGradient, 0.0);
+      embeddingGradients.clear();
+      for (final BeamNode candidate : candidates) {
+        final double weight = Math.exp(candidate.score - logNormalizer)
+            - (candidate.gold ? 1.0 : 0.0);
+        if (weight == 0.0) {
+          continue;
+        }
+        for (BeamNode node = candidate; node.parent != null; node = node.parent) {
+          backward(node.features, node.transition, weight);
+        }
+      }
+      update(model.hiddenWeights(), hiddenGradient, hiddenAccumulator, 1, settings);
+      updateVector(model.hiddenBias(), hiddenBiasGradient, hiddenBiasAccumulator, 1,
+          settings);
+      update(model.outputWeights(), outputGradient, outputAccumulator, 1, settings);
+      updateVector(model.outputBias(), outputBiasGradient, outputBiasAccumulator, 1,
+          settings);
+      for (final Map.Entry<Integer, double[]> entry : embeddingGradients.entrySet()) {
+        final float[] embeddingRow = model.embeddings()[entry.getKey()];
+        final double[] accumulatorRow = embeddingAccumulator[entry.getKey()];
+        final double[] gradientRow = entry.getValue();
+        for (int d = 0; d < embeddingSize; d++) {
+          final double gradient = gradientRow[d];
+          accumulatorRow[d] += gradient * gradient;
+          embeddingRow[d] -= settings.learningRate() * gradient
+              / (Math.sqrt(accumulatorRow[d]) + ADAGRAD_EPSILON);
+        }
+      }
+      return logNormalizer - goldScore;
+    }
+
+    /**
+     * Computes hidden activations and raw output scores for one feature vector into
+     * the scratch buffers.
+     *
+     * @param features The embedding rows of the configuration.
+     */
+    private void forward(int[] features) {
+      final float[][] embeddings = model.embeddings();
+      for (int f = 0; f < features.length; f++) {
+        final float[] embedding = embeddings[features[f]];
+        final int offset = f * embeddingSize;
+        for (int d = 0; d < embeddingSize; d++) {
+          x[offset + d] = embedding[d];
+        }
+      }
+      final float[][] hiddenWeights = model.hiddenWeights();
+      final float[] hiddenBias = model.hiddenBias();
+      for (int j = 0; j < hiddenSize; j++) {
+        final float[] weightRow = hiddenWeights[j];
+        double sum = hiddenBias[j];
+        for (int k = 0; k < inputSize; k++) {
+          sum += weightRow[k] * x[k];
+        }
+        pre[j] = sum;
+        hidden[j] = sum * sum * sum;
+      }
+      final float[][] outputWeights = model.outputWeights();
+      final float[] outputBias = model.outputBias();
+      for (int o = 0; o < outputSize; o++) {
+        final float[] weightRow = outputWeights[o];
+        double sum = outputBias[o];
+        for (int j = 0; j < hiddenSize; j++) {
+          sum += weightRow[j] * hidden[j];
+        }
+        probabilities[o] = sum;
+      }
+    }
+
+    /**
+     * Accumulates gradients for one decoded step: the weighted difference between the
+     * step's softmax and its chosen transition.
+     *
+     * @param features The step's input features.
+     * @param chosen The transition the path took at this step.
+     * @param weight The path's weight in the candidate distribution.
+     */
+    private void backward(int[] features, int chosen, double weight) {
+      forward(features);
+      double max = Double.NEGATIVE_INFINITY;
+      for (int o = 0; o < outputSize; o++) {
+        max = Math.max(max, probabilities[o]);
+      }
+      double normalizer = 0.0;
+      for (int o = 0; o < outputSize; o++) {
+        probabilities[o] = Math.exp(probabilities[o] - max);
+        normalizer += probabilities[o];
+      }
+      Arrays.fill(hiddenDelta, 0.0);
+      Arrays.fill(inputDelta, 0.0);
+      final float[][] outputWeights = model.outputWeights();
+      for (int o = 0; o < outputSize; o++) {
+        // dL/dlogit for a path's step under the conditional likelihood: the path weight
+        // times how the step's log-probability responds to this logit
+        final double delta =
+            weight * ((o == chosen ? 1.0 : 0.0) - probabilities[o] / normalizer);
+        outputBiasGradient[o] += delta;
+        final double[] gradientRow = outputGradient[o];
+        final float[] weightRow = outputWeights[o];
+        for (int j = 0; j < hiddenSize; j++) {
+          gradientRow[j] += delta * hidden[j];
+          hiddenDelta[j] += delta * weightRow[j];
+        }
+      }
+      final float[][] hiddenWeights = model.hiddenWeights();
+      for (int j = 0; j < hiddenSize; j++) {
+        final double preDelta = hiddenDelta[j] * CUBE_DERIVATIVE_FACTOR * pre[j] * pre[j];
+        hiddenBiasGradient[j] += preDelta;
+        final double[] gradientRow = hiddenGradient[j];
+        final float[] weightRow = hiddenWeights[j];
+        for (int k = 0; k < inputSize; k++) {
+          gradientRow[k] += preDelta * x[k];
+          inputDelta[k] += preDelta * weightRow[k];
+        }
+      }
+      for (int f = 0; f < features.length; f++) {
+        final double[] embeddingGradient = embeddingGradients
+            .computeIfAbsent(features[f], key -> new double[embeddingSize]);
+        final int offset = f * embeddingSize;
+        for (int d = 0; d < embeddingSize; d++) {
+          embeddingGradient[d] += inputDelta[offset + d];
+        }
+      }
+    }
+
+    /**
+     * Turns raw scores into log-probabilities in place.
+     *
+     * @param scores The raw scores, overwritten with their log-softmax.
+     */
+    private void logSoftmaxInPlace(double[] scores) {
+      double max = Double.NEGATIVE_INFINITY;
+      for (final double score : scores) {
+        max = Math.max(max, score);
+      }
+      double sum = 0.0;
+      for (final double score : scores) {
+        sum += Math.exp(score - max);
+      }
+      final double logSum = Math.log(sum);
+      for (int i = 0; i < scores.length; i++) {
+        scores[i] = (scores[i] - max) - logSum;
+      }
+    }
+  }
+
+  /**
+   * Reads a sample stream into memory; both trainers pass over the corpus repeatedly.
+   *
+   * @param samples The stream to drain.
+   * @return All samples in stream order. Never {@code null}.
+   * @throws IOException Thrown if reading the samples fails.
+   */
+  private static List<DependencySample> readAll(ObjectStream<DependencySample> samples)
+      throws IOException {
+    final List<DependencySample> corpus = new ArrayList<>();
+    DependencySample sample;
+    while ((sample = samples.read()) != null) {
+      corpus.add(sample);
+    }
+    return corpus;
+  }
+
+  /**
+   * Overwrites the random word rows with pretrained vectors where available.
+   *
+   * @param model The freshly initialized model whose word rows are seeded.
+   * @param pretrained The pretrained vector source, returning {@code null} for a word it
+   *                   does not cover.
+   * @param settings The hyperparameters, which fix the expected vector width.
+   * @throws IllegalArgumentException Thrown if a pretrained vector has a different width
+   *         than the embedding size or contains a non-finite value.
+   */
+  private static void seed(FeedforwardDependencyModel model,
+      Function<String, float[]> pretrained, Settings settings) {
+    int seeded = 0;
+    for (final Map.Entry<String, Integer> entry : model.wordIds().entrySet()) {
+      if (FeedforwardDependencyModel.isSpecialSymbol(entry.getKey())) {
+        // The special unknown, padding, and root symbols have no pretrained
+        // counterpart, so they keep their random initialization.
+        continue;
+      }
+      final float[] vector = pretrained.apply(entry.getKey());
+      if (vector == null) {
+        continue;
+      }
+      if (vector.length != settings.embeddingSize()) {
+        throw new IllegalArgumentException("pretrained vector for '" + entry.getKey()
+            + "' has " + vector.length + " dimensions, expected "
+            + settings.embeddingSize());
+      }
+      for (final float value : vector) {
+        if (!Float.isFinite(value)) {
+          throw new IllegalArgumentException(
+              "pretrained vector for '" + entry.getKey() + "' contains a non-finite value");
+        }
+      }
+      System.arraycopy(vector, 0, model.embeddings()[entry.getValue()], 0, vector.length);
+      seeded++;
+    }
+    logger.info("seeded {} of {} word embeddings from the pretrained source", seeded,
+        model.wordIds().size());
+  }
+
+  /**
+   * Builds the vocabularies and randomly initialized weights. A word, tag, or label in
+   * the training data that spells a reserved symbol shares the reserved row, as an
+   * unknown symbol does, so the reserved rows are never displaced.
+   *
+   * @param corpus The training samples.
+   * @param settings The hyperparameters.
+   * @return The untrained model. Never {@code null}.
+   * @throws IllegalArgumentException Thrown if the vocabularies and settings would
+   *         produce more model values than the model format can store.
+   */
+  private static FeedforwardDependencyModel initialize(List<DependencySample> corpus,
+      Settings settings) {
+    final Map<String, Integer> wordCounts = new HashMap<>();
+    final Map<String, Integer> tagIds = new HashMap<>();
+    final Map<String, Integer> labelIds = new HashMap<>();
+    final Map<String, Integer> transitionIds = new HashMap<>();
+    for (final DependencySample s : corpus) {
+      if (!ArcStandardOracle.isProjective(s.getGraph())) {
+        continue;
+      }
+      final List<Transition> oracle = ArcStandardOracle.transitions(s.getGraph());
+      for (final String token : s.getTokens()) {
+        wordCounts.merge(FeedforwardDependencyModel.normalize(token), 1, Integer::sum);
+      }
+      for (final String tag : s.getTags()) {
+        tagIds.putIfAbsent(tag, 0);
+      }
+      final DependencyGraph graph = s.getGraph();
+      for (int i = 0; i < graph.size(); i++) {
+        labelIds.putIfAbsent(graph.relationOf(i), 0);
+      }
+      for (final Transition transition : oracle) {
+        transitionIds.putIfAbsent(transition.encode(), 0);
+      }
+    }
+
+    int row = 0;
+    final Map<String, Integer> wordIds = new HashMap<>();
+    row = addSpecialSymbols(wordIds, row, FeedforwardDependencyModel.UNKNOWN,
+        FeedforwardDependencyModel.ABSENT, FeedforwardDependencyModel.ROOT_SYMBOL);
+    for (final Map.Entry<String, Integer> entry : wordCounts.entrySet()) {
+      if (entry.getValue() >= settings.wordCutoff() && !wordIds.containsKey(entry.getKey())) {
+        wordIds.put(entry.getKey(), row++);
+      }
+    }
+    final Map<String, Integer> tags = new HashMap<>();
+    row = addSpecialSymbols(tags, row, FeedforwardDependencyModel.UNKNOWN,
+        FeedforwardDependencyModel.ABSENT, FeedforwardDependencyModel.ROOT_SYMBOL);
+    for (final String tag : tagIds.keySet()) {
+      if (!tags.containsKey(tag)) {
+        tags.put(tag, row++);
+      }
+    }
+    final Map<String, Integer> labels = new HashMap<>();
+    row = addSpecialSymbols(labels, row, FeedforwardDependencyModel.UNKNOWN,
+        FeedforwardDependencyModel.ABSENT);
+    for (final String label : labelIds.keySet()) {
+      if (!labels.containsKey(label)) {
+        labels.put(label, row++);
+      }
+    }
+
+    final String[] transitions = transitionIds.keySet().toArray(String[]::new);
+    Arrays.sort(transitions);
+
+    final long modelValues = modelFloatValues(row, transitions.length,
+        settings.embeddingSize(), settings.hiddenSize());
+    if (modelValues > FeedforwardDependencyModel.MAX_MODEL_FLOAT_VALUES) {
+      throw new IllegalArgumentException("training vocabulary and settings require "
+          + modelValues + " model values, limit is "
+          + FeedforwardDependencyModel.MAX_MODEL_FLOAT_VALUES);
+    }
+
+    final Random random = new Random(settings.seed());
+    final int inputSize = FeedforwardContext.FEATURE_COUNT * settings.embeddingSize();
+    final float[][] embeddings = uniform(random, row, settings.embeddingSize(),
+        EMBEDDING_INIT_SCALE);
+    final float[][] hiddenWeights = uniform(random, settings.hiddenSize(), inputSize,
+        Math.sqrt(GLOROT_NUMERATOR / (inputSize + settings.hiddenSize())));
+    final float[][] outputWeights = uniform(random, transitions.length,
+        settings.hiddenSize(),
+        Math.sqrt(GLOROT_NUMERATOR / (settings.hiddenSize() + transitions.length)));
+    return new FeedforwardDependencyModel(wordIds, tags, labels, transitions,
+        settings.embeddingSize(), embeddings, hiddenWeights,
+        new float[settings.hiddenSize()], outputWeights, new float[transitions.length]);
+  }
+
+  /**
+   * Assigns the next embedding rows to the special symbols of one vocabulary.
+   *
+   * @param ids The vocabulary to fill.
+   * @param row The next free embedding row.
+   * @param symbols The special symbols, in the order they take their rows.
+   * @return The next free embedding row after the symbols.
+   */
+  private static int addSpecialSymbols(Map<String, Integer> ids, int row, String... symbols) {
+    int next = row;
+    for (final String symbol : symbols) {
+      ids.put(symbol, next);
+      next++;
+    }
+    return next;
+  }
+
+  /**
+   * @param vocabularyRows The combined word, tag, and label row count.
+   * @param transitionCount The output layer width.
+   * @param embeddingSize The embedding dimensionality.
+   * @param hiddenSize The hidden layer width.
+   * @return The number of float values a model of that shape stores.
+   */
+  private static long modelFloatValues(int vocabularyRows, int transitionCount,
+      int embeddingSize, int hiddenSize) {
+    final long inputSize = (long) FeedforwardContext.FEATURE_COUNT * embeddingSize;
+    return (long) vocabularyRows * embeddingSize
+        + (long) hiddenSize * inputSize
+        + hiddenSize
+        + (long) transitionCount * hiddenSize
+        + transitionCount;
+  }
+
+  /**
+   * Replays the oracle over every projective sample, emitting one example per step.
+   *
+   * @param corpus The training samples.
+   * @param model The initialized model whose vocabularies map the features.
+   * @param featureList Receives the embedding rows of each configuration.
+   * @param goldList Receives the gold transition index of each configuration.
+   */
+  private static void collectExamples(List<DependencySample> corpus,
+      FeedforwardDependencyModel model, List<int[]> featureList, List<Integer> goldList) {
+    final Map<String, Integer> transitionIds = new HashMap<>();
+    final String[] transitions = model.transitions();
+    for (int i = 0; i < transitions.length; i++) {
+      transitionIds.put(transitions[i], i);
+    }
+    int skipped = 0;
+    for (final DependencySample sample : corpus) {
+      if (!ArcStandardOracle.isProjective(sample.getGraph())) {
+        skipped++;
+        continue;
+      }
+      final List<Transition> oracle = ArcStandardOracle.transitions(sample.getGraph());
+      final ArcStandardState state = new ArcStandardState(sample.getGraph().size());
+      final String[] tokens = sample.getTokens();
+      final String[] tags = sample.getTags();
+      for (final Transition transition : oracle) {
+        featureList.add(model.featureIds(FeedforwardContext.extract(state, tokens, tags)));
+        goldList.add(transitionIds.get(transition.encode()));
+        state.apply(transition);
+      }
+    }
+    if (skipped > 0) {
+      logger.warn("Skipped {} non-projective sample(s) without an arc-standard derivation.",
+          skipped);
+    }
+  }
+
+  /**
+   * Minibatch AdaGrad over softmax cross-entropy with cube activation and dropout,
+   * updating {@code model} in place.
+   *
+   * @param model The initialized model.
+   * @param featureList The embedding rows of every example.
+   * @param goldList The gold transition index of every example.
+   * @param settings The hyperparameters.
+   * @throws IllegalStateException Thrown if an epoch produces a non-finite parameter.
+   */
+  private static void optimize(FeedforwardDependencyModel model, List<int[]> featureList,
+      List<Integer> goldList, Settings settings) {
+    final int exampleCount = featureList.size();
+    final int[][] features = featureList.toArray(new int[0][]);
+    final int[] gold = new int[exampleCount];
+    for (int i = 0; i < exampleCount; i++) {
+      gold[i] = goldList.get(i);
+    }
+
+    final float[][] embeddings = model.embeddings();
+    final float[][] hiddenWeights = model.hiddenWeights();
+    final float[] hiddenBias = model.hiddenBias();
+    final float[][] outputWeights = model.outputWeights();
+    final float[] outputBias = model.outputBias();
+    final int embeddingSize = settings.embeddingSize();
+    final int hiddenSize = settings.hiddenSize();
+    final int outputSize = outputBias.length;
+    final int inputSize = features[0].length * embeddingSize;
+
+    final double[][] embeddingAccumulator =
+        new double[embeddings.length][embeddingSize];
+    final double[][] hiddenAccumulator = new double[hiddenSize][inputSize];
+    final double[] hiddenBiasAccumulator = new double[hiddenSize];
+    final double[][] outputAccumulator = new double[outputSize][hiddenSize];
+    final double[] outputBiasAccumulator = new double[outputSize];
+
+    final double[][] hiddenGradient = new double[hiddenSize][inputSize];
+    final double[] hiddenBiasGradient = new double[hiddenSize];
+    final double[][] outputGradient = new double[outputSize][hiddenSize];
+    final double[] outputBiasGradient = new double[outputSize];
+    final Map<Integer, double[]> embeddingGradients = new HashMap<>();
+
+    final Random random = new Random(settings.seed());
+    final int[] order = new int[exampleCount];
+    for (int i = 0; i < exampleCount; i++) {
+      order[i] = i;
+    }
+
+    final double keep = 1.0 - settings.dropout();
+    final double[] x = new double[inputSize];
+    final double[] pre = new double[hiddenSize];
+    final double[] hidden = new double[hiddenSize];
+    final boolean[] mask = new boolean[hiddenSize];
+    final double[] probabilities = new double[outputSize];
+    final double[] hiddenDelta = new double[hiddenSize];
+    final double[] inputDelta = new double[inputSize];
+
+    for (int epoch = 1; epoch <= settings.epochs(); epoch++) {
+      final long epochStart = System.currentTimeMillis();
+      shuffle(order, random);
+      double loss = 0.0;
+      for (int batchStart = 0; batchStart < exampleCount;
+          batchStart += settings.batchSize()) {
+        final int batchEnd = Math.min(batchStart + settings.batchSize(), exampleCount);
+        final int batch = batchEnd - batchStart;
+        zero(hiddenGradient);
+        Arrays.fill(hiddenBiasGradient, 0.0);
+        zero(outputGradient);
+        Arrays.fill(outputBiasGradient, 0.0);
+        embeddingGradients.clear();
+
+        for (int b = batchStart; b < batchEnd; b++) {
+          final int[] feats = features[order[b]];
+          final int goldTransition = gold[order[b]];
+          for (int f = 0; f < feats.length; f++) {

Review Comment:
   Forward/backward duplicates `GlobalOptimizer.forward/backward` (554-640).



##########
opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/depparse/Transition.java:
##########
@@ -0,0 +1,132 @@
+/*
+ * 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.tools.depparse;
+
+import opennlp.tools.util.StringUtil;
+
+/**
+ * One action of the arc-standard transition system: shift the next buffer token onto the
+ * stack, or attach one of the two topmost stack tokens to the other under a relation label.
+ *
+ * <p>{@link #encode()} renders a transition as a classification outcome and
+ * {@link #decode(String)} restores it.</p>
+ *
+ * @param type The kind of action. Must not be {@code null}.
+ * @param label The relation label for arc actions, {@code null} for {@link Type#SHIFT}.
+ *
+ * @since 3.0.0
+ */
+public record Transition(Type type, String label) {

Review Comment:
   Public, but no public signature uses it. Package-private.



##########
opennlp-core/opennlp-runtime/src/test/java/opennlp/tools/depparse/FeedforwardDependencyScoringTest.java:
##########
@@ -0,0 +1,456 @@
+/*
+ * 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.tools.depparse;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.lang.reflect.Field;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.IdentityHashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReferenceArray;
+import java.util.stream.DoubleStream;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+
+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;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/** Checks numerical precision and concurrent cache use during dependency parsing. */
+class FeedforwardDependencyScoringTest {
+
+  private static final int CACHE_ENTRY_LIMIT = 32768;
+  private static final int FEATURES = FeedforwardContext.FEATURE_COUNT;
+  private static final int VOCABULARY_ROWS = 8;
+  private static final String[] TRANSITIONS = {"SHIFT", "LEFT_ARC:dep", "RIGHT_ARC:root"};
+  private static final String[] TOKENS = {"birds", "sing"};
+  private static final String[] TAGS = {"NOUN", "VERB"};
+
+  /**
+   * A hidden-layer calculation with a known result.
+   *
+   * @param name The arithmetic condition.
+   * @param inputs The embedding values.
+   * @param weights The hidden-layer weights.
+   * @param bias The hidden bias.
+   * @param outputScale The output weight magnitude.
+   * @param hidden The expected hidden sum before activation.
+   */
+  private record Calculation(String name, float[] inputs, float[] weights,
+      float bias, float outputScale, double hidden) {
+  }
+
+  /** {@return finite products and sums covering overflow, underflow and cancellation} */
+  private static Stream<Arguments> calculations() {
+    final float[] inputs = new float[256];
+    final float[] weights = new float[256];
+    Arrays.fill(inputs, Math.scalb(1f, 80));
+    Arrays.fill(weights, Math.scalb(1f, 40));
+    return Stream.of(
+        new Calculation("product overflow", new float[] {Math.scalb(1f, 80)},
+            new float[] {Math.scalb(1f, 80)}, 0, Math.scalb(1f, -120), Math.scalb(1d, 160)),
+        new Calculation("product underflow", new float[] {Math.scalb(1f, -80)},
+            new float[] {Math.scalb(1f, -80)}, 0, Math.scalb(1f, 120), Math.scalb(1d, -160)),
+        new Calculation("product cancellation", new float[] {Math.nextUp(1f), 1f},
+            new float[] {Math.nextUp(1f), -(1f + Math.scalb(1f, -22))}, 0,
+            Math.scalb(1f, 120), Math.scalb(1d, -46)),
+        new Calculation("cache range", inputs, weights, 0, Math.scalb(1f, -120),
+            Math.scalb(1d, 128)),
+        new Calculation("cache cancellation", new float[] {1f, Math.scalb(1f, -24)},
+            new float[] {1f, 1f}, -1f, Math.scalb(1f, 80), Math.scalb(1d, -24)))
+        .flatMap(calculation -> Stream.of(false, true).map(negative ->
+            Arguments.of(calculation.name(), calculation, negative)));
+  }
+
+  /**
+   * Direct, cached, copied and reloaded models retain the calculated values.
+   *
+   * @param name The arithmetic condition.
+   * @param calculation The input values and expected result.
+   * @param negative Whether to negate the hidden sum.
+   * @throws IOException If model serialization or loading fails.
+   */
+  @ParameterizedTest(name = "{0}, negative={2}")
+  @MethodSource("calculations")
+  void testKnownScores(String name, Calculation calculation, boolean negative) throws IOException {
+    final FeedforwardDependencyModel model = calculationModel(calculation, negative);
+    final double hidden = negative ? -calculation.hidden() : calculation.hidden();
+    final double score = hidden * hidden * hidden * calculation.outputScale();
+    final double[] expected = {0, -score, score};
+    final int[] features = new int[FEATURES];
+    assertArrayEquals(expected, model.score(features), name);
+    final byte[] serialized = serialize(model);
+    model.enableScoringCache();
+    assertArrayEquals(expected, model.score(features));
+    assertArrayEquals(expected, model.score(features));
+    assertArrayEquals(expected, model.copy().score(features));
+    assertArrayEquals(serialized, serialize(model));
+    final FeedforwardDependencyModel loaded = FeedforwardDependencyModel.load(
+        new ByteArrayInputStream(serialized));
+    assertArrayEquals(expected, loaded.score(features));
+    final DependencyGraph expectedGraph = negative
+        ? DependencyGraph.of(new int[] {1, -1}, new String[] {"dep", "root"})
+        : DependencyGraph.of(new int[] {-1, 0}, new String[] {"root", "root"});
+    assertEquals(expectedGraph, new FeedforwardDependencyParser(loaded).parse(TOKENS, TAGS));
+  }
+
+  /**
+   * Builds one active input block with opposite arc output weights.
+   *
+   * @param calculation The input values.
+   * @param negative Whether to negate weights and bias.
+   * @return The model.
+   */
+  private FeedforwardDependencyModel calculationModel(Calculation calculation, boolean negative) {
+    final int width = calculation.inputs().length;
+    final float[][] embeddings = new float[VOCABULARY_ROWS][width];
+    for (int row = 0; row < embeddings.length; row++) {
+      embeddings[row] = calculation.inputs().clone();
+    }
+    final float[][] weights = new float[1][FEATURES * width];
+    for (int i = 0; i < width; i++) {
+      weights[0][i] = negative ? -calculation.weights()[i] : calculation.weights()[i];
+    }
+    return model(embeddings, weights,
+        new float[] {negative ? -calculation.bias() : calculation.bias()},
+        new float[][] {{0}, {-calculation.outputScale()}, {calculation.outputScale()}});
+  }
+
+  /**
+   * Builds a model with disjoint reserved vocabularies and valid transitions.
+   *
+   * @param embeddings The embedding matrix.
+   * @param weights The hidden weights.
+   * @param bias The hidden bias.
+   * @param outputs The output weights.
+   * @return The model.
+   */
+  private FeedforwardDependencyModel model(float[][] embeddings, float[][] weights,
+      float[] bias, float[][] outputs) {
+    return new FeedforwardDependencyModel(
+        Map.of(FeedforwardDependencyModel.UNKNOWN, 0, FeedforwardDependencyModel.ABSENT, 1,
+            FeedforwardDependencyModel.ROOT_SYMBOL, 2),
+        Map.of(FeedforwardDependencyModel.UNKNOWN, 3, FeedforwardDependencyModel.ABSENT, 4,
+            FeedforwardDependencyModel.ROOT_SYMBOL, 5),
+        Map.of(FeedforwardDependencyModel.UNKNOWN, 6, FeedforwardDependencyModel.ABSENT, 7),
+        TRANSITIONS.clone(), embeddings[0].length, embeddings, weights, bias, outputs,
+        new float[TRANSITIONS.length]);
+  }
+
+  /** {@return invalid values in each output for greedy and beam parsing} */
+  private static Stream<Arguments> invalidScores() {
+    return Stream.of(Float.NaN, Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY)
+        .flatMap(value -> IntStream.range(0, TRANSITIONS.length).boxed().flatMap(index ->
+            Stream.of(1, 4).map(beam -> Arguments.of(value, index, beam))));
+  }
+
+  /**
+   * Corrupt in-memory scores fail at either decoding entry point.
+   *
+   * @param value The injected output bias.
+   * @param index The affected transition.
+   * @param beam The decoder beam size.
+   */
+  @ParameterizedTest
+  @MethodSource("invalidScores")
+  void testInvalidScores(float value, int index, int beam) {
+    final FeedforwardDependencyModel model = model(new float[VOCABULARY_ROWS][1],
+        new float[1][FEATURES], new float[1], new float[TRANSITIONS.length][1]);
+    model.outputBias()[index] = value;
+    final FeedforwardDependencyParser parser = new FeedforwardDependencyParser(model, beam);
+    final IllegalStateException error = assertThrows(IllegalStateException.class,
+        () -> parser.parse(TOKENS, TAGS));
+    assertTrue(error.getMessage().contains("non-finite"), error.getMessage());
+  }
+
+  /** {@return common score offsets for parsing and refinement normalization} */
+  private static Stream<Arguments> normalizationCases() {
+    return DoubleStream.of(0, 1, -1, 1e20, -1e20, Float.MAX_VALUE, -Float.MAX_VALUE, 1e100)
+        .boxed().flatMap(offset -> Stream.of(false, true)
+            .map(refinement -> Arguments.of(offset, refinement)));
+  }
+
+  /**
+   * A common finite score offset leaves equal transition probabilities unchanged.
+   *
+   * @param offset The score shared by all transitions.
+   * @param refinement Whether to use the refinement optimizer's normalization.
+   * @throws ReflectiveOperationException If the normalization method cannot be called.
+   */
+  @ParameterizedTest
+  @MethodSource("normalizationCases")
+  void testEqualLogProbabilities(double offset, boolean refinement)
+      throws ReflectiveOperationException {
+    final double[] scores = new double[TRANSITIONS.length];
+    Arrays.fill(scores, offset);
+    final double[] expected = new double[TRANSITIONS.length];
+    Arrays.fill(expected, -Math.log(TRANSITIONS.length));
+    assertArrayEquals(expected, normalizedScores(scores, refinement), 1e-15);
+  }
+
+  /** {@return offsets for three unequal, representable scores in both normalizers} */
+  private static Stream<Arguments> unequalNormalizationCases() {
+    return DoubleStream.of(0, 1, -1, 1e12, -1e12, Math.scalb(1d, 48)).boxed()
+        .flatMap(offset -> Stream.of(false, true).map(refinement -> Arguments.of(offset, refinement)));
+  }
+
+  /**
+   * Unequal probabilities retain their values and sum to one after a common shift.
+   *
+   * @param offset The common score shift.
+   * @param refinement Whether to use refinement normalization.
+   * @throws ReflectiveOperationException If the normalization method cannot be called.
+   */
+  @ParameterizedTest
+  @MethodSource("unequalNormalizationCases")
+  void testUnequalLogProbabilities(double offset, boolean refinement)
+      throws ReflectiveOperationException {
+    final double logSum = Math.log(Math.exp(-0.5) + Math.exp(-0.25) + 1);
+    final double[] expected = {-0.5 - logSum, -0.25 - logSum, -logSum};
+    final double[] actual = normalizedScores(new double[] {offset, offset + 0.25, offset + 0.5},
+        refinement);
+    assertArrayEquals(expected, actual, 1e-15);
+    assertEquals(1.0, Arrays.stream(actual).map(Math::exp).sum(), 1e-15);
+  }
+
+  /**
+   * Calls a private normalizer without exposing it through production API.
+   *
+   * @param scores The finite raw scores; refinement overwrites them.
+   * @param refinement Whether to use refinement normalization.
+   * @return The log probabilities.
+   * @throws ReflectiveOperationException If the normalizer cannot be called.
+   */
+  private double[] normalizedScores(double[] scores, boolean refinement)
+      throws ReflectiveOperationException {
+    final FeedforwardDependencyModel model = model(
+        new float[VOCABULARY_ROWS][1], new float[1][FEATURES], new float[1],
+        new float[TRANSITIONS.length][1]);
+    if (refinement) {
+      final Class<?> type = Class.forName(

Review Comment:
   Reflection into private members, and `32768` copied from `MAX_PAIRS`. Please test through package-private API.



##########
opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/depparse/FeedforwardDependencyModel.java:
##########
@@ -0,0 +1,951 @@
+/*
+ * 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.tools.depparse;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReferenceArray;
+
+import opennlp.tools.commons.ThreadSafe;
+import opennlp.tools.util.InvalidFormatException;
+import opennlp.tools.util.StringUtil;
+
+/**
+ * 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, stored
+ * in a plain versioned binary format with no serialization framework involved. The
+ * architecture follows
+ * <a href="https://aclanthology.org/D14-1082/">Chen and Manning (2014)</a>.
+ *
+ * <p>The network runs with Java arrays and requires no native runtime. The same class
+ * scores configurations during training and decoding. Unknown words use a learned
+ * fallback row; words are matched case-insensitively after
+ * {@link #normalize(String) normalization}.</p>
+ *
+ * <p>Instances returned by {@link FeedforwardDependencyTrainer} are immutable and safe
+ * to share between threads. {@link FeedforwardDependencyTrainer#refine refine} updates
+ * an independent copy.</p>
+ *
+ * @see FeedforwardDependencyParser
+ * @see FeedforwardDependencyTrainer
+ * @since 3.0.0
+ */
+@ThreadSafe
+public class FeedforwardDependencyModel {
+
+  /** The format header written before every serialized model; it carries the format version. */
+  private static final String MAGIC = "ONLP-FFDP-1";
+
+  /** The vocabulary label used in load errors for the word map. */
+  private static final String WORD_VOCABULARY = "word vocabulary";
+
+  /** The vocabulary label used in load errors for the tag map. */
+  private static final String TAG_VOCABULARY = "tag vocabulary";
+
+  /** The vocabulary label used in load errors for the label map. */
+  private static final String LABEL_VOCABULARY = "label vocabulary";
+
+  /** Maximum combined entries across the word, tag, and label maps. */
+  private static final int MAX_VOCABULARY_ENTRIES = 2_000_000;
+
+  /** Maximum transitions accepted from a serialized model. */
+  private static final int MAX_TRANSITIONS = 100_000;
+
+  /** Maximum embedding width accepted from a serialized model. */
+  static final int MAX_EMBEDDING_SIZE = 4_096;
+
+  /** Maximum hidden-layer width accepted from a serialized model. */
+  static final int MAX_HIDDEN_SIZE = 65_536;
+
+  /** Maximum float values allocated while loading a serialized model. */
+  static final long MAX_MODEL_FLOAT_VALUES = 100_000_000L;
+
+  /** U+03A3, GREEK CAPITAL LETTER SIGMA, the one code point with a contextual lowering. */
+  private static final int GREEK_CAPITAL_SIGMA = 0x03A3;
+
+  /** U+03C2, GREEK SMALL LETTER FINAL SIGMA, the word-final lowering of the capital. */
+  private static final char GREEK_SMALL_FINAL_SIGMA = '\u03C2';
+
+  /** The vocabulary key of every word, tag, or label the model has no embedding row for. */
+  static final String UNKNOWN = "*UNK*";
+
+  /** The vocabulary key of a template position that does not exist in a configuration. */
+  static final String ABSENT = "*NULL*";
+
+  /** The vocabulary key of the artificial root node. */
+  static final String ROOT_SYMBOL = "*ROOT*";
+
+  /** The lazy scoring cache; {@code null} until {@link #enableScoringCache()}. */
+  private volatile ContributionCache cache;
+
+  private final Map<String, Integer> wordIds;
+  private final Map<String, Integer> tagIds;
+  private final Map<String, Integer> labelIds;
+  private final String[] transitions;
+
+  private final int embeddingSize;
+  private final float[][] embeddings;
+  private final float[][] hiddenWeights;
+  private final float[] hiddenBias;
+  private final float[][] outputWeights;
+  private final float[] outputBias;
+
+  /**
+   * Assembles a model from its vocabularies and weights, copying the maps so later
+   * changes by the caller do not reach the model.
+   *
+   * @param wordIds The word vocabulary, mapping each normalized word to its row.
+   * @param tagIds The tag vocabulary.
+   * @param labelIds The dependency label vocabulary.
+   * @param transitions The transition inventory, indexed by output row.
+   * @param embeddingSize The embedding dimensionality.
+   * @param embeddings The embedding rows for words, tags, and labels.
+   * @param hiddenWeights The hidden layer weights.
+   * @param hiddenBias The hidden layer bias.
+   * @param outputWeights The output layer weights.
+   * @param outputBias The output layer bias.
+   */
+  FeedforwardDependencyModel(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) {
+    this.wordIds = Map.copyOf(wordIds);
+    this.tagIds = Map.copyOf(tagIds);
+    this.labelIds = Map.copyOf(labelIds);
+    this.transitions = transitions;
+    this.embeddingSize = embeddingSize;
+    this.embeddings = embeddings;
+    this.hiddenWeights = hiddenWeights;
+    this.hiddenBias = hiddenBias;
+    this.outputWeights = outputWeights;
+    this.outputBias = outputBias;
+  }
+
+  /**
+   * Scores every transition for a configuration described by embedding row indices.
+   *
+   * @param features The embedding rows of the configuration, as produced by
+   *                 {@link #featureIds(String[])}. Must not be {@code null}.
+   * @return One unnormalized score per transition, indexed like
+   *         {@link #transitions()}. Never {@code null}.
+   * @throws IllegalArgumentException Thrown if {@code features} is {@code null}, does not
+   *         have the required length, or contains an invalid embedding index.
+   * @throws IllegalStateException If the model produces a non-finite transition score.
+   */
+  double[] score(int[] features) {
+    if (features == null) {
+      throw new IllegalArgumentException("features must not be null");
+    }
+    if (features.length != FeedforwardContext.FEATURE_COUNT) {
+      throw new IllegalArgumentException("features must contain "
+          + FeedforwardContext.FEATURE_COUNT + " embedding indices");
+    }
+    for (int i = 0; i < features.length; i++) {
+      if (features[i] < 0 || features[i] >= embeddings.length) {
+        throw new IllegalArgumentException(
+            "feature embedding out of range at index " + i + ": " + features[i]);
+      }
+    }
+    final int hidden = hiddenBias.length;
+    final double[] h = new double[hidden];
+    for (int j = 0; j < hidden; j++) {
+      h[j] = hiddenBias[j];
+    }
+    final ContributionCache cache = this.cache;
+    for (int f = 0; f < features.length; f++) {
+      final int row = features[f];
+      final double[] contribution = cache == null ? null : cache.contribution(this, f, row);
+      if (contribution != null) {
+        for (int j = 0; j < hidden; j++) {
+          h[j] += contribution[j];
+        }
+      } else {
+        final float[] embedding = embeddings[row];
+        final int offset = f * embeddingSize;
+        for (int j = 0; j < hidden; j++) {
+          final float[] weights = hiddenWeights[j];
+          double sum = 0.0;
+          for (int d = 0; d < embeddingSize; d++) {
+            sum += (double) weights[offset + d] * embedding[d];
+          }
+          h[j] += sum;
+        }
+      }
+    }
+    for (int j = 0; j < hidden; j++) {
+      h[j] = h[j] * h[j] * h[j];
+    }
+    final double[] scores = new double[transitions.length];
+    for (int o = 0; o < scores.length; o++) {
+      final float[] row = outputWeights[o];
+      double sum = outputBias[o];
+      for (int j = 0; j < hidden; j++) {
+        sum += row[j] * h[j];
+      }
+      if (!Double.isFinite(sum)) {
+        throw new IllegalStateException("the model produced a non-finite transition score");
+      }
+      scores[o] = sum;
+    }
+    return scores;
+  }
+
+  /**
+   * Caches hidden-layer contributions by template position and embedding row.
+   *
+   * <p>Contributions retain double precision so cached and direct scoring use the
+   * same values. Training and refinement use uncached copies; {@link #copy()}
+   * does not copy the cache.</p>
+   */
+  synchronized void enableScoringCache() {
+    if (cache == null) {
+      cache = new ContributionCache(FeedforwardContext.FEATURE_COUNT, embeddings.length);
+    }
+  }
+
+  /**
+   * Stores contributions on first use up to a shared entry limit. Reference tables
+   * are allocated for every template position and embedding row. Pairs beyond the
+   * entry limit use direct scoring.
+   */
+  private static final class ContributionCache {
+
+    /** The maximum number of cached (position, row) pairs. */
+    private static final int MAX_PAIRS = 32768;
+
+    /** The cached contribution vectors, indexed by template position and embedding row. */
+    private final AtomicReferenceArray<double[]>[] byPosition;
+
+    /** The number of pairs the cache may still add before the budget is spent. */
+    private final AtomicInteger remaining = new AtomicInteger(MAX_PAIRS);
+
+    /**
+     * Creates an empty cache.
+     *
+     * @param positions The number of feature positions.
+     * @param rows The number of embedding rows a position can hold.
+     */
+    @SuppressWarnings("unchecked")
+    private ContributionCache(int positions, int rows) {
+      byPosition = new AtomicReferenceArray[positions];
+      for (int f = 0; f < positions; f++) {
+        byPosition[f] = new AtomicReferenceArray<>(rows);
+      }
+    }
+
+    /**
+     * Returns the cached hidden-layer contribution of one pair, computing and
+     * publishing it on first sight while the budget lasts.
+     *
+     * @param model The immutable model the contributions derive from.
+     * @param position The template position.
+     * @param row The embedding row at that position.
+     * @return The contribution vector, or {@code null} when the budget is spent and
+     *         the pair is not cached.
+     */
+    private double[] contribution(FeedforwardDependencyModel model, int position, int row) {
+      final AtomicReferenceArray<double[]> slots = byPosition[position];
+      double[] contribution = slots.get(row);
+      if (contribution != null) {
+        return contribution;
+      }
+      if (!reserve()) {
+        return null;
+      }
+      boolean published = false;
+      try {
+        final int hidden = model.hiddenBias.length;
+        final float[] embedding = model.embeddings[row];
+        final int offset = position * model.embeddingSize;
+        contribution = new double[hidden];
+        for (int j = 0; j < hidden; j++) {
+          final float[] weights = model.hiddenWeights[j];
+          double sum = 0.0;
+          for (int d = 0; d < model.embeddingSize; d++) {
+            sum += (double) weights[offset + d] * embedding[d];
+          }
+          contribution[j] = sum;
+        }
+        published = slots.compareAndSet(row, null, contribution);
+        return published ? contribution : slots.get(row);
+      } finally {
+        if (!published) {
+          remaining.incrementAndGet();
+        }
+      }
+    }
+
+    /**
+     * Reserves capacity before allocating a contribution array.
+     *
+     * @return Whether one entry was reserved.
+     */
+    private boolean reserve() {
+      int available = remaining.get();
+      while (available > 0) {
+        if (remaining.compareAndSet(available, available - 1)) {
+          return true;
+        }
+        available = remaining.get();
+      }
+      return false;
+    }
+  }
+
+  /**
+   * Maps the symbolic features of {@link FeedforwardContext} onto embedding rows.
+   *
+   * @param symbols The symbolic features. Must not be {@code null}.
+   * @return The embedding row per feature. Never {@code null}.
+   * @throws IllegalArgumentException Thrown if {@code symbols} is {@code null} or does
+   *         not have the required length.
+   */
+  int[] featureIds(String[] symbols) {
+    if (symbols == null) {
+      throw new IllegalArgumentException("symbols must not be null");
+    }
+    if (symbols.length != FeedforwardContext.FEATURE_COUNT) {
+      throw new IllegalArgumentException("symbols must contain "
+          + FeedforwardContext.FEATURE_COUNT + " features");
+    }
+    final int[] ids = new int[symbols.length];
+    for (int i = 0; i < FeedforwardContext.POSITIONS; i++) {
+      ids[i] = lookup(wordIds, normalize(symbols[i]));
+    }
+    for (int i = FeedforwardContext.POSITIONS; i < 2 * FeedforwardContext.POSITIONS; i++) {
+      ids[i] = lookup(tagIds, symbols[i]);
+    }
+    for (int i = 2 * FeedforwardContext.POSITIONS; i < symbols.length; i++) {
+      ids[i] = lookup(labelIds, symbols[i]);
+    }
+    return ids;
+  }
+
+  /**
+   * @return The transition outcome strings by output index. Never {@code null}.
+   */
+  public String[] transitions() {
+    return transitions.clone();

Review Comment:
   About 120 lines of final-sigma handling. The vocabulary key only has to be consistent between training and parsing, so `StringUtil.toLowerCase` is enough. Or move it to `StringUtil`.



##########
opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/depparse/FeedforwardDependencyTrainer.java:
##########
@@ -0,0 +1,1175 @@
+/*
+ * 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.tools.depparse;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Random;
+import java.util.function.Function;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import opennlp.tools.util.ObjectStream;
+
+/**
+ * Trains the {@link FeedforwardDependencyModel} entirely in Java: 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
+ * <a href="https://aclanthology.org/D14-1082/">Chen and Manning (2014)</a>. Training and
+ * inference use Java arrays and require no external training framework.
+ *
+ * <p>Words below the frequency cutoff share a learned unknown embedding; absent
+ * template positions share a learned padding embedding. Non-projective samples have no
+ * arc-standard derivation and are skipped. Training is deterministic for a fixed
+ * {@link Settings#seed()}.</p>
+ *
+ * @since 3.0.0
+ */
+public final class FeedforwardDependencyTrainer {
+
+  private static final Logger logger =
+      LoggerFactory.getLogger(FeedforwardDependencyTrainer.class);
+
+  /** The AdaGrad denominator offset that keeps the first steps finite. */
+  private static final double ADAGRAD_EPSILON = 1e-6;
+
+  /** The derivative factor of the cube activation, {@code d/dx x^3 = 3x^2}. */
+  private static final double CUBE_DERIVATIVE_FACTOR = 3.0;
+
+  /** The numerator of the Glorot uniform bound, {@code sqrt(6 / (fanIn + fanOut))}. */
+  private static final double GLOROT_NUMERATOR = 6.0;
+
+  /** The half-width of the uniform range embeddings are drawn from. */
+  private static final double EMBEDDING_INIT_SCALE = 0.01;
+
+  /** The smallest probability the reported training loss takes the log of. */
+  private static final double LOSS_PROBABILITY_FLOOR = 1e-12;
+
+  /** The sentence loss reported when refinement made no update for a sentence. */
+  private static final double NO_UPDATE = -1.0;
+
+  /** Special-symbol rows present before any training vocabulary is added. */
+  private static final int MIN_VOCABULARY_ROWS = 8;
+
+  /** SHIFT and at least one RIGHT_ARC are required to parse a sentence. */
+  private static final int MIN_TRANSITIONS = 2;
+
+  /** Prevents construction of this utility class. */
+  private FeedforwardDependencyTrainer() {
+  }
+
+  /**
+   * The training hyperparameters.
+   *
+   * @param embeddingSize The embedding dimensionality. Must be positive.
+   * @param hiddenSize The hidden layer width. Must be positive.
+   * @param epochs The number of passes over the examples. Must be positive.
+   * @param batchSize The minibatch size. Must be positive.
+   * @param learningRate The AdaGrad step size. Must be positive.
+   * @param l2 The L2 penalty applied to the dense weights. Must not be negative.
+   * @param dropout The hidden dropout probability. Must be in {@code [0, 1)}.
+   * @param wordCutoff The minimum frequency for a word to get its own embedding. Must
+   *                   not be negative.
+   * @param seed The random seed making a run reproducible.
+   */
+  public record Settings(int embeddingSize, int hiddenSize, int epochs, int batchSize,
+      double learningRate, double l2, double dropout, int wordCutoff, long seed) {
+
+    /** The default embedding dimensionality. */
+    private static final int DEFAULT_EMBEDDING_SIZE = 50;
+
+    /** The default hidden layer width. */
+    private static final int DEFAULT_HIDDEN_SIZE = 200;
+
+    /** The default number of epochs. */
+    private static final int DEFAULT_EPOCHS = 10;
+
+    /** The default minibatch size. */
+    private static final int DEFAULT_BATCH_SIZE = 256;
+
+    /** The default AdaGrad step size. */
+    private static final double DEFAULT_LEARNING_RATE = 0.02;
+
+    /** The default L2 penalty. */
+    private static final double DEFAULT_L2 = 1e-8;
+
+    /** The default hidden dropout probability. */
+    private static final double DEFAULT_DROPOUT = 0.5;
+
+    /** The default minimum word frequency for an embedding row. */
+    private static final int DEFAULT_WORD_CUTOFF = 2;
+
+    /** The default random seed. */
+    private static final long DEFAULT_SEED = 17L;
+
+    /**
+     * Validates the hyperparameters.
+     *
+     * @throws IllegalArgumentException Thrown if a value is outside its documented
+     *         range.
+     */
+    public Settings {
+      if (embeddingSize <= 0 || hiddenSize <= 0 || epochs <= 0 || batchSize <= 0) {
+        throw new IllegalArgumentException("sizes, epochs and batch must be positive");
+      }
+      if (embeddingSize > FeedforwardDependencyModel.MAX_EMBEDDING_SIZE) {
+        throw new IllegalArgumentException("embeddingSize exceeds the model format limit: "
+            + embeddingSize);
+      }
+      if (hiddenSize > FeedforwardDependencyModel.MAX_HIDDEN_SIZE) {
+        throw new IllegalArgumentException("hiddenSize exceeds the model format limit: "
+            + hiddenSize);
+      }
+      final long minimumModelValues = modelFloatValues(MIN_VOCABULARY_ROWS,
+          MIN_TRANSITIONS, embeddingSize, hiddenSize);
+      if (minimumModelValues > FeedforwardDependencyModel.MAX_MODEL_FLOAT_VALUES) {
+        throw new IllegalArgumentException("embeddingSize and hiddenSize exceed the model "
+            + "format allocation limit");
+      }
+      if (!Double.isFinite(learningRate) || learningRate <= 0.0
+          || !Double.isFinite(l2) || l2 < 0.0) {
+        throw new IllegalArgumentException(
+            "learningRate must be finite and positive, l2 finite and not negative");
+      }
+      if (!(dropout >= 0.0 && dropout < 1.0)) {
+        throw new IllegalArgumentException("dropout must be in [0, 1): " + dropout);
+      }
+      if (wordCutoff < 0) {
+        throw new IllegalArgumentException("wordCutoff must not be negative");
+      }
+    }
+
+    /**
+     * @return The default hyperparameters. Never {@code null}.
+     */
+    public static Settings defaults() {
+      return new Settings(DEFAULT_EMBEDDING_SIZE, DEFAULT_HIDDEN_SIZE, DEFAULT_EPOCHS,
+          DEFAULT_BATCH_SIZE, DEFAULT_LEARNING_RATE, DEFAULT_L2, DEFAULT_DROPOUT,
+          DEFAULT_WORD_CUTOFF, DEFAULT_SEED);
+    }
+  }
+
+  /**
+   * Trains a model from dependency samples.
+   *
+   * @param samples The training samples. Must not be {@code null}.
+   * @param settings The hyperparameters. Must not be {@code null}.
+   * @return A trained {@link FeedforwardDependencyModel}. Never {@code null}.
+   * @throws IOException Thrown if reading the samples fails.
+   * @throws IllegalArgumentException Thrown if a parameter is {@code null} or no
+   *         trainable example can be derived from the samples.
+   */
+  public static FeedforwardDependencyModel train(ObjectStream<DependencySample> samples,
+      Settings settings) throws IOException {
+    return train(samples, settings, null);
+  }
+
+  /**
+   * Trains a model from dependency samples, seeding word embeddings from a pretrained
+   * source.
+   *
+   * <p>The provider is consulted once per vocabulary word during initialization; words
+   * it returns {@code null} for keep their random initialization, and all embeddings
+   * remain trainable afterwards. The pretrained source is a training-time ingredient
+   * only: the learned embeddings ship inside the model, so parsing carries no
+   * dependency on the source.</p>
+   *
+   * @param samples The training samples. Must not be {@code null}.
+   * @param settings The hyperparameters. Must not be {@code null}.
+   * @param pretrained Maps a normalized word to its pretrained vector of exactly
+   *                   {@link Settings#embeddingSize()} dimensions, or {@code null} for
+   *                   unknown words. May be {@code null} to disable seeding.
+   * @return A trained {@link FeedforwardDependencyModel}. Never {@code null}.
+   * @throws IOException Thrown if reading the samples fails.
+   * @throws IllegalArgumentException Thrown if {@code samples} or {@code settings} is
+   *         {@code null}, no trainable example can be derived, or a pretrained vector
+   *         has the wrong dimensionality.
+   */
+  public static FeedforwardDependencyModel train(ObjectStream<DependencySample> samples,
+      Settings settings, Function<String, float[]> pretrained)
+      throws IOException {
+    if (samples == null) {
+      throw new IllegalArgumentException("samples must not be null");
+    }
+    if (settings == null) {
+      throw new IllegalArgumentException("settings must not be null");
+    }
+    final List<DependencySample> corpus = readAll(samples);
+    final FeedforwardDependencyModel model = initialize(corpus, settings);
+    if (pretrained != null) {
+      seed(model, pretrained, settings);
+    }
+    final List<int[]> featureList = new ArrayList<>();
+    final List<Integer> goldList = new ArrayList<>();
+    collectExamples(corpus, model, featureList, goldList);
+    if (featureList.isEmpty()) {
+      throw new IllegalArgumentException("no trainable examples in the samples");
+    }
+    optimize(model, featureList, goldList, settings);
+    return model;
+  }
+
+  /**
+   * Refines a locally trained model with beam search and the early-update method of
+   * <a href="https://aclanthology.org/P04-1015/">Collins and Roark (2004)</a>. The loss
+   * is conditional likelihood over candidate paths scored by summed log-probabilities.
+   *
+   * <p>Refinement updates a copy with per-sentence AdaGrad steps and no dropout.
+   * {@link Settings#epochs()} sets the number of refinement passes. Use the same beam
+   * size for parsing the result.</p>
+   *
+   * <p>The transition inventory comes from {@code model} and is not extended, because
+   * its size is the width of the trained output layer. A refinement corpus using a
+   * relation label the original training set lacked is therefore rejected rather than
+   * silently ignored.</p>
+   *
+   * @param model The locally trained model to refine. Left untouched. Must not be
+   *              {@code null}.
+   * @param samples The training samples. Must not be {@code null}.
+   * @param settings The hyperparameters; {@code epochs}, {@code learningRate},
+   *                 {@code l2}, and {@code seed} apply. Must not be {@code null}.
+   * @param beamSize The beam width to track the gold derivation in. Must be at least 2.
+   * @return A new refined model, distinct from {@code model}. Never {@code null}.
+   * @throws IOException Thrown if reading the samples fails.
+   * @throws IllegalArgumentException Thrown if a parameter is {@code null},
+   *         {@code beamSize} is below 2, no trainable sample can be derived, or a sample
+   *         requires a transition {@code model} does not know.
+   */
+  public static FeedforwardDependencyModel refine(FeedforwardDependencyModel model,
+      ObjectStream<DependencySample> samples, Settings settings, int beamSize)
+      throws IOException {
+    if (model == null) {
+      throw new IllegalArgumentException("model must not be null");
+    }
+    if (samples == null) {
+      throw new IllegalArgumentException("samples must not be null");
+    }
+    if (settings == null) {
+      throw new IllegalArgumentException("settings must not be null");
+    }
+    if (beamSize < 2) {
+      throw new IllegalArgumentException("beamSize must be at least 2: " + beamSize);
+    }
+    final List<DependencySample> corpus = readAll(samples);
+    final String[] outcomes = model.transitions();
+    final Map<String, Integer> transitionIds = new HashMap<>();
+    final Transition[] transitions = new Transition[outcomes.length];
+    for (int i = 0; i < transitions.length; i++) {
+      transitionIds.put(outcomes[i], i);
+      transitions[i] = Transition.decode(outcomes[i]);
+    }
+
+    final List<DependencySample> trainable = new ArrayList<>();
+    final List<int[]> oracles = new ArrayList<>();
+    for (final DependencySample s : corpus) {
+      if (!ArcStandardOracle.isProjective(s.getGraph())) {
+        continue;
+      }
+      final List<Transition> oracle = ArcStandardOracle.transitions(s.getGraph());
+      final int[] encoded = new int[oracle.size()];
+      for (int i = 0; i < encoded.length; i++) {
+        final String outcome = oracle.get(i).encode();
+        final Integer id = transitionIds.get(outcome);
+        if (id == null) {
+          // The outcome space was fixed by the original training set, so a relation
+          // label it never saw has no output unit to push probability onto.
+          throw new IllegalArgumentException(
+              "unknown transition in the refinement samples: " + outcome);
+        }
+        encoded[i] = id;
+      }
+      trainable.add(s);
+      oracles.add(encoded);
+    }
+    if (trainable.isEmpty()) {
+      throw new IllegalArgumentException("no trainable samples for refinement");
+    }
+
+    final FeedforwardDependencyModel refined = model.copy();
+    final GlobalOptimizer optimizer = new GlobalOptimizer(refined, settings);
+    final Random random = new Random(settings.seed());
+    final int[] order = new int[trainable.size()];
+    for (int i = 0; i < order.length; i++) {
+      order[i] = i;
+    }
+    for (int epoch = 1; epoch <= settings.epochs(); epoch++) {
+      final long epochStart = System.currentTimeMillis();
+      shuffle(order, random);
+      double loss = 0.0;
+      int updates = 0;
+      for (final int index : order) {
+        final double sentenceLoss = optimizer.refineSentence(trainable.get(index),
+            oracles.get(index), transitions, beamSize);
+        if (sentenceLoss >= 0.0) {
+          loss += sentenceLoss;
+          updates++;
+        }
+      }
+      checkFinite(refined);
+      logger.info("refine epoch {}: loss {} over {} updates in {} ms", epoch,
+          loss / Math.max(updates, 1), updates, System.currentTimeMillis() - epochStart);
+    }
+    return refined;
+  }
+
+  /** One candidate path in the refinement beam: the parent link forms the history. */
+  private static final class BeamNode {
+    private final BeamNode parent;
+    private final int[] features;
+    private final int transition;
+    private final double score;
+    private final boolean gold;
+    private ArcStandardState state;
+
+    /**
+     * Extends {@code parent} by one transition; the start node passes {@code null}.
+     *
+     * @param parent The node this one extends, or {@code null} for the start node.
+     * @param features The embedding rows the transition was scored on.
+     * @param transition The transition index taken from {@code parent}.
+     * @param score The summed log-probability of the path.
+     * @param gold Whether the path is the gold derivation so far.
+     */
+    private BeamNode(BeamNode parent, int[] features, int transition, double score,
+        boolean gold) {
+      this.parent = parent;
+      this.features = features;
+      this.transition = transition;
+      this.score = score;
+      this.gold = gold;
+    }
+  }
+
+  /** The forward, backward, and AdaGrad state for global refinement. */
+  private static final class GlobalOptimizer {
+    private final FeedforwardDependencyModel model;
+    private final Settings settings;
+    private final int embeddingSize;
+    private final int hiddenSize;
+    private final int outputSize;
+    private final int inputSize;
+
+    private final double[][] embeddingAccumulator;
+    private final double[][] hiddenAccumulator;
+    private final double[] hiddenBiasAccumulator;
+    private final double[][] outputAccumulator;
+    private final double[] outputBiasAccumulator;
+
+    private final double[][] hiddenGradient;
+    private final double[] hiddenBiasGradient;
+    private final double[][] outputGradient;
+    private final double[] outputBiasGradient;
+    private final Map<Integer, double[]> embeddingGradients = new HashMap<>();
+
+    private final double[] x;
+    private final double[] pre;
+    private final double[] hidden;
+    private final double[] probabilities;
+    private final double[] hiddenDelta;
+    private final double[] inputDelta;
+
+    /**
+     * Sizes the accumulators and scratch buffers for one refinement run.
+     *
+     * @param model The model copy the run updates in place.
+     * @param settings The hyperparameters; {@code learningRate} and {@code l2} apply.
+     */
+    private GlobalOptimizer(FeedforwardDependencyModel model, Settings settings) {
+      this.model = model;
+      this.settings = settings;
+      this.embeddingSize = model.embeddings()[0].length;
+      this.hiddenSize = model.hiddenBias().length;
+      this.outputSize = model.outputBias().length;
+      this.inputSize = FeedforwardContext.FEATURE_COUNT * embeddingSize;
+      this.embeddingAccumulator =
+          new double[model.embeddings().length][embeddingSize];
+      this.hiddenAccumulator = new double[hiddenSize][inputSize];
+      this.hiddenBiasAccumulator = new double[hiddenSize];
+      this.outputAccumulator = new double[outputSize][hiddenSize];
+      this.outputBiasAccumulator = new double[outputSize];
+      this.hiddenGradient = new double[hiddenSize][inputSize];
+      this.hiddenBiasGradient = new double[hiddenSize];
+      this.outputGradient = new double[outputSize][hiddenSize];
+      this.outputBiasGradient = new double[outputSize];
+      this.x = new double[inputSize];
+      this.pre = new double[hiddenSize];
+      this.hidden = new double[hiddenSize];
+      this.probabilities = new double[outputSize];
+      this.hiddenDelta = new double[hiddenSize];
+      this.inputDelta = new double[inputSize];
+    }
+
+    /**
+     * Decodes one sentence with the beam, updating on the early-update point or the
+     * final beam.
+     *
+     * @param sample The sentence.
+     * @param oracle The gold transition indexes.
+     * @param transitions The decoded transition inventory.
+     * @param beamSize The beam width.
+     * @return The sentence loss, or {@link FeedforwardDependencyTrainer#NO_UPDATE} when the
+     *         sentence produced no update.
+     */
+    private double refineSentence(DependencySample sample, int[] oracle,
+        Transition[] transitions, int beamSize) {
+      final String[] tokens = sample.getTokens();
+      final String[] tags = sample.getTags();
+      final BeamNode root = new BeamNode(null, null, -1, 0.0, true);
+      root.state = new ArcStandardState(tokens.length);
+      List<BeamNode> beam = List.of(root);
+
+      for (int step = 0; step < oracle.length; step++) {
+        final List<BeamNode> expansions = new ArrayList<>();
+        BeamNode goldChild = null;
+        for (final BeamNode node : beam) {
+          final int[] features =
+              model.featureIds(FeedforwardContext.extract(node.state, tokens, tags));
+          forward(features);
+          logSoftmaxInPlace(probabilities);
+          for (int i = 0; i < outputSize; i++) {
+            if (node.state.canApply(transitions[i])) {
+              final boolean goldNext = node.gold && i == oracle[step];
+              final BeamNode child = new BeamNode(node, features, i,
+                  node.score + probabilities[i], goldNext);
+              expansions.add(child);
+              if (goldNext) {
+                goldChild = child;
+              }
+            }
+          }
+        }
+        expansions.sort((a, b) -> Double.compare(b.score, a.score));
+        final List<BeamNode> survivors =
+            new ArrayList<>(expansions.subList(0, Math.min(beamSize, expansions.size())));
+        boolean goldRetained = false;
+        for (final BeamNode survivor : survivors) {
+          if (survivor.gold) {
+            goldRetained = true;
+            break;
+          }
+        }
+        if (!goldRetained) {
+          if (goldChild == null) {
+            // The gold transition was not applicable in the gold configuration, so
+            // this sentence yields no update.
+            return NO_UPDATE;
+          }
+          survivors.add(goldChild);
+          return updateFromCandidates(survivors);
+        }
+        if (step == oracle.length - 1) {
+          return updateFromCandidates(survivors);
+        }
+        for (final BeamNode survivor : survivors) {
+          survivor.state = survivor.parent.state.copy();
+          survivor.state.apply(transitions[survivor.transition]);
+        }
+        beam = survivors;
+      }
+      return NO_UPDATE;
+    }
+
+    /**
+     * Applies the conditional-likelihood update over the candidate paths.
+     *
+     * @param candidates The surviving paths plus, on early update, the gold path.
+     * @return The negative log-probability of the gold path under the candidates.
+     */
+    private double updateFromCandidates(List<BeamNode> candidates) {
+      double max = Double.NEGATIVE_INFINITY;
+      double goldScore = Double.NEGATIVE_INFINITY;
+      for (final BeamNode candidate : candidates) {
+        max = Math.max(max, candidate.score);
+        if (candidate.gold) {
+          goldScore = candidate.score;
+        }
+      }
+      double normalizer = 0.0;
+      for (final BeamNode candidate : candidates) {
+        normalizer += Math.exp(candidate.score - max);
+      }
+      final double logNormalizer = max + Math.log(normalizer);
+
+      zero(hiddenGradient);
+      Arrays.fill(hiddenBiasGradient, 0.0);
+      zero(outputGradient);
+      Arrays.fill(outputBiasGradient, 0.0);
+      embeddingGradients.clear();
+      for (final BeamNode candidate : candidates) {
+        final double weight = Math.exp(candidate.score - logNormalizer)
+            - (candidate.gold ? 1.0 : 0.0);
+        if (weight == 0.0) {
+          continue;
+        }
+        for (BeamNode node = candidate; node.parent != null; node = node.parent) {
+          backward(node.features, node.transition, weight);
+        }
+      }
+      update(model.hiddenWeights(), hiddenGradient, hiddenAccumulator, 1, settings);
+      updateVector(model.hiddenBias(), hiddenBiasGradient, hiddenBiasAccumulator, 1,
+          settings);
+      update(model.outputWeights(), outputGradient, outputAccumulator, 1, settings);
+      updateVector(model.outputBias(), outputBiasGradient, outputBiasAccumulator, 1,
+          settings);
+      for (final Map.Entry<Integer, double[]> entry : embeddingGradients.entrySet()) {
+        final float[] embeddingRow = model.embeddings()[entry.getKey()];
+        final double[] accumulatorRow = embeddingAccumulator[entry.getKey()];
+        final double[] gradientRow = entry.getValue();
+        for (int d = 0; d < embeddingSize; d++) {
+          final double gradient = gradientRow[d];
+          accumulatorRow[d] += gradient * gradient;
+          embeddingRow[d] -= settings.learningRate() * gradient
+              / (Math.sqrt(accumulatorRow[d]) + ADAGRAD_EPSILON);
+        }
+      }
+      return logNormalizer - goldScore;
+    }
+
+    /**
+     * Computes hidden activations and raw output scores for one feature vector into
+     * the scratch buffers.
+     *
+     * @param features The embedding rows of the configuration.
+     */
+    private void forward(int[] features) {
+      final float[][] embeddings = model.embeddings();
+      for (int f = 0; f < features.length; f++) {
+        final float[] embedding = embeddings[features[f]];
+        final int offset = f * embeddingSize;
+        for (int d = 0; d < embeddingSize; d++) {
+          x[offset + d] = embedding[d];
+        }
+      }
+      final float[][] hiddenWeights = model.hiddenWeights();
+      final float[] hiddenBias = model.hiddenBias();
+      for (int j = 0; j < hiddenSize; j++) {
+        final float[] weightRow = hiddenWeights[j];
+        double sum = hiddenBias[j];
+        for (int k = 0; k < inputSize; k++) {
+          sum += weightRow[k] * x[k];
+        }
+        pre[j] = sum;
+        hidden[j] = sum * sum * sum;
+      }
+      final float[][] outputWeights = model.outputWeights();
+      final float[] outputBias = model.outputBias();
+      for (int o = 0; o < outputSize; o++) {
+        final float[] weightRow = outputWeights[o];
+        double sum = outputBias[o];
+        for (int j = 0; j < hiddenSize; j++) {
+          sum += weightRow[j] * hidden[j];
+        }
+        probabilities[o] = sum;
+      }
+    }
+
+    /**
+     * Accumulates gradients for one decoded step: the weighted difference between the
+     * step's softmax and its chosen transition.
+     *
+     * @param features The step's input features.
+     * @param chosen The transition the path took at this step.
+     * @param weight The path's weight in the candidate distribution.
+     */
+    private void backward(int[] features, int chosen, double weight) {
+      forward(features);
+      double max = Double.NEGATIVE_INFINITY;
+      for (int o = 0; o < outputSize; o++) {
+        max = Math.max(max, probabilities[o]);
+      }
+      double normalizer = 0.0;
+      for (int o = 0; o < outputSize; o++) {
+        probabilities[o] = Math.exp(probabilities[o] - max);
+        normalizer += probabilities[o];
+      }
+      Arrays.fill(hiddenDelta, 0.0);
+      Arrays.fill(inputDelta, 0.0);
+      final float[][] outputWeights = model.outputWeights();
+      for (int o = 0; o < outputSize; o++) {
+        // dL/dlogit for a path's step under the conditional likelihood: the path weight
+        // times how the step's log-probability responds to this logit
+        final double delta =
+            weight * ((o == chosen ? 1.0 : 0.0) - probabilities[o] / normalizer);
+        outputBiasGradient[o] += delta;
+        final double[] gradientRow = outputGradient[o];
+        final float[] weightRow = outputWeights[o];
+        for (int j = 0; j < hiddenSize; j++) {
+          gradientRow[j] += delta * hidden[j];
+          hiddenDelta[j] += delta * weightRow[j];
+        }
+      }
+      final float[][] hiddenWeights = model.hiddenWeights();
+      for (int j = 0; j < hiddenSize; j++) {
+        final double preDelta = hiddenDelta[j] * CUBE_DERIVATIVE_FACTOR * pre[j] * pre[j];
+        hiddenBiasGradient[j] += preDelta;
+        final double[] gradientRow = hiddenGradient[j];
+        final float[] weightRow = hiddenWeights[j];
+        for (int k = 0; k < inputSize; k++) {
+          gradientRow[k] += preDelta * x[k];
+          inputDelta[k] += preDelta * weightRow[k];
+        }
+      }
+      for (int f = 0; f < features.length; f++) {
+        final double[] embeddingGradient = embeddingGradients
+            .computeIfAbsent(features[f], key -> new double[embeddingSize]);
+        final int offset = f * embeddingSize;
+        for (int d = 0; d < embeddingSize; d++) {
+          embeddingGradient[d] += inputDelta[offset + d];
+        }
+      }
+    }
+
+    /**
+     * Turns raw scores into log-probabilities in place.
+     *
+     * @param scores The raw scores, overwritten with their log-softmax.
+     */
+    private void logSoftmaxInPlace(double[] scores) {
+      double max = Double.NEGATIVE_INFINITY;
+      for (final double score : scores) {
+        max = Math.max(max, score);
+      }
+      double sum = 0.0;
+      for (final double score : scores) {
+        sum += Math.exp(score - max);
+      }
+      final double logSum = Math.log(sum);
+      for (int i = 0; i < scores.length; i++) {
+        scores[i] = (scores[i] - max) - logSum;
+      }
+    }
+  }
+
+  /**
+   * Reads a sample stream into memory; both trainers pass over the corpus repeatedly.
+   *
+   * @param samples The stream to drain.
+   * @return All samples in stream order. Never {@code null}.
+   * @throws IOException Thrown if reading the samples fails.
+   */
+  private static List<DependencySample> readAll(ObjectStream<DependencySample> samples)
+      throws IOException {
+    final List<DependencySample> corpus = new ArrayList<>();
+    DependencySample sample;
+    while ((sample = samples.read()) != null) {
+      corpus.add(sample);
+    }
+    return corpus;
+  }
+
+  /**
+   * Overwrites the random word rows with pretrained vectors where available.
+   *
+   * @param model The freshly initialized model whose word rows are seeded.
+   * @param pretrained The pretrained vector source, returning {@code null} for a word it
+   *                   does not cover.
+   * @param settings The hyperparameters, which fix the expected vector width.
+   * @throws IllegalArgumentException Thrown if a pretrained vector has a different width
+   *         than the embedding size or contains a non-finite value.
+   */
+  private static void seed(FeedforwardDependencyModel model,
+      Function<String, float[]> pretrained, Settings settings) {
+    int seeded = 0;
+    for (final Map.Entry<String, Integer> entry : model.wordIds().entrySet()) {
+      if (FeedforwardDependencyModel.isSpecialSymbol(entry.getKey())) {
+        // The special unknown, padding, and root symbols have no pretrained
+        // counterpart, so they keep their random initialization.
+        continue;
+      }
+      final float[] vector = pretrained.apply(entry.getKey());
+      if (vector == null) {
+        continue;
+      }
+      if (vector.length != settings.embeddingSize()) {
+        throw new IllegalArgumentException("pretrained vector for '" + entry.getKey()
+            + "' has " + vector.length + " dimensions, expected "
+            + settings.embeddingSize());
+      }
+      for (final float value : vector) {
+        if (!Float.isFinite(value)) {
+          throw new IllegalArgumentException(
+              "pretrained vector for '" + entry.getKey() + "' contains a non-finite value");
+        }
+      }
+      System.arraycopy(vector, 0, model.embeddings()[entry.getValue()], 0, vector.length);
+      seeded++;
+    }
+    logger.info("seeded {} of {} word embeddings from the pretrained source", seeded,
+        model.wordIds().size());
+  }
+
+  /**
+   * Builds the vocabularies and randomly initialized weights. A word, tag, or label in
+   * the training data that spells a reserved symbol shares the reserved row, as an
+   * unknown symbol does, so the reserved rows are never displaced.
+   *
+   * @param corpus The training samples.
+   * @param settings The hyperparameters.
+   * @return The untrained model. Never {@code null}.
+   * @throws IllegalArgumentException Thrown if the vocabularies and settings would
+   *         produce more model values than the model format can store.
+   */
+  private static FeedforwardDependencyModel initialize(List<DependencySample> corpus,
+      Settings settings) {
+    final Map<String, Integer> wordCounts = new HashMap<>();
+    final Map<String, Integer> tagIds = new HashMap<>();
+    final Map<String, Integer> labelIds = new HashMap<>();
+    final Map<String, Integer> transitionIds = new HashMap<>();
+    for (final DependencySample s : corpus) {
+      if (!ArcStandardOracle.isProjective(s.getGraph())) {
+        continue;
+      }
+      final List<Transition> oracle = ArcStandardOracle.transitions(s.getGraph());
+      for (final String token : s.getTokens()) {
+        wordCounts.merge(FeedforwardDependencyModel.normalize(token), 1, Integer::sum);
+      }
+      for (final String tag : s.getTags()) {
+        tagIds.putIfAbsent(tag, 0);
+      }
+      final DependencyGraph graph = s.getGraph();
+      for (int i = 0; i < graph.size(); i++) {
+        labelIds.putIfAbsent(graph.relationOf(i), 0);
+      }
+      for (final Transition transition : oracle) {
+        transitionIds.putIfAbsent(transition.encode(), 0);
+      }
+    }
+
+    int row = 0;
+    final Map<String, Integer> wordIds = new HashMap<>();
+    row = addSpecialSymbols(wordIds, row, FeedforwardDependencyModel.UNKNOWN,
+        FeedforwardDependencyModel.ABSENT, FeedforwardDependencyModel.ROOT_SYMBOL);
+    for (final Map.Entry<String, Integer> entry : wordCounts.entrySet()) {

Review Comment:
   Ids follow `HashMap` iteration order, while the transitions a few lines below are sorted. Line 43 promises deterministic training. Please sort the keys.



##########
opennlp-core/opennlp-runtime/src/main/java/opennlp/tools/depparse/ArcStandardState.java:
##########
@@ -0,0 +1,320 @@
+/*
+ * 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.tools.depparse;
+
+import java.util.Arrays;
+
+/**
+ * The mutable configuration of an arc-standard parse: a stack, a buffer of remaining
+ * tokens, and the arcs assigned so far. The arc-standard transition system is described
+ * in <a href="https://aclanthology.org/W04-0308/">Nivre (2004)</a>.
+ *
+ * <p>The stack bottom holds the artificial root, exposed as {@link #ROOT}. Positions that
+ * do not exist, such as the second stack element in the initial configuration, are exposed
+ * as {@link #NONE}. A right arc from the artificial root is only applicable once the buffer
+ * is empty and the root is the only other stack element, which guarantees every completed
+ * parse has exactly one sentence root.</p>
+ *
+ * <p>Instances are confined to a single parse and must not be shared between threads.</p>
+ *
+ * @since 3.0.0
+ */
+final class ArcStandardState {
+
+  /** The stack value representing the artificial root node. */
+  public static final int ROOT = -1;

Review Comment:
   `public` members on a package-private class. The `default` at 161 is unreachable.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opennlp.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OPENNLP-547: Add a transition-based dependency parser component (opennlp)

Posted by "krickert (via GitHub)" <gi...@apache.org>.
krickert commented on PR #1236:
URL: https://github.com/apache/opennlp/pull/1236#issuecomment-6068202309

   @mawiesne  - thank you for taking the time to review which has taught me so much in a short period of time.  I'll say with humility: the PR-pocolapse you dealt with required so much patience, and I can't tell ya enough of how much I appreciate your work and patience to lead through and keep the quality so high.  It's taught me a lot quickly - both technically and how to do things the apache way - and looking forward to further collaborations and contributions with the team.  
   
   I don't think I've had more fun with coding since I first compiled w/gcc via slackware linux for the first time in a dorm room :)


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opennlp.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OPENNLP-547: Add a dependency parser component (opennlp)

Posted by "krickert (via GitHub)" <gi...@apache.org>.
krickert commented on PR #1236:
URL: https://github.com/apache/opennlp/pull/1236#issuecomment-5575930251

   Evals passed for this, going to re-run it as I added double precision scoring.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opennlp.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OPENNLP-547: Add a dependency parser component (opennlp)

Posted by "mawiesne (via GitHub)" <gi...@apache.org>.
mawiesne commented on PR #1236:
URL: https://github.com/apache/opennlp/pull/1236#issuecomment-5489118560

   @krickert Can you rebase this one onto _main_? Currently changes show up here that are now already included in main.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opennlp.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OPENNLP-547: Add a dependency parser component (opennlp)

Posted by "krickert (via GitHub)" <gi...@apache.org>.
krickert commented on PR #1236:
URL: https://github.com/apache/opennlp/pull/1236#issuecomment-5751698337

   R4R @rzo1 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opennlp.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OPENNLP-547: Add a dependency parser component (opennlp)

Posted by "rzo1 (via GitHub)" <gi...@apache.org>.
rzo1 commented on PR #1236:
URL: https://github.com/apache/opennlp/pull/1236#issuecomment-5751312953

   @krickert Can you fixed up this branch plz? It has 147 commits and I don't think they belong here.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opennlp.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OPENNLP-547: Add a transition-based dependency parser (opennlp)

Posted by "krickert (via GitHub)" <gi...@apache.org>.
krickert commented on PR #1236:
URL: https://github.com/apache/opennlp/pull/1236#issuecomment-5988542201

   @rzo1  followed all the suggestions and agree with all of them.  Please check again


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opennlp.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OPENNLP-547: Add a dependency parser component (opennlp)

Posted by "krickert (via GitHub)" <gi...@apache.org>.
krickert commented on PR #1236:
URL: https://github.com/apache/opennlp/pull/1236#issuecomment-5565284731

   Eval build for this head (afd68fb1f) is running on Jenkins: https://ci-builds.apache.org/job/OpenNLP/job/eval-tests-configurable/74/ (eval-tests-configurable, branch OPENNLP-547-dependency-parser). It uses the opennlp-data.zip published on nightlies today and includes the new UniversalDependencyParserEval, so expect it to take longer than a regular eval run.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opennlp.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OPENNLP-547: Add a dependency parser component (opennlp)

Posted by "krickert (via GitHub)" <gi...@apache.org>.
krickert commented on PR #1236:
URL: https://github.com/apache/opennlp/pull/1236#issuecomment-5771323403

   I'm really excited about this one.  It's going to be a fun feature to have.  The front end is going to look really cool.  I'll rebase and mark r4r after it merges.  No rush and thank you - I know this one is a larger one.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opennlp.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OPENNLP-547: Add a transition-based dependency parser (opennlp)

Posted by "krickert (via GitHub)" <gi...@apache.org>.
krickert commented on PR #1236:
URL: https://github.com/apache/opennlp/pull/1236#issuecomment-5973512508

   > Can we rebase and make use of ArgumentChecker?
   
   Rebased onto main and switched the null checks to ArgumentChecks. The three combined checks now name the argument that was null.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opennlp.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OPENNLP-547: Add a transition-based dependency parser (opennlp)

Posted by "krickert (via GitHub)" <gi...@apache.org>.
krickert commented on code in PR #1236:
URL: https://github.com/apache/opennlp/pull/1236#discussion_r4180161456


##########
opennlp-api/src/main/java/opennlp/tools/depparse/DependencyGraph.java:
##########
@@ -0,0 +1,238 @@
+/*
+ * 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.tools.depparse;
+
+import java.io.Serial;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import opennlp.tools.commons.ThreadSafe;
+import opennlp.tools.util.ArgumentChecks;
+import opennlp.tools.util.StringUtil;
+
+/**
+ * An immutable dependency tree over one sentence: for every token, the index of its head
+ * and the label of the relation to that head.
+ *
+ * <p>Token indices are zero-based positions in the sentence the graph was built for.
+ * Exactly one token carries the head value {@link DependencyArc#ROOT_HEAD}, marking it as
+ * the sentence root. Instances are immutable and safe to share between threads.</p>
+ *
+ * @since 3.0.0
+ */
+@ThreadSafe
+public final class DependencyGraph implements Serializable {
+
+  @Serial
+  private static final long serialVersionUID = 5144949884365294061L;
+
+  /** Traversal state of a token whose head chain has not been followed yet. */
+  private static final byte UNVISITED = 0;
+
+  /** Traversal state of a token on the head chain currently being followed. */
+  private static final byte VISITING = 1;
+
+  /** Traversal state of a token whose head chain is known to reach the root. */
+  private static final byte VISITED = 2;
+
+  private final int[] heads;
+  private final String[] relations;
+  private final int root;
+
+  /**
+   * Wraps already validated arrays; instances are created through {@link #of}.
+   *
+   * @param heads The validated head array, owned by the new instance.
+   * @param relations The validated relation array, owned by the new instance.
+   * @param root The index of the single token whose head is {@link DependencyArc#ROOT_HEAD}.
+   */
+  private DependencyGraph(int[] heads, String[] relations, int root) {
+    this.heads = heads;
+    this.relations = relations;
+    this.root = root;
+  }
+
+  /**
+   * Creates a {@link DependencyGraph} from parallel head and relation arrays.
+   *
+   * @param heads For each token, the zero-based index of its head token, or
+   *              {@link DependencyArc#ROOT_HEAD} for the sentence root. Must not be
+   *              {@code null} or empty, every value must be a valid token index or
+   *              {@link DependencyArc#ROOT_HEAD}, no token may head itself, and exactly
+   *              one token must be the root.
+   * @param relations For each token, the label of the relation to its head. Must not be
+   *                  {@code null}, must have the same length as {@code heads}, and no
+   *                  entry may be {@code null} or blank.
+   * @return A validated {@link DependencyGraph}. Never {@code null}.
+   * @throws IllegalArgumentException Thrown if any of the above constraints is violated.
+   */
+  public static DependencyGraph of(int[] heads, String[] relations) {
+    ArgumentChecks.requireNonNullArg(heads, "heads");
+    ArgumentChecks.requireNonNullArg(relations, "relations");
+    if (heads.length == 0) {
+      throw new IllegalArgumentException("a dependency graph needs at least one token");
+    }
+    if (heads.length != relations.length) {
+      throw new IllegalArgumentException("heads and relations must have the same length: "
+          + heads.length + " != " + relations.length);
+    }
+    int roots = 0;
+    int root = DependencyArc.ROOT_HEAD;
+    for (int i = 0; i < heads.length; i++) {
+      if (heads[i] == DependencyArc.ROOT_HEAD) {
+        roots++;
+        root = i;
+      } else if (heads[i] < 0 || heads[i] >= heads.length) {
+        throw new IllegalArgumentException("head of token " + i
+            + " is out of range: " + heads[i]);
+      } else if (heads[i] == i) {
+        throw new IllegalArgumentException("token " + i + " must not head itself");
+      }
+      if (relations[i] == null || StringUtil.isBlank(relations[i])) {
+        throw new IllegalArgumentException("relation of token " + i + " must not be blank");
+      }
+    }
+    if (roots != 1) {
+      throw new IllegalArgumentException("expected exactly one root, found " + roots);
+    }
+    checkAcyclic(heads);
+    return new DependencyGraph(heads.clone(), relations.clone(), root);
+  }
+
+  /**
+   * Rejects a cycle that is disconnected from the single root by following every token's
+   * head chain until it reaches the root or a token already known to reach it.
+   *
+   * @param heads The head array, already checked for range, self-heads, and root count.
+   * @throws IllegalArgumentException Thrown if a head chain returns to a token on that
+   *         same chain.
+   */
+  private static void checkAcyclic(int[] heads) {
+    final byte[] states = new byte[heads.length];
+    for (int start = 0; start < heads.length; start++) {
+      int current = start;
+      while (current != DependencyArc.ROOT_HEAD && states[current] == UNVISITED) {
+        states[current] = VISITING;
+        current = heads[current];
+      }
+      if (current != DependencyArc.ROOT_HEAD && states[current] == VISITING) {
+        throw new IllegalArgumentException(
+            "dependency graph contains a cycle at token " + current);
+      }
+      current = start;
+      while (current != DependencyArc.ROOT_HEAD && states[current] == VISITING) {
+        states[current] = VISITED;
+        current = heads[current];
+      }
+    }
+  }
+
+  /**
+   * @return The number of tokens the graph spans.
+   */
+  public int size() {
+    return heads.length;
+  }
+
+  /**
+   * Retrieves the head of a token.
+   *
+   * @param index The zero-based token index. Must be within {@code [0, size())}.
+   * @return The zero-based index of the head token, or {@link DependencyArc#ROOT_HEAD}
+   *         when the token is the sentence root.
+   * @throws IllegalArgumentException Thrown if {@code index} is out of range.
+   */
+  public int headOf(int index) {
+    checkIndex(index);
+    return heads[index];
+  }
+
+  /**
+   * Retrieves the relation label of a token.
+   *
+   * @param index The zero-based token index. Must be within {@code [0, size())}.
+   * @return The label of the relation between the token and its head. Never {@code null}.
+   * @throws IllegalArgumentException Thrown if {@code index} is out of range.
+   */
+  public String relationOf(int index) {
+    checkIndex(index);
+    return relations[index];
+  }
+
+  /**
+   * @return The zero-based index of the sentence root token.
+   */
+  public int root() {
+    return root;
+  }
+
+  /**
+   * @return All arcs of the graph in token order, one per token. Never {@code null}.

Review Comment:
   done



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opennlp.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] OPENNLP-547: Add a transition-based dependency parser (opennlp)

Posted by "krickert (via GitHub)" <gi...@apache.org>.
krickert commented on code in PR #1236:
URL: https://github.com/apache/opennlp/pull/1236#discussion_r4180170272


##########
opennlp-api/src/main/java/opennlp/tools/depparse/DependencyGraph.java:
##########
@@ -0,0 +1,238 @@
+/*
+ * 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.tools.depparse;
+
+import java.io.Serial;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import opennlp.tools.commons.ThreadSafe;
+import opennlp.tools.util.ArgumentChecks;
+import opennlp.tools.util.StringUtil;
+
+/**
+ * An immutable dependency tree over one sentence: for every token, the index of its head
+ * and the label of the relation to that head.
+ *
+ * <p>Token indices are zero-based positions in the sentence the graph was built for.
+ * Exactly one token carries the head value {@link DependencyArc#ROOT_HEAD}, marking it as
+ * the sentence root. Instances are immutable and safe to share between threads.</p>
+ *
+ * @since 3.0.0
+ */
+@ThreadSafe
+public final class DependencyGraph implements Serializable {
+
+  @Serial
+  private static final long serialVersionUID = 5144949884365294061L;
+
+  /** Traversal state of a token whose head chain has not been followed yet. */
+  private static final byte UNVISITED = 0;
+
+  /** Traversal state of a token on the head chain currently being followed. */
+  private static final byte VISITING = 1;
+
+  /** Traversal state of a token whose head chain is known to reach the root. */
+  private static final byte VISITED = 2;
+
+  private final int[] heads;
+  private final String[] relations;
+  private final int root;
+
+  /**
+   * Wraps already validated arrays; instances are created through {@link #of}.
+   *
+   * @param heads The validated head array, owned by the new instance.
+   * @param relations The validated relation array, owned by the new instance.
+   * @param root The index of the single token whose head is {@link DependencyArc#ROOT_HEAD}.
+   */
+  private DependencyGraph(int[] heads, String[] relations, int root) {
+    this.heads = heads;
+    this.relations = relations;
+    this.root = root;
+  }
+
+  /**
+   * Creates a {@link DependencyGraph} from parallel head and relation arrays.
+   *
+   * @param heads For each token, the zero-based index of its head token, or
+   *              {@link DependencyArc#ROOT_HEAD} for the sentence root. Must not be
+   *              {@code null} or empty, every value must be a valid token index or
+   *              {@link DependencyArc#ROOT_HEAD}, no token may head itself, and exactly
+   *              one token must be the root.
+   * @param relations For each token, the label of the relation to its head. Must not be
+   *                  {@code null}, must have the same length as {@code heads}, and no
+   *                  entry may be {@code null} or blank.
+   * @return A validated {@link DependencyGraph}. Never {@code null}.
+   * @throws IllegalArgumentException Thrown if any of the above constraints is violated.
+   */
+  public static DependencyGraph of(int[] heads, String[] relations) {
+    ArgumentChecks.requireNonNullArg(heads, "heads");
+    ArgumentChecks.requireNonNullArg(relations, "relations");
+    if (heads.length == 0) {
+      throw new IllegalArgumentException("a dependency graph needs at least one token");
+    }
+    if (heads.length != relations.length) {
+      throw new IllegalArgumentException("heads and relations must have the same length: "
+          + heads.length + " != " + relations.length);
+    }
+    int roots = 0;
+    int root = DependencyArc.ROOT_HEAD;
+    for (int i = 0; i < heads.length; i++) {
+      if (heads[i] == DependencyArc.ROOT_HEAD) {
+        roots++;
+        root = i;
+      } else if (heads[i] < 0 || heads[i] >= heads.length) {
+        throw new IllegalArgumentException("head of token " + i
+            + " is out of range: " + heads[i]);
+      } else if (heads[i] == i) {
+        throw new IllegalArgumentException("token " + i + " must not head itself");
+      }
+      if (relations[i] == null || StringUtil.isBlank(relations[i])) {
+        throw new IllegalArgumentException("relation of token " + i + " must not be blank");
+      }
+    }
+    if (roots != 1) {
+      throw new IllegalArgumentException("expected exactly one root, found " + roots);
+    }
+    checkAcyclic(heads);
+    return new DependencyGraph(heads.clone(), relations.clone(), root);
+  }
+
+  /**
+   * Rejects a cycle that is disconnected from the single root by following every token's
+   * head chain until it reaches the root or a token already known to reach it.
+   *
+   * @param heads The head array, already checked for range, self-heads, and root count.
+   * @throws IllegalArgumentException Thrown if a head chain returns to a token on that
+   *         same chain.
+   */
+  private static void checkAcyclic(int[] heads) {
+    final byte[] states = new byte[heads.length];
+    for (int start = 0; start < heads.length; start++) {
+      int current = start;
+      while (current != DependencyArc.ROOT_HEAD && states[current] == UNVISITED) {
+        states[current] = VISITING;
+        current = heads[current];
+      }
+      if (current != DependencyArc.ROOT_HEAD && states[current] == VISITING) {
+        throw new IllegalArgumentException(
+            "dependency graph contains a cycle at token " + current);
+      }
+      current = start;
+      while (current != DependencyArc.ROOT_HEAD && states[current] == VISITING) {
+        states[current] = VISITED;
+        current = heads[current];
+      }
+    }
+  }
+
+  /**
+   * @return The number of tokens the graph spans.
+   */
+  public int size() {
+    return heads.length;
+  }
+
+  /**
+   * Retrieves the head of a token.
+   *
+   * @param index The zero-based token index. Must be within {@code [0, size())}.
+   * @return The zero-based index of the head token, or {@link DependencyArc#ROOT_HEAD}
+   *         when the token is the sentence root.
+   * @throws IllegalArgumentException Thrown if {@code index} is out of range.
+   */
+  public int headOf(int index) {
+    checkIndex(index);
+    return heads[index];
+  }
+
+  /**
+   * Retrieves the relation label of a token.
+   *
+   * @param index The zero-based token index. Must be within {@code [0, size())}.
+   * @return The label of the relation between the token and its head. Never {@code null}.
+   * @throws IllegalArgumentException Thrown if {@code index} is out of range.
+   */
+  public String relationOf(int index) {
+    checkIndex(index);
+    return relations[index];
+  }
+
+  /**
+   * @return The zero-based index of the sentence root token.
+   */
+  public int root() {
+    return root;
+  }
+
+  /**
+   * @return All arcs of the graph in token order, one per token. Never {@code null}.
+   */
+  public List<DependencyArc> arcs() {
+    final List<DependencyArc> arcs = new ArrayList<>(heads.length);
+    for (int i = 0; i < heads.length; i++) {
+      arcs.add(new DependencyArc(heads[i], i, relations[i]));
+    }
+    return Collections.unmodifiableList(arcs);
+  }
+
+  /**
+   * Rejects a token index outside {@code [0, size())}.
+   *
+   * @param index The zero-based token index to check.
+   * @throws IllegalArgumentException Thrown if {@code index} is out of range.
+   */
+  private void checkIndex(int index) {
+    if (index < 0 || index >= heads.length) {
+      throw new IllegalArgumentException("token index out of range: " + index
+          + ", size: " + heads.length);
+    }
+  }
+
+  @Override
+  public boolean equals(Object obj) {
+    if (this == obj) {
+      return true;
+    }
+    if (!(obj instanceof DependencyGraph other)) {
+      return false;
+    }
+    return Arrays.equals(heads, other.heads) && Arrays.equals(relations, other.relations);
+  }
+
+  @Override
+  public int hashCode() {
+    return 31 * Arrays.hashCode(heads) + Arrays.hashCode(relations);

Review Comment:
   The hash is cached at creation now.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@opennlp.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org