Skip to content

perf(kumo-pytorch): avoid per-anchor reconstruction for inspectable graphs - #340

Merged
am-porter merged 2 commits into
mainfrom
codex/kumo-pytorch-inspectable-performance
Nov 17, 2026
Merged

am-porter merged 2 commits into
mainfrom
codex/kumo-pytorch-inspectable-performance

Conversation

@am-porter

@am-porter am-porter commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Graph-only serving through Task.batches(output_format="inspectable") rebuilt Python requests and history objects after native sampling had already produced the graph. Timestamp conversion also repeatedly attempted to import optional pytz. This change resolves timezones once per column and reuses typed native assembly for eligible fixed-size inspectable graph batches.

The route requires one graph input, one selected native stage, and no additional retrieval/target/availability declarations. Other inspectable contracts retain their existing route; explicit model output still refuses unsupported Raw fields. No public API or batch shape changes.

Rebased onto main 2f7171fc. The rebase preserves main's lossless nanosecond timestamp representation, typed external targets, and native token-budget batching. Fractional nanoseconds remain Arrow scalars without requiring pandas.

Performance evidence

The original matched benchmark at c458c2e, using the same freshly rebuilt DiskGraph wheel from base ffd51069 for main and candidate, reduced the 10,000-seed payload from 834 ms to 134 ms (6.2×) with identical bytes. These are historical measurements, not new measurements of the refreshed head.

Seeds Original main, ms Original candidate, ms Direct native, ms
1 3.184 3.091 1.359
128 12.125 4.864 3.053
1,000 73.133 16.219 13.613
10,000 834.419 134.430 120.803

Same AMD EPYC 9654P host, frozen 20,000-event one-hop fixture, two sampler threads, one warmup and seven full-payload draws; preparation/materialization excluded. All four hashes matched main, candidate and direct native. The candidate remained about 11% slower than direct native at 10,000 seeds. The one-seed case changed little.

Original benchmark environment: Python 3.11.17, Arrow 24.0.0, NumPy 2.4.6, DuckDB 2.0.0, CPU PyTorch 2.15.0.

Testing Done

Head 0fffd73b, rebased onto main 2f7171fc, macOS arm64 / Python 3.12.13 / Arrow 24.0.0 / NumPy 2.5.4 / PyTorch 2.15.0 / pytz 2026.6:

  • Full package suite against main 9c9cba53 plus this change and a freshly rebuilt DiskGraph wheel: 2,372 passed, 7 skipped, 3 deselected; spawned-worker tests included.
  • After incorporating main's subsequent Python-only padding fix (2f7171fc), output and inspectable regression suites: 81 passed on the final head. Native sources are unchanged between those main revisions.
  • Reproduced CodeRabbit's timezone-oracle issue with pytz installed: the original test fails all four America/New_York timestamp units; the corrected inspectable suite passes all 33 cases. Expected values are now computed after blocking pytz, and the import counter is cleared before measuring the optimized conversion.
  • Package Ruff check/format, repository license-header check, Python/native wheel builds and git diff --check pass.
  • Native wheel SHA-256: a24467eb9d41edd5c132892929596dba83bf6f2e63c1d892cc997cd86651f612.
  • Historical performance measurements were not rerun.

Change map

Maintained change map.

Checklist

  • No breaking API changes.
  • Existing model validation and unsupported-contract fallbacks preserved.
  • Regression coverage for exact graph output and timestamp precision.

@copy-pr-bot

copy-pr-bot Bot commented Nov 14, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@am-porter
am-porter temporarily deployed to gha-kumo-workflow-tests November 14, 2026 00:56 — with GitHub Actions Inactive
@coderabbitai

coderabbitai Bot commented Nov 14, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

A shared Arrow column conversion helper handles null-only columns and timezone-aware timestamps while preserving nanosecond precision. Metadata and request extraction use this helper. Native fixed-size batching now supports eligible inspectable graph output. Model-contract validation applies only to model output. Tests cover timestamp conversion, batching parity, and configurations that retain request-based batching.

Sequence Diagram(s)

sequenceDiagram
  participant native_anchors
  participant _can_batch_inspectable_graph
  participant _typed_batches
  participant NativeCollator
  native_anchors->>_can_batch_inspectable_graph: Check inspectable graph eligibility
  _can_batch_inspectable_graph-->>native_anchors: Return eligibility
  native_anchors->>_typed_batches: Pass output_format for eligible fixed batches
  _typed_batches->>NativeCollator: Collate typed buffers and Arrow Raw fields
Loading
Security architecture risk: Minimal · up to 0fffd

No introduced or worsened risk materially affecting security, isolation, rollback, or ownership guarantees was established in the inspected change.

Pre-merge checks: Passed 2 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Change Map Design Review Warning The change map (<!-- kumo-pr-change-map -->, comment 6868907169, fetched via the GitHub API) gives a plausible problem statement, a stated stopping condition, and historical benchmarks. Its design s… Revise the change map and, where needed, the implementation: - Add a row or note for _can_batch_inspectable_graph. State the eligibility gate exactly as coded, including the output_format, single-stage, one-Graph-input, and fixed cond…
Passed Passed checks: 2 passed

Check name Status Explanation
Pr Size Passed The PR size check counts changed files and fails only above 40. The changed-file inventory for the review range (`git diff --name-status refs/coderabbit/pre-merge-check/base refs/coderabbit/pre-merge-…
Public Resource Access Passed The check applies only to external resource references (URLs, repository locations, package source locations) that this PR adds or modifies. The PR changes two files: `packages/experimental/kumo-pytor…
Full details: Pr Size

Explanation

The PR size check counts changed files and fails only above 40. The changed-file inventory for the review range (git diff --name-status refs/coderabbit/pre-merge-check/base refs/coderabbit/pre-merge-check/head) lists 2 files: - M packages/experimental/kumo-pytorch/src/kumo/pytorch/engines/native_anchors.py - A packages/experimental/kumo-pytorch/tests/test_inspectable_graph_batches.py Both --name-status and --name-only agree on a count of 2. This is below the threshold of 40, so the check passes. Line counts are ignored, as the check requires.

Full details: Public Resource Access

Explanation

The check applies only to external resource references (URLs, repository locations, package source locations) that this PR adds or modifies. The PR changes two files: packages/experimental/kumo-pytorch/src/kumo/pytorch/engines/native_anchors.py (modified) and packages/experimental/kumo-pytorch/tests/test_inspectable_graph_batches.py (added). I scanned all 305 added diff lines for http(s)://, git+, git@, github.com, package index names, pip install, file://, ssh://, archive/wheel suffixes, registry, S3/GCS, and Docker references. None matched. No dependency manifests, lockfiles, CI configs, or docs with links were changed. The PR therefore adds or changes no external resource reference, and the check passes. The CodeRabbit comment about pytz concerns test logic, not an external resource reference.

Full details: Change Map Design Review

Explanation

The change map (&lt;!-- kumo-pr-change-map --&gt;, comment 6868907169, fetched via the GitHub API) gives a plausible problem statement, a stated stopping condition, and historical benchmarks. Its design still fails the check in three material ways, verified against the head diff. 1. Omitted material behavior: inspectable graph output now uses model-mode collation. _typed_batches calls assembler._collate(values, epoch=epoch, seed=seed, model=True) for the new inspectable graph route (native_anchors.py, the _surface_padding(assembler._collate(...model=True)) hunk). In assembly.py _collate, model changes several paths. It selects values.entity_ids instead of per-anchor _history(value).entity_id, and it is passed to _rows_for_inputs and the encoders (encode_arrow(..., model=model)). The code comment says only that "Raw fields keep the same Arrow representation as inspection." The change map does not mention this coupling. It is the core mechanism of the fast route, so the map should state it, justify it, and name the parity evidence for it. 2. Misleading claim: timezones are not resolved once per column for all timestamp columns. The map and the PR say timezones are "resolved once per column." _column_values resolves the zone once only when the top-level dtype is a timestamp. For list/large_list/fixed_size_list timestamp columns, it falls through to _arrow_values, which calls values.to_pylist() for non-ns units and per-scalar _arrow_scalar_value for ns. The nested test (test_nanosecond_columns_preserve_main_scalar_contract_without_pandas) covers only ns with UTC. It does not check a named zone or the import count for nested values. The "once per column" claim therefore does not hold for nested columns. The map should either narrow the claim or extend the helper and test it. 3. Incomplete scope and change list. The table's scope omits _can_batch_inspectable_graph, the new function that holds the whole eligibility gate. The map also omits the _model_batches → _typed_batches rename and the new output_format parameter. It does not state that _validate_model_contract() now runs only for output_format == "model". The "model validation preserved" wording covers the model route only. The eligibility wording ("fixed-size batching, source identity") also differs from the code gate. The code gate is (output_format == "model" or inspectable_graph) and (fixed or ...) and assembler._source is self._source, with inspectable_graph requiring one stage and one Graph input. Confirmed as accurate: the oracle-ordering fix in the test file (expected computed after the pytz blocker, attempts.clear() before measuring). Exactly one Graph input and no split, target, or filter declarations do gate the route. Model output still rejects unsupported Raw fields. Limits: I read only lines 1–80 of the 257-line test file. I did not verify the parity claims for duplicate/isolated anchors, shuffle, rank padding, and drop-last. I did not re-run the benchmark. The performance numbers are historical and the map says so. These are design and explanation defects. The core direction (typed reuse for a single-graph inspectable route, plus a one-time zone lookup) appears necessary and is tested. The defects are the unexplained model-mode coupling, the overstated nested timezone claim, and the incomplete scope.

Resolution

Revise the change map and, where needed, the implementation: - Add a row or note for _can_batch_inspectable_graph. State the eligibility gate exactly as coded, including the output_format, single-stage, one-Graph-input, and fixed conditions. - State that inspectable graph output now calls _collate(..., model=True). Explain why the typed buffers match the requests path, including entity_ids and Raw encoding. Cite the parity tests that cover this. - Either (a) extend _column_values to resolve the zone once for list/large_list/fixed_size_list timestamp columns, with a named-zone test that counts optional pytz imports, or (b) narrow the "once per column" claim to top-level timestamp columns. - Record the _model_batches → _typed_batches rename, the new output_format parameter, and that _validate_model_contract() now runs only for model output. - Keep the benchmark marked as historical, as the map already does.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 04bdf1c and 0fffd73.

Files selected for processing: 1

  • packages/experimental/kumo-pytorch/tests/test_inspectable_graph_batches.py

Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 11 remain after this review.

@am-porter

am-porter commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor Author

Change map

File Function / scope What changed Why
packages/experimental/kumo-pytorch/src/kumo/pytorch/engines/native_anchors.py _column_values, _requests, _batch_values, _typed_batches, batches Resolve timestamp timezones once per column and reuse typed native assembly for eligible fixed-size inspectable graphs. Preserve main's lossless nanosecond scalars, typed target conversion, native token-budget planning, model validation and fallback routes. Profiling found repeated optional timezone imports and redundant per-anchor request/history reconstruction dominating graph-only serving.
packages/experimental/kumo-pytorch/tests/test_inspectable_graph_batches.py Timestamp conversion and native graph parity regressions Compare exact outputs with the existing inspectable route across Raw fields, duplicate/isolated anchors, shuffle, rank padding and drop-last. Check timezone/DST/null handling, aligned and fractional nanoseconds without pandas, nested timestamp values, bounded optional imports and fallback/model refusal. Compute the timestamp oracle after blocking pytz and reset its import counter before measuring the optimized path. Prevent the optimization or its refresh against main from changing data, precision, metadata, ordering or accepted contracts.

The fast route requires one graph input, one selected native stage, fixed-size batching, source identity, and no additional retrieval/target/availability declarations. Other inspectable contracts retain their existing path. Explicit model output still rejects unsupported Raw fields. Main's non-graph native token-budget path remains enabled.

Historical matched measurements at c458c2e with native base ffd51069 showed 834 → 134 ms at 10,000 seeds with identical bytes; the candidate remained about 11% slower than direct native. Those measurements are not a benchmark of this refreshed head. Small-request overhead and timeless sampling are outside this performance patch.

The branch is rebased onto main 2f7171fc. Nanosecond values that Python datetime cannot represent remain Arrow scalars, matching main; microsecond-aligned timestamps retain ordinary datetime values. The change remains limited to two files relative to main.

Rebase validation

Head 0fffd73b, rebased onto main 2f7171fc, macOS arm64 / Python 3.12.13 / Arrow 24.0.0 / NumPy 2.5.4 / PyTorch 2.15.0 / pytz 2026.6:

  • Full package suite against main 9c9cba53 plus this change and a freshly rebuilt DiskGraph wheel: 2,372 passed, 7 skipped, 3 deselected; spawned-worker tests included.
  • After incorporating main's subsequent Python-only padding fix (2f7171fc), output and inspectable regression suites: 81 passed on the final head. Native sources are unchanged between those main revisions.
  • Reproduced CodeRabbit's timezone-oracle issue with pytz installed: the original test fails all four America/New_York timestamp units; the corrected inspectable suite passes all 33 cases. Expected values are now computed after blocking pytz, and the import counter is cleared before measuring the optimized conversion.
  • Package Ruff check/format, repository license-header check, Python/native wheel builds and git diff --check pass.
  • Native wheel SHA-256: a24467eb9d41edd5c132892929596dba83bf6f2e63c1d892cc997cd86651f612.
  • Historical performance measurements were not rerun.

Stopping condition: preserve exact inspectable output and fallback contracts, pass the affected tests, and correct the reviewed oracle ordering. Further serving optimizations remain separate.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between c458c2e and 04bdf1c.

Files selected for processing: 2

  • packages/experimental/kumo-pytorch/src/kumo/pytorch/engines/native_anchors.py
  • packages/experimental/kumo-pytorch/tests/test_inspectable_graph_batches.py

Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 11 remain after this review.

@Vedaant-J

Vedaant-J commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

why are we using: Task.batches(output_format="inspectable") and not Task.batches(output_format="model")? #282 #339 made it faster for output_format=model already

Vedaant-J
Vedaant-J previously approved these changes Nov 16, 2026

@Vedaant-J Vedaant-J left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks good, I looked at fm dataloader so understand why this helps the inspectable path specifically

@am-porter can we remove discussion of a private repo (fm datalaoder) from this public repo?

@am-porter
am-porter force-pushed the codex/kumo-pytorch-inspectable-performance branch from 04bdf1c to 0fffd73 Compare November 17, 2026 00:05
@am-porter
am-porter temporarily deployed to gha-kumo-workflow-tests November 17, 2026 00:06 — with GitHub Actions Inactive
@am-porter

Copy link
Copy Markdown
Contributor Author

/ok to test 0fffd73

@am-porter
am-porter requested a review from Vedaant-J November 17, 2026 03:56
@aleksssokolovski
aleksssokolovski self-requested a review November 17, 2026 17:37
@am-porter
am-porter merged commit 28335cd into main Nov 17, 2026
129 checks passed
@am-porter
am-porter deleted the codex/kumo-pytorch-inspectable-performance branch November 17, 2026 17:42
am-porter added a commit that referenced this pull request Nov 17, 2026
A foundation-model user may need Arrow tables to assemble model-specific
payloads. The inspectable Graph output first encodes sampled nodes into
tensor/mask dictionaries, requiring a columnar consumer to reconstruct
Arrow columns. Add `Task.batches(output_format="columnar")` to return
public `ColumnarGraph`, `ColumnarNodes`, and `ColumnarEdges` directly
from native Arrow buffers.

- Preserve declared feature types and NULLs, example ownership,
isolated/repeated roots, and selected edge endpoints in declared
relation orientation.
- Reuse the native anchor iterator and existing metadata, padding,
sharding and resume logic. Refuse unsupported contracts before
iteration.
- Keep native edge chunks by default. Offer `deduplicate_edges=True` for
unique pairs per relation in first-occurrence order, preserving example
isolation. Document the additional allocation/work and consumer
normalization contract. Existing inspectable/model outputs remain
unchanged.

Stacked on #340. No native/Rust changes.

## Benchmark

A foundation-model payload consumer was evaluated using the same
indexes, native binary and frozen 10k-seed batches for both output
formats. Each format received one warmup and five alternating measured
draws. Columnar measurements use the default `deduplicate_edges=False`;
the opt-in deduplication path has not been benchmarked. Medians include
the consumer's complete payload assembly and JSON encoding; preparation
and validation are excluded.

| Workload | #340 inspectable | Columnar | Latency reduction |
| --- | ---: | ---: | ---: |
| Commerce, 2 hops | 1.632s | 1.016s | 37.8% |
| Commerce, 4 hops | 20.084s | 13.305s | 33.8% |
| Streaming, 2 hops | 0.681s | 0.465s | 31.8% |
| Delivery, 2 hops | 1.943s | 1.361s | 29.9% |

AMD EPYC 9654P, 16 sampler threads. All measured payloads are
byte-identical across formats. Full 10k native/Python encoder parity and
independent DuckDB source validation on 128 distributed anchors per
workload pass. These measurements retain the native binary used for the
#340 baseline and isolate the output-format change.

## Testing

237 focused engine/API tests pass, including 56 columnar tests, existing
graph direction/uniqueness/temporal/native-anchor suites, and generated
API-reference checks. Tests cover both deduplication settings, stable
uniqueness within/across chunks, empty/singleton edges, uint32/uint64
indexes, repeated entities in separate examples, reverse/self-relations,
and rejection of changed deduplication settings on resume.
Buffer-address and closed-task lifetime tests cover Arrow sharing;
sharding, padding, shuffle and rejection tests cover the public
contract. Consumer integration checks additionally cover asymmetric
sampling radii, shuffled-anchor mapping and payload equality. Ruff and
diff checks pass.

## Change map

#365 (comment)
nittin-murthi added a commit that referenced this pull request Nov 18, 2026
## Summary

Mixed graph/sequence contracts force `fit_plan` to reconstruct Python
samples because an input uses `NeighborhoodSource`. Graph fields already
have a separate fitting pass, so allow the other inputs and targets to
use the existing columnar `build_model` path. Keep the candidate and
dated-entity fallbacks.

The production change is one routing condition and its explanation. Six
regression cases compare both paths using existing fixtures. This
addresses fitting; #340 addresses graph-only inspectable batch delivery.

## Measured result

The completed AWS replication uses the Arena profiler CLI on AML
HI-Small next-day involvement with v2 graph anchors: **1,969,386
training anchors**, complete preparation/fitting, then 20 timed batches
× 3 repetitions after two warmup batches per repetition. Baseline
`08577147` and candidate `19d084ca` ran serially on one r7i.8xlarge CPU
worker, with four threads, batch size 128, fresh indexes, identical
dependencies and the same native DiskGraph binary. Two independent fits
per side test both orders.

| Representation / order | Baseline main fitting | Candidate main
fitting | Baseline / candidate |
| --- | ---: | ---: | ---: |
| Combined, baseline → candidate | 2,978.17 s | 716.10 s | 4.16× |
| Combined, candidate → baseline | 2,989.87 s | 696.09 s | 4.30× |
| GraphSAGE control, baseline → candidate | 269.71 s | 273.35 s | 0.99×
|
| GraphSAGE control, candidate → baseline | 267.14 s | 271.06 s | 0.99×
|

Across the two fits, combined main fitting averaged **4.23× faster**.
Total fitting, including shared inputs, averaged 3,255.82 → 974.82 s;
sampled main-fitting peak RSS averaged 5.10 → 4.70 GiB. Unchanged shared
fitting was 271.80 → 268.73 s. The GraphSAGE control was 1.4% slower on
average; this patch does not demonstrate a graph-only improvement.

Saved fitted states, contracts, populations, source identities,
configurations and available sample/token/node/edge counts matched
within every pair. Execution, recording and measurement completeness
checks passed for all eight runs. Missing counters remain unavailable;
the profiler's aggregate measurement status is `partial`. Exact tensor
parity is covered by regression fixtures; full-run batch payloads were
not retained.

This is two fits per side on one CPU host with uncontrolled filesystem
cache, not a statistical significance claim. **Performance evidence is
scoped to AML HI-Small; cross-dataset generalization has not been
established.** Raw profiler reports, commands, source identities and
archive checksum inventories are under
`s3://kumo-engine-arena/runs/mixed-fitting-generalization-20261115/results/`.

The earlier macOS single-pair observation was 1,677.34 → 318.18 s main
fitting (5.27×), with sampled RSS 4.61 → 5.36 GiB. It used an earlier
baseline run and also showed substantial improvement in unchanged shared
fitting, so the matched AWS results above are the stronger evidence.

**Related decimal fix: #348.** Both implementations use the same local
decimal-decoding workaround for that issue; it is not the exact #348
head. Decimal changes remain outside this PR. The separate Arrow/Rust
experiments are not included in these measurements.

<details>
<summary>Profiler reproduction</summary>

From `kumo-ai/kumo-engine-arena` at
`220aa187921ddb1d846985bec8f8edff1d3581c9`, using staged source/anchor
paths and an independent Kumo checkout:
The command below is the local form. The AWS campaign used the same
workload/timing options with a 192 GiB RAM guard and 768 GiB storage
guard; exact commands are retained in the published evidence.

```sh
python -m profiling \
  --binding-id kumo-binding-0b7ba9313e19cae69aec45e615aaf123e1ad27506efd3a3502ed7e4f3b61b4b2 \
  --kumo-path "$KUMO_CHECKOUT" --source-dir "$SOURCE_DIR" \
  --anchor-path "$ANCHORS" --anchor-manifest "$ANCHOR_MANIFEST" \
  --output-root "$OUTPUT_ROOT" \
  --backend diskgraph --mode batch --split train --device cpu --precision float32 \
  --batch-size 128 --model-dim 16 --steps 20 --warmup 2 --repetitions 3 \
  --threads 4 --workers 0 --seed 0 --backend-measurements common --retention diagnostic \
  --ram-limit-bytes 17179869184 --storage-limit-bytes 68719476736 \
  --resource-limit-interval-seconds 1
```

</details>

## Testing Done

- From `packages/experimental/kumo-pytorch`, `PYTHONPATH=src python -m
pytest -q` on the clean PR branch: **2,334 passed, 5 skipped, 47
deselected**. Skips cover unavailable CUDA and Linux `/proc` checks;
notebook/E2E tiers retain their default deselection.
- Regression coverage: request lists and Parquet anchors, chunk
boundaries, held-out rows, derived history ages, shared graph/history
encoders, external/computed/aligned targets, and exact fitted-state plus
model/inspectable batch parity. The new test fails on the original
route.
- Ruff 0.17.3 lint/format and `git diff --check`: passed.

## Change map

[File-by-file rationale and
verification](#351 (comment)).

## Checklist

- [x] Internal routing change; public API and contract meanings are
unchanged.
- [x] Existing documentation remains applicable; the routing rationale
is documented inline.
- [x] Added focused regression coverage.

This branch was previously deployed

1 inactive deployment
gha-kumo-workflow-tests — 0fffd73b Deployed Nov 17, 2026 by am-porter via import #2462
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants