← Back to Pull requests

Only zero and accumulate split-feature columns in CPU SHAP contributions #12823

Closed
unknown closed this pull request without merging on Nov 10, 2026 09:55 UTC
View on GitHub
unknown unknown commented on Nov 09, 2026 19:42 UTC
Author

What

CPU pred_contribs=True (QuadratureTreeSHAP) zeroed and accumulated every feature column for every row and every tree. A tree only writes to the features it splits on, because AdditiveContributionFormulation::HandleReturn only adds to phi[split_index]. This PR builds each tree's sorted, unique split features once per call and zeroes and accumulates only those columns.

Why

On wide data, that per-tree pass over all columns was most of the work. A text model with 38,563 TF-IDF features and 20 classes swept 38,563 columns × 2,000 trees for every row, while each depth-6 tree splits on at most 63 features.

Median predict(..., pred_contribs=True) time, 100-round multi:softprob hist models, same model file and input on both sides:

| Case | Environment | Pairs | Base | Branch |
|---|---|---:|---:|---:|
| 20 newsgroups TF-IDF, 38,563 features, 20 classes, 200 rows | macOS arm64, 12 threads | 6 | 0.272 s | 0.037 s |
| same | Linux arm64 Docker VM, 4 CPU / 8 GiB | 6 | 0.576 s | 0.053 s |
| MNIST, 784 features, 10 classes, 2,000 rows | macOS arm64 | 6 | 0.105 s | 0.087 s |
| same | Linux arm64 Docker VM | 6 | 0.214 s | 0.159 s |
| covertype, 54 features, 7 classes, 20,000 rows | macOS arm64 | 6 | 2.61 s | 2.56 s |
| same | Linux arm64 Docker VM | 4 runs of 6-8 | no measurable change | |

Peak RSS is unchanged (1,985 → 1,981 MiB on macOS for the text case, 1,844 MiB on both sides on Linux). On covertype the four Linux runs gave −16%, +12%, +4% and −4% for the branch, so the VM noise was larger than any effect there. The Linux VM runs on the same Apple Silicon Mac, not bare-metal Linux.

Numerical behavior

Every column still gets the same operations, in the same tree order. The skipped work was p += 0.0f weight on columns the tree never writes.

  • clang (macOS): the full output is bit-identical for all three cases above, and for small DART (tree weights ≠ 1), categorical, multi_output_tree, pruned (gamma), base_margin and iteration_range models.

  • GCC (Linux): 0.6-1.2% of the output values differ in the last bits (max abs diff 2e-6; row sums agree within 3e-6). Built with -ffp-contract=off, base and branch are bit-identical, so the difference comes from where GCC fuses multiply-adds, not from the change in logic. The base output already differs bitwise between the clang and GCC builds.

  • Non-finite tree weights: before, a DART tree weight of inf or nan turned every column of the row into nan (0 inf). Now only that tree's split columns get it. Finite weights are what DART produces; I only hit this with a hand-edited model.
  • pred_interactions does not build or use the new lists. approx_contribs=True (ApproxFeatureImportance) has the same full-width loop; I left it for a follow-up to keep this PR small.

    How to test

    pytest tests/python/test_interpret.py tests/python/test_shap.py tests/python/test_multi_target.py: 73 passed. I did not build the C++ gtests locally; tests/cpp/predictor/test_shap.cc checks that contributions sum to the margin.

    <details><summary>Benchmark script</summary>

    # python shap_bench.py <case>: median of 5 pred_contribs calls on a saved model and input
    import sys, time, hashlib, numpy as np, scipy.sparse as sp, xgboost as xgb
    
    case = sys.argv[1]
    X = sp.load_npz(f"shap_input_{case}.npz") if case == "news" else np.load(f"shap_input_{case}.npy")
    bst = xgb.Booster(model_file=f"shap_model_{case}.ubj")
    d = xgb.DMatrix(X)
    bst.predict(xgb.DMatrix(X[:5]), pred_contribs=True)
    ts = []
    for _ in range(5):
        t = time.perf_counter()
        out = bst.predict(d, pred_contribs=True)
        ts.append(time.perf_counter() - t)
    print(case, f"median {np.median(ts):.4f}", "sha", hashlib.sha256(out.tobytes()).hexdigest()[:12])
    

    Models: xgb.train({"objective": "multi:softprob", "num_class": k, "tree_method": "hist", "max_depth": d, "seed": 0}, ..., 100) with max_depth 6 (news, MNIST) or 8 (covertype). News: TfidfVectorizer(min_df=3, stop_words="english") on the 20 newsgroups train split, scoring the first 200 test documents. MNIST: first 20,000 rows to train, rows 60,000-62,000 to score. Covertype: first 100,000 rows to train, rows 100,000-120,000 to score.

    </details>

    Risk

    Low. If a future contribution formulation writes to columns other than the tree's split features, those writes would be dropped; the sum-to-margin tests would catch a missing column. Revert by restoring the two full-width loops in QuadratureTreeShapValues.

    Diff: 561 lines (+420 / -141) across 7 files Reviewer: RAMitchell Review duration: 852m
    All Vouch review confidence checks passed
    Residual risk 0.20 = Change Risk (0.50) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.50 · 561 lines diff across 7 files
    0.50
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.379
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #12823"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 49.7% (MEDIUM) · Higher = larger blast radius
    49.7%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 19.6% · Safe to merge
    19.6%
    Repository