You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Reduce Digits DecisionTree predictive disparity and compare learned tree structure #204
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.
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.
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.
#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.
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.
Per-node impurity and sample counts. Emitted only for the root today. preorder_impurities and preorder_n_samples would follow the same pattern
and would tell you whether node 4 is a genuine tie or a real disagreement about
which split is better.
Tie-breaking._build_classifier_tree keeps the first split with strictly
lower weighted impurity, scanning features 0..n_features and, within a feature,
ascending sorted values. sklearn's BestSplitter shuffles the feature order
using random_state and applies its own tie rule. Node 4 is the place to check
whether the two candidate splits are impurity-tied. Nothing emitted yet
measures that.
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.
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:
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.
"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:
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.
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.
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.
Activity
godofecht commentedon Aug 18, 2026
Triage: still open, nothing has landed
Verified against the frozen canonical evidence on
main(c1e01df).benchmarks/disparity_report.json, digits DecisionTree accuracy:score_abs_diffis0.019444424000000016, unchanged from the ~0.0194 figure this issue was filed against.final_parity_statusandstrict_diagnostic_statusare both "approximately equivalent".runtime_ratio_sklearn_over_flowis0.2112, so Flow is about 4.7x slower on this row.model_state_diagnosticsfor this row is empty{}. The row contributes nothing torows_with_model_state_diagnostics, which stands at 3 of 19.benchmarks/bench_flow_v2.flowemitsDETAIL|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.Remaining work: emit per-node structure (node count, depth, split feature, threshold, impurity, weighted sample count, leaf class distribution) as
DETAIL|records frombench_flow_v2.flowand the matching sklearn side inbench_sklearn_v2.py, add a comparison ingenerate_disparity_report.pythat 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.godofecht commentedon Aug 18, 2026
#207 is done for this row. PR #402 adds tree-structure
DETAIL|emission on bothsides and the pairing logic that turns it into
model_state_diagnostics.What you can now read straight out of
disparity_report.jsonDigits DecisionTree,
score_abs_diffstill 0.019444424:n_nodesn_leavesmax_depth_reachedroot_split_feature/root_split_thresholdroot_impuritydepth1_splitsnodes_per_depthmean_leaf_depthsplit_feature_histogram_max_abs_diffThe first structural divergence
Both trees emit
preorder_split_featuresandpreorder_split_thresholdsforevery node. Node ids are assigned parent-before-children, left subtree first, in
_build_classifier_treeand in sklearn'sDepthFirstTreeBuilder, so indexinames the same position in both trees. The report records
preorder_split_features_first_divergent_index.For Digits it is 4:
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_diffof 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
TreeNode.valueis only written on leaves andfeature/thresholdonly on internal nodes, and the array comes frommalloc(Tree nodes are malloc'd without initialisation, so unwritten fields hold nondeterministic garbage #359), so the unwritten fields hold heap garbage that differs run to run.
Nothing in feat: learned-state diagnostics for every canonical benchmark row (3/19 -> 19/19) #402 reads them. Leaf predictions stay uncovered until Tree nodes are malloc'd without initialisation, so unwritten fields hold nondeterministic garbage #359 lands;
after that, adding
preorder_leaf_valuesis a two-line change alongside theexisting preorder vectors.
preorder_impuritiesandpreorder_n_sampleswould follow the same patternand would tell you whether node 4 is a genuine tie or a real disagreement about
which split is better.
_build_classifier_treekeeps the first split with strictlylower weighted impurity, scanning features 0..n_features and, within a feature,
ascending sorted values. sklearn's
BestSplittershuffles the feature orderusing
random_stateand applies its own tie rule. Node 4 is the place to checkwhether the two candidate splits are impurity-tied. Nothing emitted yet
measures that.
fitted numeric;
score_abs_diffis unchanged at 0.019444424 by design.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.pyThe disparity job on
mainwill pick this up oncefreeze-resultsrefreshes thecommitted
flow_results_v2.txtandsklearn_results_v2.txt.godofecht commentedon Aug 19, 2026
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 gini0.66.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_treescans features0..X.cols-1in fixed order and keeps a candidate only on strictweighted < best_impurity. Lowest feature index wins a tie. Feature 3 is the lowest of the six.sklearn's
BestSplitterdraws features through a Fisher-Yates shuffle from the splitter'srand_rstate, seeded offrandom_state, and keeps a candidate only on strict>on proxy improvement. First drawn among equals wins. Withrandom_state=42that happened to be feature 46.Both sides consider the identical candidate set, since
max_features=Nonefor a plainDecisionTreeClassifier. 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_stateover 0..59, holding data and every hyperparameter fixed: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:
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 recorded0.833333313. Swapping only its tie-break to a random feature permutation, over 60 seeds:The two distributions are the same distribution. The tracked
score_abs_diffof 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:
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.
"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_rxorshift reproduced bit for bit, seeded fromnp.random.RandomState(42).randint(0, RAND_R_MAX), plus the exact number of draws consumed at every node, which depends on sklearn'sn_drawn_constants/n_found_constants/n_known_constantsconstant-feature bookkeeping inside the split loop. That couplestree.flowto sklearn's private RNG internals, andtree.flowis 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:
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) withStandardScalerfit on train,max_depth=10, matchingbench_sklearn_v2.pyandbench_flow_v2.flow.godofecht commentedon Aug 19, 2026
PR #426 opened: documentation of the tie-break rule plus
tests/test_tree_split_tiebreak.flowto pin it. No behavioural change, all 19 canonical RESULT rows and all 146 DETAIL records byte-identical toorigin/main.Same diagnosis applies to #205; cross-referenced there.
docs: document the tree split tie-break rule and pin it with a test
godofecht commentedon Aug 19, 2026
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: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:
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_stateover 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_indexis reported (#402). The tie-break rule is now recorded intree.flowand pinned bytests/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_rxorshift bit for bit plus then_drawn_constants/n_found_constants/n_known_constantsbookkeeping that sets the draw count per node.tree.flowis 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.