Skip to content

Reduce Digits DecisionTree predictive disparity and compare learned tree structure #204

Closed

Description

@godofecht

Parent: #202

Problem

The canonical Digits DecisionTree row is parity-eligible but still has an absolute accuracy disparity of roughly 0.0194 in the current diagnostic artifact. Final-score eligibility alone does not explain why the learned trees differ.

Work

Instrument both implementations to persist and compare:

  • node count and depth
  • split feature and threshold per node
  • impurity and sample counts
  • leaf predictions/class distributions
  • tie-breaking behavior
  • feature iteration/order semantics
  • stopping/min-samples/max-depth behavior

Identify the earliest structural divergence on the canonical split.

Align sklearn semantics where the difference is accidental. If an intentional Flow choice remains, document it explicitly and benchmark both variants.

Acceptance criteria

A deterministic regression identifies the first structural divergence between the canonical sklearn and Flow trees.

The predictive disparity is materially reduced from the current ~0.0194 absolute accuracy gap without widening the existing parity tolerance.

disparity_report.json includes tree-structure/model-state diagnostics for this row so future regressions remain visible.

Activity

  1. godofecht commented on Aug 18, 2026

    @godofecht
    OwnerAuthor

    Triage: still open, nothing has landed

    Verified against the frozen canonical evidence on main (c1e01df).

    • benchmarks/disparity_report.json, digits DecisionTree accuracy: score_abs_diff is 0.019444424000000016, unchanged from the ~0.0194 figure this issue was filed against. final_parity_status and strict_diagnostic_status are both "approximately equivalent". runtime_ratio_sklearn_over_flow is 0.2112, so Flow is about 4.7x slower on this row.
    • model_state_diagnostics for this row is empty {}. The row contributes nothing to rows_with_model_state_diagnostics, which stands at 3 of 19.
    • The cause is upstream: benchmarks/bench_flow_v2.flow emits DETAIL| records only for KMeans and PCA. There is no node count, depth, split feature, threshold, impurity, sample count or leaf distribution emitted by either implementation, so there is no artifact to compare.
    • No merged PR touches decision-tree structure comparison. The infrastructure from PR Expose canonical learned-state diagnostic coverage #331 can carry these diagnostics once they are emitted; it does not produce them.

    Remaining work: emit per-node structure (node count, depth, split feature, threshold, impurity, weighted sample count, leaf class distribution) as DETAIL| records from bench_flow_v2.flow and the matching sklearn side in bench_sklearn_v2.py, add a comparison in generate_disparity_report.py that reports the first structurally divergent node in a deterministic pre-order walk, then reconcile the accidental differences (feature iteration order and split tie-breaking are the usual suspects) to bring the 0.0194 gap down without touching the tolerance.

  2. godofecht commented on Aug 18, 2026

    @godofecht
    OwnerAuthor

    #207 is done for this row. PR #402 adds tree-structure DETAIL| emission on both
    sides and the pairing logic that turns it into model_state_diagnostics.

    What you can now read straight out of disparity_report.json

    Digits DecisionTree, score_abs_diff still 0.019444424:

    Field Flow sklearn
    n_nodes 245 245
    n_leaves 123 123
    max_depth_reached 10 10
    root_split_feature / root_split_threshold 36 / -1.67066383 36 / -1.67066377
    root_impurity 0.899978638 0.899978644
    depth1_splits 28 @ -0.873653173, 21 @ -1.19120884 28 @ -0.873653173, 21 @ -1.19120878
    nodes_per_depth 1,2,4,8,16,24,30,34,42,46,38 1,2,4,8,16,24,30,34,44,44,38
    mean_leaf_depth 7.59777308 7.59707724
    split_feature_histogram_max_abs_diff 24

    The first structural divergence

    Both trees emit preorder_split_features and preorder_split_thresholds for
    every node. Node ids are assigned parent-before-children, left subtree first, in
    _build_classifier_tree and in sklearn's DepthFirstTreeBuilder, so index i
    names the same position in both trees. The report records
    preorder_split_features_first_divergent_index.

    For Digits it is 4:

    node          0        1        2        3        4
    flow      36        28       21        5        3   @ -1.72580624
    sklearn   36        28       21        5       46   @ -0.692062497
    

    Nodes 0 through 3 are identical to float32 print precision. Node 4 is where they
    part: Flow picks feature 3 with threshold -1.7258, sklearn picks feature 46 with
    threshold -0.6921. Everything downstream of that node is a consequence.

    For Iris the index is -1: the two trees are structurally identical, which is
    consistent with that row's score_abs_diff of 4e-09.

    That is the deterministic first-divergence identification your acceptance
    criteria asked for, and it is now regenerated on every disparity run.

    What is still missing for this issue

    Reproducing

    FLOW_HEADLINE_COMMAND="flow run benchmarks/bench_flow_v2.flow" \
      python benchmarks/run_headline.py --repeats 3
    cp benchmarks/headline_summary.json benchmarks/headline_result_v2.json
    python benchmarks/generate_disparity_report.py

    The disparity job on main will pick this up once freeze-results refreshes the
    committed flow_results_v2.txt and sklearn_results_v2.txt.

  3. godofecht commented on Aug 19, 2026

    @godofecht
    OwnerAuthor

    Diagnosis: node 4 is a tie, not an error

    Using the DETAIL| first-divergence pointer from #402 (digits agrees on nodes 0-3, diverges at node 4). Of the four candidate causes, this is cause 1: tie-breaking among equally good splits. Nothing is wrong in either implementation.

    The numbers at node 4

    Node 4 holds 10 training samples with labels [2 4 6 4 4 0 4 4 2 6]. Parent gini 0.66.

    candidate best weighted gini (f64) (f32) threshold n_left impurity decrease
    feature 3 (Flow's pick) 0.31999999999999995 0.32 -1.7258062 5 0.34
    feature 46 (sklearn's pick) 0.31999999999999995 0.32 -0.6920625 5 0.34

    Identical to the last bit in float64 and in float32. Six features reach that same minimum at this node: 3, 29, 37, 41, 45, 46.

    Both thresholds are the correct midpoint of the relevant consecutive distinct sorted pair for their own feature. Feature 3 sorted: [-2.552 -2.552 -2.552 -2.316 -1.844 | -1.608 -0.664 0.281 0.517 0.753], midpoint -1.72580 . Feature 46 sorted: [-0.8098 x5 | -0.5744 -0.1035 -0.1035 0.1319 0.3673], midpoint -0.69206. So candidate 3 (threshold placement) is clean, and candidate 4 (impurity calculation) is clean.

    Why the two sides break the tie differently

    lib/scikit/tree.flow:_build_classifier_tree scans features 0..X.cols-1 in fixed order and keeps a candidate only on strict weighted < best_impurity. Lowest feature index wins a tie. Feature 3 is the lowest of the six.

    sklearn's BestSplitter draws features through a Fisher-Yates shuffle from the splitter's rand_r state, seeded off random_state, and keeps a candidate only on strict > on proxy improvement. First drawn among equals wins. With random_state=42 that happened to be feature 46.

    Both sides consider the identical candidate set, since max_features=None for a plain DecisionTreeClassifier. The permutation changes nothing except tie order. So candidate 2 (candidate ordering/subsampling) is the mechanism, and it only bites because of the tie.

    Confirmation from sklearn itself

    Sweeping only sklearn's random_state over 0..59, holding data and every hyperparameter fixed:

    node-4 split feature across seeds: [-2, 3, 29, 37, 41, 45, 46]
    

    sklearn's own node 4 lands on exactly the six-feature tied set my scan computed, and picks feature 3 (Flow's answer) for one of those seeds. Test accuracy over the same sweep:

    sklearn, random_state 0..59:   min 0.811111  max 0.844444  mean 0.826574  std 0.008324
                                   random_state=42 -> 0.813889
    

    A faithful Python replica of the Flow builder (f32 arithmetic, first-appearance class order, fixed feature order, strict <, f32 midpoint) reproduces the shipped Flow tree exactly: 245 nodes, node 4 = feature 3 @ -1.7258062, accuracy 0.833333 against the recorded 0.833333313. Swapping only its tie-break to a random feature permutation, over 60 seeds:

    flow builder, permuted tie-break: min 0.811111  max 0.847222  mean 0.827407  std 0.008279
    

    The two distributions are the same distribution. The tracked score_abs_diff of 0.019444424 is 2.3 standard deviations of tie-break noise, and both endpoints sit inside the range each implementation reaches on its own by changing nothing but a seed.

    How widespread the ties are

    Census over the digits tree, counting features that attain the exact f32 minimum weighted gini at each split node:

    internal (split) nodes: 122
    nodes with >1 feature at the minimum: 68  (55.7%)
    tie multiplicity: mean 9.74, max 48
    

    Node 4 is not special. It is the first node where the two tie-break rules happened to disagree. Node 3 is also a tie (features 5, 6, 53, 60, 61) and both sides happened to land on 5.

    Direction of the disparity

    Worth stating plainly: Flow is the more accurate of the two on this row.

    DecisionTree digits   flow 0.833333313   sklearn 0.813888889   (flow +0.019444424)
    RandomForest digits   flow 0.955555558   sklearn 0.936111111   (flow +0.019444447)
    

    "Reducing the disparity" here means moving Flow's digits accuracy down to sklearn's, by adopting sklearn's tie-break. That would not fix a defect. It would trade one arbitrary choice among mathematically identical splits for another arbitrary choice that scores worse on this particular test split.

    Is it fixable

    Matching sklearn exactly is possible in principle and expensive in practice. It needs sklearn's our_rand_r xorshift reproduced bit for bit, seeded from np.random.RandomState(42).randint(0, RAND_R_MAX), plus the exact number of draws consumed at every node, which depends on sklearn's n_drawn_constants / n_found_constants / n_known_constants constant-feature bookkeeping inside the split loop. That couples tree.flow to sklearn's private RNG internals, and tree.flow is shared with RandomForest and the Bagging estimators, so #205's row moves with it.

    Per the constraint in this issue's brief, I am not shipping a change that moves the metric without a defect behind it. Recommendation:

    1. Close Reduce Digits DecisionTree predictive disparity and compare learned tree structure #204 as diagnosed rather than fixed, or requalify it as "document the tie-break rule and record the tied-feature evidence".
    2. Same conclusion applies to Reduce Digits RandomForest disparity and align bootstrap / per-tree randomness #205: 0.019444447 on RandomForest digits is the same phenomenon in the same shared builder.
    3. If per-node structural parity with sklearn is genuinely wanted later, it is a deliberate, separately-benchmarked port of sklearn's feature-permutation RNG, not a tweak to the comparison operator.

    The acceptance criterion "a deterministic regression identifies the first structural divergence" is already met by #402. The criterion "the predictive disparity is materially reduced" is not reachable without making Flow's digits tree worse on purpose.

    Method: everything above comes from the canonical fixture split (benchmarks/split_indices.json) with StandardScaler fit on train, max_depth=10, matching bench_sklearn_v2.py and bench_flow_v2.flow.

  4. godofecht commented on Aug 19, 2026

    @godofecht
    OwnerAuthor

    PR #426 opened: documentation of the tie-break rule plus tests/test_tree_split_tiebreak.flow to pin it. No behavioural change, all 19 canonical RESULT rows and all 146 DETAIL records byte-identical to origin/main.

    Same diagnosis applies to #205; cross-referenced there.

  5. godofecht commented on Aug 19, 2026

    @godofecht
    OwnerAuthor

    Closing as diagnosed. The disparity is real, explained, and in Flow's favour, so reducing it would mean making flow-scikit worse.

    What the numbers actually say

    From the committed headline_result_v2.json:

    Flow sklearn
    DecisionTree / digits 0.833333313 0.813888889

    The tracked 0.019444424 is Flow scoring higher. This issue asks to reduce it.

    Why the trees differ

    Using the per-node diagnostics from #402, the first divergent node on Digits is node 4. Both implementations are correct:

    • Node 4 holds 10 samples, parent gini 0.66.
    • Flow picks feature 3 at threshold -1.7258; sklearn picks feature 46 at -0.6921.
    • Both give weighted gini 0.31999999999999995 in f64 and 0.32 in f32. Identical.
    • Six features reach that exact minimum: 3, 29, 37, 41, 45, 46.

    Flow scans features in index order with a strict <, so the lowest index wins. sklearn draws candidates through a Fisher-Yates permutation off its splitter RNG, so the first drawn among equals wins. Ties are the normal case here, not an edge case: 68 of 122 split nodes have more than one feature at the exact f32 minimum, mean multiplicity 9.74, max 48.

    The gap is tie-break noise, quantified

    Sweeping only sklearn's random_state over 0..59 moves node 4's split across exactly the tied set and gives accuracy 0.811111 to 0.844444, mean 0.826574, std 0.008324. Seed 42 gives 0.813889.

    The tracked 0.019444424 is 2.3 standard deviations of tie-break noise. A float32-faithful replica of Flow's builder, with only its tie-break swapped for a random permutation, reproduces the same distribution.

    What was delivered

    The documentation half of this issue is satisfied. Per-node structure is emitted, node ids align across implementations parent-before-children left-subtree-first, and <field>_first_divergent_index is reported (#402). The tie-break rule is now recorded in tree.flow and pinned by tests/test_tree_split_tiebreak.flow (#426), which fails if anyone reorders the scan or relaxes < to <=.

    What was deliberately not done

    Matching sklearn exactly would require reproducing its our_rand_r xorshift bit for bit plus the n_drawn_constants / n_found_constants / n_known_constants bookkeeping that sets the draw count per node. tree.flow is shared, so #205 would move with it. That is substantial machinery to make a benchmark row agree by becoming less accurate.

    Closing as diagnosed rather than fixed. If the goal is ever restated as "make the trees structurally identical to sklearn" rather than "reduce the disparity", that is a different and legitimate issue, and this comment is the starting point for it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions