Skip to content

Fit encoders without building samples (stack 5/5) - #324

Merged
Vedaant-J merged 168 commits into
mainfrom
vedaant/fit-without-samples
Nov 13, 2026
Merged

Vedaant-J merged 168 commits into
mainfrom
vedaant/fit-without-samples

Conversation

@Vedaant-J

@Vedaant-J Vedaant-J commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Stack 5/5. Based on main; #299, #318, #306 and #307 are merged.

Summary

Plan.materialize used to fetch every fitting anchor as a SampleRequest and build every fitting sample at once, then fit encoders from that list. After #306 and #307 most encoders no longer need those samples: they are pinned from DiskGraph column statistics or a tokenizer trained from the index. This PR stops building the samples for them:

  • Fitting anchors are read 4,096 at a time.
  • The default encoder_cutoff (the latest fitting anchor time) is the max anchor time over those chunks, converted once at full precision by Fit table-column encoders on table rows up to an encoder cutoff (stack 3/5) #306's cutoff_nanos, so it selects the same rows as the same cutoff given explicitly.
  • Encodings whose state comes from column statistics, a tokenizer or the contract (Raw(), Vocabulary(values=...), ZScore(mean=, scale=), Buckets(boundaries=), Text(state=)) build nothing.
  • Learned encodings over supplied labels (ExternalTarget) read the labels from the anchors; nothing is built.
  • What still needs a sample builds it 4,096 anchors at a time, keeping only each encoder's observed values. That is learned encodings over aggregates, calculations and computed targets, plus the cases listed under "Known remaining cases". Inputs build without their targets. Computed targets build alone (no entity values, events or neighbourhoods) unless they read input rows.
  • The fit-time length summary (manifest["lengths"]) is deleted. Computing it meant building every fitting sample, and nothing reads it: batching measures its own lengths when it iterates.

Fitted state is bit-identical to #307's (head 252c0dbd) for the same inputs. This was checked over the whole test suite and on 13,000-anchor multi-chunk cases; see "Testing Done".

On a DiskGraph contract whose encoders are all pinned or declared, with 100k Parquet anchors, materialize takes 1.0 s and grows peak RSS by 20 MiB. Before this PR it took 30.1–30.3 s and 933–963 MiB.

Behaviour changes

Checks that ran only because fitting built samples now run when a batch builds the anchor. When nothing is built at fit time, the following are refused by the batch (or preview) that builds the anchor, not by materialize:

  • an entity created after its anchor time (entity did not exist before …);
  • an unknown candidate set, or duplicate candidate IDs;
  • duplicate sample IDs (in-memory engine);
  • a single sample over Batching.max_tokens (one sample exceeds Batching.max_tokens), which the length summary used to catch.

As before, anchors outside fit_split were never checked at fit time.

Dropped at fit time.

  • An AlignedEventTarget derived label (ThresholdEventLabel) with a supplied threshold and a declared encoding no longer checks at fit that its field's values are finite. With a fitted threshold or a learned encoding, the check still runs.
  • Declared encodings no longer normalise every fitting value, which was a validation-only pass.

Length summary removed.

  • Task.manifest and PreparedBatchPlan.manifest no longer have "lengths", and fitted-state.json no longer holds it.
  • manifest["artifact_fingerprint"] covered that key (None without a length_input), so its value, and every batch's metadata["artifact_fingerprint"], changes for every task.
  • The fitted-state fingerprint and Task.fingerprints are unchanged.

Public API touched

API Change Errors
Plan.materialize Same signature. Builds samples only as described above, and reads anchors in chunks. The refusals listed under "Behaviour changes" moved to batch time. All others are unchanged.
PreparedBatchPlan(...) The fitting_values= and length_summary= keyword parameters are removed. They only fed the summary. None
PreparedBatchPlan.manifest, Task.manifest No "lengths"; new artifact_fingerprint value None
prepare_batch_spec Same signature; no summary one sample exceeds Batching.max_tokens is raised by batches(), not by prepare_batch_spec
FittedState The _lengths field is removed (it appears in the documented constructor) None
Artifact.save / Artifact.load No "lengths" is written. load accepts an older artifact that has one, and ignores it. load no longer raises has no length summary, has a malformed length summary or the length summary … is not the one manifest.json records. All other refusals are unchanged.
SampleSource.fit_graph_fields (engine seam) Called once with every fitting root, as before. The roots are now made from the anchors, not from built samples. None

fit_plan (internal) now fits only with a contract; Plan.materialize and serving always pass one.

How it works

  1. Anchors (preparation.py: Plan.materialize, assembly.py: _Mapped, _chunks). fitting = _Mapped(partial(task_anchors.fetch, chosen), range(count)): slicing it fetches those positions. _chunks(values) yields values[i:i + 4096]. Plan._pinned_from_stats takes the latest anchor time as a max over _chunks(fitting).
  2. What learns (encoding.py: learns_from_values, moved from column_stats._learns_from_stats unchanged). An encoding learns from values when it is Vocabulary(values=None), ZScore(mean=None) with a numeric dtype, Buckets(bins=…) with a numeric dtype, or Text(state=None) with a string dtype. Every other encoding takes its state from the contract.
  3. Inputs (assembly.py: _fit_inputs).
    • First, without values, it computes each encoder's config and dtype from the declarations, as before.
    • It records a slot (input, field), or (input, table, field) for a graph, for each encoder that learns and is not pinned. Slots are kept in the old iteration order, so shared encoders concatenate their observations exactly as the single build did.
    • Unpinned graph slots: source.fit_graph_fields is called once, with GraphRoot(sample_id, entity_id, cutoff_to_epoch(as_of_time)) for every fitting anchor.
    • Field slots, and Composite(vocabulary=None) rows, take _chunks(values_for(sample_without_targets(sample))). Per chunk, the rows' learned columns are appended to their slot, and composite rows are counted as raw-value tuples.
    • After the chunks, fit_encoder runs on the concatenated slot lists. Composite tuple counts are mapped through _component_key and summed, which gives the same counts and the same ordering as counting per row.
  4. Targets (assembly.py: _fit_targets).
    • Slots go to target encoders that learn and are not shared with an input.
    • Observations are also kept for derived labels with a fitted threshold, and for matching groups.
    • What it builds:
      • the full sample, if a learned target reads input rows (AlignedEventTarget, MatchingGroupTarget, CandidateTarget);
      • otherwise, if a learned target is computed (Aggregate, Compare, RowTarget), a targets-only sample (entity_values, dated_entity_values, events, current_events and neighborhoods emptied);
      • otherwise the anchors themselves, with _normalize_supplied_targets applied as the engines apply it. _targets reads a SampleRequest's targets.
    • Thresholds, labels and group numbering are computed after the chunks, as before.
  5. Builds (assembly.py: fit_plan.values_for). values_for(spec) is a _Mapped over the fitting requests. Each slice's supplied labels are first normalised against the full sample with _normalize_supplied_targets. A value supplied for a generated target is therefore refused as … was both supplied and generated, as a full build refuses it, even when the build itself uses a sample without targets. The slice is then built with source.build_model (or build) under spec. values_for(None) returns the normalised requests and builds nothing. prepare_batch_spec passes its already-built values as the single source.
  6. Length summary (assembly.py: PreparedBatchPlan; artifact.py; task.py; serving.py; preparation.py). Removed. Artifact.load pops "lengths" from an older fitted-state.json. If an older manifest.json has "lengths", load first checks the manifest against the rebuilt one with that summary added and its fingerprint recomputed the old way. It then drops the summary and takes the rebuilt artifact_fingerprint. Every manifest field, the old fingerprint included, is verified.

Known remaining cases

These still build samples, chunk by chunk, keeping only observed values. Before this PR they were fitted from the full sample list.

Case What it needs Why
Learned encodings over aggregates, Compare, Derived entity values Each chunk's input sample (without targets) The values are computed per anchor from history
Learned encodings over computed targets Each chunk's targets-only sample The labels are computed from future rows
Learned encodings over event fields that aren't plain stored columns (Derived, EventTimeDelta, Constant, a Field with path), including current_events History rows Values exist only per event in a sample
Learned encodings over entity Fields with path, and over dated entity values (OccurrencesOf) Related-row lookup, or dated facts Not a stored column of the entity table
Composite(vocabulary=None) rows History rows Tuple counts are over each event's encoded components, even when every component is pinned
Learned encodings on CandidateSource inputs, and learned CandidateTargets The candidates' rows (full sample) Values are per requested candidate
AlignedEventTarget with a learned field or a fitted threshold The input's event rows (full sample) Labels are aligned with the retained events
MatchingGroupTarget The entity input's rows (full sample) Groups are the typed values those rows hold
A UseEncoding shared between a stored column and a per-anchor value Rows for both It is not pinned, so it learns from built rows
Unpinned graph node fields: shared as in the row above, or on an engine without column_stats One fit_graph_fields call over every fitting root, as before Node values come from neighbourhood sampling

Semantics a reviewer should check

  • Observation order. Each slot list is filled chunk by chunk in request order, and slots concatenate in the old loop order: sorted inputs, then tables and fields; targets' fields before their derived labels. ZScore (numpy summation) and Text depend on order. Vocabulary, Buckets and composite counting don't.
  • Graph roots from the anchors. Both engines' built samples have sample_id = request.sample_id, entity_id = request.entity_id and evaluation_time = cutoff_to_epoch(as_of_time). Model collation already makes graph roots this way.
  • Targets-only builds. Computed targets reference only their own rows and fields, never entity values or events.
  • Supplied labels. They are normalised by the same _normalize_supplied_targets the engines use, so a Vocabulary over a label sees the same typed values.

Back-compat

Case Behaviour
New artifact No "lengths" in fitted-state.json or manifest.json
Artifact written before this PR, loaded by this PR Loads. The old artifact_fingerprint is checked against the summary it covers, then the summary is dropped from both files and the fingerprint replaced by the rebuilt one. Tested, including a summary edited after writing, which is refused.
New artifact, loaded by #307 Refused (has no length summary with a length_input, and a manifest mismatch otherwise). Older code expected the key.
materialize(..., fitted=...) Never fits, as before
Fitted state Bit-identical for the same inputs
Batch metadata Same tensors. metadata["artifact_fingerprint"] has a new value.
prepare_batch_spec Same fitted state; no summary in its manifest

Production questions

Question Answer
Peak memory of materialize, all encoders pinned or declared (DiskGraph, Parquet anchors) Before: about 11 KB per anchor. Now: about 0.1 KB per anchor, which is the anchor table. Table under "Testing Done".
Wall time, 100k anchors 1.02–1.05 s, against 30.1–30.3 s
Contracts that still build (aggregates, computed targets) Bounded per chunk. Learned values are kept as Python lists, which is about 0.1 KB per anchor per learned encoder.
Anchor reads Each pass fetches the fit-split anchors chunk by chunk, each only when needed: the default cutoff, one pass per graph input with an unpinned learning field (it collects every root), the input pass and the target pass. Before, there was one fetch of all anchors.
Builds At most two: inputs without targets, and targets (alone, or the full sample if they read input rows). Before, there was one build of every full sample.
Unpinned graph fields One fit_graph_fields over every fitting root, as before. That is population-sized, which is why it is listed as a remaining case.

Testing Done

Head 59b4d727: this PR's commits, merged with #307's 3ffaaa03 (which brings in main through #306's 1c46724f). DiskGraph was built from that tree.

  • On this head, the targeted tests pass; conformance last ran on 88df2a4f. In kumo-pytorch, test_text_from_index.py, test_column_stats.py, test_fitted_state_persistence.py, test_model_history_limits.py, test_candidates.py, test_core_api.py, test_api_reference.py, test_keyless_tables.py and test_entity_identity.py gave 177 passed, and DiskGraph test_token_lengths.py, test_train_tokenizer.py and test_cutoff_col_stats.py gave 14 passed; python -m conformance --engine all gave 705 passed on 88df2a4f. CI runs the full suite on this head.
  • On c84dcbc0, the commit before the Train Text tokenizers for stored columns inside DiskGraph (stack 4/5) #307 merge: the full kumo-pytorch suite gave 1914 passed, 3 skipped. That run doubled as the fitted-state comparison below.
  • On 1b85da73, before the review fixes: python -m conformance --engine all gave 701 passed, and pytest -m notebook tests/test_notebooks.py gave 3 passed. No docs page or notebook output changed. docs/api was regenerated for the removed parameters.
  • ruff check, ruff format --check and vulture: clean.
  • New and changed tests:
    • test_column_stats.py::test_a_shared_encoder_fits_the_graph_values_of_every_root_then_the_aggregate.
      • A UseEncoding ZScore is shared by a graph node field and an aggregate, over 10,000 anchors, on DiskGraph.
      • The test asserts the fitted mean and scale equal numpy's over the documented order: one SampleSource.fit_graph_fields call over every root, then each anchor's built aggregate.
      • Chunking the graph pass (this branch at 618107de) fails it in the last bit: 33042.8568529613 vs 33042.85685296129.
    • test_column_stats.py::test_a_value_supplied_for_a_generated_target_is_refused_while_fitting. It fails on 618107de, which gave unknown supplied target.
    • test_fitted_state_persistence.py::test_an_artifact_written_with_a_length_summary_still_loads. It replaces the summary refusal test.
    • Four tests now check the late validations at batch time:
      • test_candidates.py::test_unknown_candidate_groups_and_duplicate_candidates_are_refused
      • test_diskgraph_backend.py: the materialize-time "did not exist before" block is removed; the batch-time block below it stays
      • test_core_api.py::test_token_budget_rejects_one_example_that_cannot_fit
      • test_field_outputs.py::test_single_grouped_history_exceeding_padding_budget_is_refused
    • test_model_history_limits.py::test_real_model_requests_are_bounded_but_preview_and_labels_are_not (renamed from …_but_preview_fitting_and_labels_are_not) now asserts that fitting that contract issues no history query: its Vocabulary is pinned and the rest is Raw().
  • Fitted state against Train Text tokenizers for stored columns inside DiskGraph (stack 4/5) #307, by hand, on Train Text tokenizers for stored columns inside DiskGraph (stack 4/5) #307's head 252c0dbd and this branch at c84dcbc0.
    • A pytest plugin recorded every PreparedBatchPlan's fitted-state fingerprint across the full suite on both. The renamed history-limit tests are matched by their old names.
    • 951 tests ran on both. In 950 of them every plan matches, 3,231 plans in all.
    • In the remaining one, a contract preview that Train Text tokenizers for stored columns inside DiskGraph (stack 4/5) #307 refused during fitting now fits first and is refused by the preview's build. All its plans match Train Text tokenizers for stored columns inside DiskGraph (stack 4/5) #307's one.
    • 6 extra cases with 13,000 anchors (4 chunks), on both engines, plus 24 small ones: all equal. The large cases cover:
      • a ZScore shared across two inputs and two fields;
      • Buckets and Vocabulary over aggregates;
      • Composite(top_k=4);
      • MatchingGroupTarget;
      • AlignedEventTarget with a fitted threshold;
      • learned computed labels.
  • Memory and time, by hand, fresh processes, on 579baaa0.
    • Peak RSS growth during materialize (VmHWM minus VmRSS before the call; warm index).

      Fitting anchors Before (Train Text tokenizers for stored columns inside DiskGraph (stack 4/5) #307) This PR
      25,000 332 / 337 MiB 61 / 67 MiB
      100,000 1,174 / 1,174 MiB 75 / 75 MiB
      400,000 4,640 MiB (one run) 101 / 102 MiB

      The ~60 MiB floor is fixed: imports, statistics and the tokenizer. What grows is the anchor table and one chunk.

    • Wall time at 100k anchors on a similar contract (stored columns, a graph, a Raw() aggregate and a Raw() label): 1.02 / 1.05 s and 20 / 20 MiB, against 30.1 / 30.3 s and 933 / 963 MiB. Same fitted state.

    • Contracts that still build. A 3-user fixture with 200,000 anchors, on DiskGraph with 4 threads. Each row fits the same state on both trees.

      Contract Before (Train Text tokenizers for stored columns inside DiskGraph (stack 4/5) #307) This PR
      A ZScore shared by three aggregate fields across two inputs, Buckets and Vocabulary over aggregates, Composite(top_k=4), a Buckets computed label, MatchingGroupTarget 15.8 / 16.3 s, 258 / 263 MiB 10.5 / 10.6 s, 121 / 123 MiB
      The same with Batching(max_tokens=4096, length_input="history") 187.0 / 199.5 s, 286 / 288 MiB 10.8 / 11.0 s, 122 / 125 MiB
      AlignedEventTarget with a learned field and a fitted threshold, and a Vocabulary computed label 9.8 / 10.2 s, 193 / 195 MiB 9.0 / 9.4 s, 124 / 125 MiB

      The second row's 187–200 s before was the length summary.

Where to look

  1. assembly.py: _fit_inputs: slots, the single graph pass, the chunked input pass, composite counting.
  2. assembly.py: _fit_targets: what is built for targets, and thresholds and groups after the chunks.
  3. assembly.py: fit_plan (values_for), _Mapped, _chunks; preparation.py: Plan.materialize, Plan._pinned_from_stats.
  4. artifact.py: Artifact.load, _split_fit: the length-summary removal and back-compat.
  5. encoding.py: learns_from_values; then the tests.

Change map

File-by-file change map.

🤖 Generated with Claude Code

Vedaant-J and others added 30 commits November 10, 2026 23:13
A standard-library-only module for process-wide settings shared by the
Kumo packages. It holds the scratch directory: configure(scratch_dir=...),
scratch_dir() and scoped(scratch_dir=...), plus the KUMO_SCRATCH_DIR
environment variable. Resolution is scoped, then configure, then the
environment, then ~/.cache/kumo-engine. The path must be local; configure
creates it if missing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
kumo.engine.configure delegates to kumo.settings.configure, the scratch
helpers resolve through kumo.settings.scratch_dir(), and batch prediction
scopes its scratch directory with kumo.settings.scoped. kumo-engine now
depends on kumo-settings, so the engine wheel bundles it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
kumo.settings.configure only records the path again, as the engine's
configure did: callers create what they write, and configuring a scratch
directory inside a FileConnector root writes nothing there. The license
metadata inventory now counts kumo-settings.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The shift that picks the bin becomes a const parameter (default 49, eight
bins per octave), so finer bins can reuse the same exact counting table.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Ingest writes `index_id`: the sha256 of the resolved config, every source
file with its size, and the DiskGraph version. `index_id()` returns it, or
for an index ingested before ids existed, a hash of its config, metadata
and manifest files. Readers that do not know the field ignore it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`cutoff_stats` counts values, exact moments and fine log bins per column
over the rows created at or before a cutoff, and publishes one file per
statistic under `col_stats/<cutoff_id>/`. Sums are exact fixed-point
integers and every merge is order-independent, so a rescan over any number
of shards and threads writes the same bytes. `ensure_col_stats` reuses
valid files and recomputes the missing ones from the stored rows, decoding
only the needed columns.

The index exposes its durable write and temporal conversion for this, and
the rowpack decoder gains a single-pass visit of the requested columns.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`stats_from_arrow` gives the same data objects as the files for an
in-memory column, converting values and create times to the index clock
the way ingest does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`diskgraph.col_stats_index_id`, `ensure_col_stats` and
`col_stats_from_arrow` return plain dicts parsed from the same JSON the
files hold.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`ingest(col_stats_requests=...)` takes the cutoffs and
`[table, column, stat]` requests, observes each encoded row alongside the
existing statistics, and counts it only once it is stored with node data.
The files are published after `index_metadata.json` is final, byte for
byte what a rescan of the index writes. Without the option nothing
changes; a resumed ingest that skipped Encode publishes nothing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Ingest, a rescan and Arrow produce identical files and data across thread
and shard counts, matching exact references; concurrent ensures, indexes
without an id and unsupported requests are covered too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The mean and m2 divide the exact sums by n before their single rounding,
so they stay finite whenever the true values are (rounding Σx first made
two values of 1e308 publish a null mean). The rescan skips rows stored
without node data, which oversized rows are; request names are checked
before ingest starts; temp files get a random suffix; an empty Arrow stats
list returns nothing; a resumed ingest that skipped Encode warns that it
publishes no statistics.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The four ingests share one fixture, so each layout is built once and the
remaining tests run against a single index. Moments are checked against
exact fractions divided before rounding.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`CreateTime` reads a row's create time in index-clock ticks and decides
whether the row counts at a cutoff; `node_chunks` and `stored_row` walk a
table's rows that carry node data, in shard then node order. Statistics
use them unchanged, so a column scan can count exactly the same rows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`diskgraph.scan_column(index_dir, table, column, cutoff)` yields the
non-null values of a string column as `pa.large_string()` arrays of
`chunk_rows` values, over exactly the rows the cutoff statistics count, in
shard then node order whatever the thread count. A thread decodes windows
of node chunks in parallel and hands finished arrays over a bounded
channel, so memory stays near two windows; the GIL is released while
waiting.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`diskgraph.publish_col_stats_file(index_dir, cutoff, table, name, payload)`
writes bytes at `col_stats/<cutoff_id>/<table>/<name>` with the same
durable, uniquely named temp file and rename as the statistics, adds the
cutoff manifest if missing, and returns the path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The concatenated chunks equal the stored values in node order for every
thread, shard and chunk size, the cutoff is inclusive, non-temporal tables
yield every row, non-string columns are refused, and scanning a few
million rows keeps the resident set far below the column size.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A panic while decoding now ends the scan with an error instead of a
silent early end. Nodes decode in fixed 64Ki grains whatever chunk_rows
is, only two finished arrays wait in the queue, and a dropped scan stops
before its next window. Waiting for a chunk wakes every 100 ms so Python
signals such as Ctrl-C get through. num_threads=0 and files for tables
the index lacks are refused.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fit_encoder's frequency-then-value ordering is now learned_entries, so
counts that come from elsewhere are ordered by the same rule.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Encoders in pinned are used as given: their fields contribute no
observations, and a graph input whose node fields are all pinned samples
no neighborhoods for fitting.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A Vocabulary, ZScore or Buckets(bins=...) whose every use reads a stored
column directly (an entity, event or graph node field) is pinned from that
column's statistics over the rows whose clock is at or before
Plan.materialize's new encoder_cutoff, one row one observation. The cutoff
defaults to the latest anchor time the fit split selects; None reads every
row, and a cutoff after the latest anchor logs a warning. Buckets cuts are
np.quantile's over the counted values, or from 128-per-octave log bins for a
column with more distinct values than are counted; a vocabulary with more
categories than are counted keeps fitting on the training examples.

DiskGraph reads the statistics from <index>/col_stats/, computing the
missing ones from the index; the in-memory engine computes them over its
rows with the same collector. The inputs fit record names each pinned
encoder's statistics files and digests, and Artifact.load refuses records
the contract's encoders could not have read.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…r_cutoffs=...)

When prepare builds the index, it passes the contract's (table, column,
statistic) requests and the engine's encoder_cutoffs to the ingest, which
writes those statistics files in the same pass. It is only a hint:
materialize still computes whatever it finds missing, and its log line
names the statistics' source (ingest, existing or recompute).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Values against numpy over the rows up to the cutoff, Buckets cuts against
np.quantile with ties, narrow ranges, negatives and separate zeros, the
fallbacks past the category cap, shared encoders, the inclusive boundary, a
static table, both engines agreeing, ingest and recompute publishing the
same statistics, the late-cutoff warning, reuse reading nothing, and the fit
record's statistics through Artifact.load.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The fit-selection tests read their score through a calculation, which still
fits on the selected anchors; the held-out-anchor case now checks that a
stored column fits on its table rows; the fit record carries statistics; and
the serving page prints the scores of a model trained with the new
encodings.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The in-memory engine computes column statistics with DiskGraph's collector,
so the CPU suite and the in-memory golden cases need DiskGraph built from
this commit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`diskgraph.cutoff_ticks(seconds, unit)` reads the epoch seconds through
the same Arrow timestamp path that ingest uses for a `timestamp[s]`
create time, so a coarser clock rounds the cutoff up exactly as it rounds
the rows, and a value beyond the clock raises.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Vedaant-J and others added 4 commits November 13, 2026 09:51
diskgraph.convert_ticks(value, from, to, *, rounding="truncate") now
matches #310's binding: it lives in tt_builder beside its other clock
helpers, parses units with parse_time_unit, refuses non-index clocks,
and rounds with convert_trunc or convert_floor. #310 can drop its copy.

Co-Authored-By: Claude <[email protected]>
The tokenizer and token-length cutoffs floor to the index clock, as
#306's statistics cutoff now does, so all three share one directory.

Co-Authored-By: Claude <[email protected]>
@Vedaant-J
Vedaant-J temporarily deployed to gha-kumo-workflow-tests November 13, 2026 10:02 — with GitHub Actions Inactive
Vedaant-J and others added 2 commits November 13, 2026 10:20
decode_chunk decoded 65,536 rows at once, so dictionary-expanded strings
could hold gigabytes per worker. column_scan::scan_chunk now decodes a
chunk row by row into Arrow builders with decode_row_to_builders, as the
engine's feature fetch does, and hands batches to its caller once their
decoded values reach 128 MiB (builder_value_bytes). Each batch first takes
a permit from one ScanBudget shared by the workers, ingest's ByteBudget
sized as ingest sizes Encode's (a third of the machine's or cgroup's
memory). A batch that ends larger than its permit, such as one row
larger than the limit, swaps it for an oversized permit. Chunks and
batches keep node order, so the statistics are unchanged.

Co-Authored-By: Claude <[email protected]>
scan_chunk bounds a batch's decoded values at 128 MiB, so its 32-bit
Arrow offsets hold, and decode_batch_to_arrow_with and its LargeUtf8,
LargeBinary and List<LargeUtf8> builders have no caller left.

Co-Authored-By: Claude <[email protected]>
Victsm
Victsm previously approved these changes Nov 13, 2026

@Victsm Victsm left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Re-reviewed current c7b8c8c against the previously reviewed sample-free fitting implementation. The intervening delta adopts the shared convert_ticks binding and explicit floor rounding for encoder cutoffs; it does not restore fitting samples or the removed length summary. No new incremental correctness blocker found. The current draft state and inherited encoder-statistics follow-ups remain separate from this code approval.

Vedaant-J and others added 2 commits November 13, 2026 10:36
cutoff_nanos parsed strings through Python datetime, which keeps only
microseconds, so 2024-01-01T00:00:00.000000001Z lost its last nanosecond and
moved the boundary on a nanosecond index. Strings now go through
diskgraph.resolve_temporal, the parser ingest uses. Dates and datetimes go
through it as one nanosecond Arrow array, so the latest-anchor default is one
call for all anchors and a pandas Timestamp keeps its nanoseconds. Integers
stay epoch seconds; each engine still floors the result into its index clock.

Co-Authored-By: Claude <[email protected]>
…chor once

A cutoff string is refused unless datetime.fromisoformat reads it, as before
86919cc, so impossible dates and bare digits are refused again; DiskGraph
supplies the exact nanoseconds when it parses the string too. The default
cutoff converts only the latest anchor time.

Co-Authored-By: Claude <[email protected]>
Vedaant-J added a commit that referenced this pull request Nov 13, 2026
…k 3/5) (#306)

Stack 3/5. Merge order: #299 (`kumo.settings`), #318 (`StatSet`), then
this PR (it contains #318's commits; review the commits after #318),
then #307 (Text tokenizers trained inside DiskGraph), then #324 (fitting
without samples).

## Summary

In kumo-pytorch, an encoder over a **stored table column** now fits on
the table's rows created at or before an *encoder cutoff*, not on the
training examples. This covers `Vocabulary`, `ZScore` and
`Buckets(bins=N)` over an entity field, an event field or a graph node
field.

The numbers come from **DiskGraph's existing col-stats pipeline**, the
`FileColStats` and `TableCategoryCounts` collectors behind
`col_stats.json`:
- `Vocabulary` uses the Hybrid category counts, capped at 1M distinct
values.
- `ZScore` uses Welford's mean and standard deviation.
- `Buckets` uses the t-digest.

This PR adds three hooks to that pipeline:
1. A per-row cutoff gate during ingest.
2. A recompute that reads an index's stored rows and drives them through
the Arrow driver `compute_col_stats_for_parquet` already uses.
3. t-digest quantiles published on request.

It also fills gaps in the pipeline, listed under "Statistics added to
the pipeline" below. Both routes write the existing `col_stats.json`
format, one file per table, under `<index>/col_stats/<cutoff dir>/`. A
column's statistics are requested by #318's `StatSet`, so one pass
computes everything a column needs.

> **Behaviour change.** An encoder over a stored column learns from
every table row created at or before the cutoff, **whatever `fit_split`
selects**. Rows of held-out or unassigned entities count too.
Vocabularies, z-score statistics and bucket cuts change, and so do model
metrics. These still fit on the examples, as before: per-anchor values
(aggregates, calculations, targets), `Text` (until #307), and an encoder
shared through `UseEncoding` with a per-anchor value.

> **Not in this PR.** Fitting still builds samples. `Plan.materialize`
still fetches every fitting anchor, and `fit_plan` still builds samples
whenever anything needs fitting, even when every input encoder is pinned
from statistics. A follow-up PR stacked on #307 removes that.

## What changes for users

### kumo-pytorch

| API | Accepts | Default | Errors and warnings |
| --- | --- | --- | --- |
| `Plan.materialize(..., encoder_cutoff=...)` | ISO 8601 string
(validated by `datetime.fromisoformat`, its value exact to the
nanosecond from `diskgraph.resolve_temporal`), epoch seconds (`int`, as
an anchor takes them), `datetime`, `date`, or `None` (every row) |
`LATEST_ANCHOR`: the latest anchor time in `fit_split` | `ValueError:
encoder_cutoff 'soon' is not an ISO 8601 timestamp`; `TypeError` for
other types. A cutoff later than the latest fitting anchor, or `None` on
a temporal contract, logs `encoder_cutoff … is after the latest fitting
anchor …`. |
| `DiskGraphEngine(..., encoder_cutoffs=[...])` | A list of the same
values | `()` | `TypeError: encoder_cutoffs is a list of cutoffs; wrap a
single one in a list` for a bare string. When an ingest builds the
index, the statistics for these cutoffs are computed in the same pass. |
| `FitRecord["statistics"]` (inputs only) | — | — | `{"cutoff": <epoch
nanoseconds or None>, "col_stats": ["<dir>/<table>.col_stats.json",
...]}`. Informational: fitted-state equality and fingerprints ignore it.
|

Other errors and warnings:
- `Vocabulary` over a column with more than 1M distinct values logs
`<table>.<column> has more distinct values than DiskGraph counts;
encoder … learns the ones it counted`.
- `ZScore` or `Buckets` over a column holding NaN or ±inf raises
`ValueError: encoder …: numeric transforms require finite values`.
- `Vocabulary` over a float column holding NaN or ±inf raises
`ValueError: float32 vocabulary values must be finite` (or the `float64`
equivalent).

### DiskGraph Python

| Function | Signature and return | Notes |
| --- | --- | --- |
| `diskgraph.ingest` | New keyword `cutoff_col_stats: str \| None =
None` (request JSON) | Collects during Encode and adds each table's
statistics to `col_stats/<dir>/<table>.col_stats.json` at the end of
Encode. The table name is percent-encoded in the file name: every byte
except ASCII letters, digits, `-` and `_`. Errors: `col_stats and
cutoff_col_stats are exclusive`, unknown table or column, `column …
requests more than one kind of category counts`, `one directory per
cutoff`, `each cutoff needs its own directory`, a non-local output. |
| `diskgraph.cutoff_col_stats(index_dir, request_json, num_threads=None)
-> None` | Recomputes the request from the index's stored rows and adds
it to the same files | The same validation. A column already in a file
keeps its keys and gains the new ones. |
| `diskgraph.convert_ticks(value, from, to, *, rounding="truncate") ->
int` | A value in one index clock as ticks of another; `rounding` is
`"truncate"` or `"floor"`. The encoder cutoff converts from
`nanoseconds` with `rounding="floor"`. The same binding as #310 |
`convert_ticks requires fixed index clocks`; `rounding must be truncate
or floor`; never raises on precision |

The request JSON:

```json
{"cutoffs": [1694608000, null],          // index-clock ticks; null counts every row
 "dirs": ["3f2a91c0d4e5b678", "…"],       // col_stats/<dir>/ of each cutoff
 "columns": {"events": {"amount": ["categorical", "numerical"], "channel": ["categorical"]}},
 "quantiles": [0.0, 0.0009765625, …, 1.0]} // t-digest quantiles every numerical column publishes
```

Each column lists the semantic types whose statistics it collects;
#318's `StatSet` collects all of them in one pass.

### DiskGraph Rust

| API | Added or changed |
| --- | --- |
| `IngestOptions::cutoff_col_stats: Option<CutoffColStatsRequest>` | New
option, default `None` |
| `cutoff_col_stats::{CutoffColStatsRequest, CutoffTable, CutoffSinks}`
| New module. `columns` maps table → column → `Vec<SemanticType>`, built
into #318's `StatSet`; `CutoffTable::sinks() -> Result<CutoffSinks>` |
| `column_scan::{node_chunks, scan_chunk, ScanBudget, create_times,
at_cutoff}` | New module: a chunk's stored rows in batches of at most
about 128 MiB of decoded values, each admitted by a `ScanBudget`
(ingest's `ByteBudget`) shared by the workers; #307 builds its text scan
on it |
| `ColumnValueObserver::{observe_bytes, observe_decimal, observe_u64,
wants_create_time, start_row, finish_row}` | New default methods.
`observe_decimal` defaults to `observe_f64` and `observe_u64` to
`observe_i64` of the value's bits, so other observers see the same calls
as before; `finish_row(stored)` follows each encoded row. |
| `FloatListView`, `IntListView`, `StringListView` and their value enums
| Derive `Clone` |
| `FileColStats::{with_quantiles, collects, counts_categories}`,
`col_stats::bytes_hex` | New; `collects` and `counts_categories` look at
every collector of a column |
| `decimal_i128_to_f64`, `decimal_i256_to_f64`, `format_decimal_i128`,
`format_decimal_i256` | Made public |
| diskgraph-ingest's `serde_json` | `raw_value` feature, so values
already in a file are copied as written |
| `diskgraph_rowpack::builder_value_bytes` | New: the decoded value
bytes in a builder from `make_arrow_builder` |
| `TDigestEstimator` merge and quantile | Each mean is weighed
separately when a sum or difference overflows near ±f64::MAX; other
values are unchanged |
| diskgraph-pybind crate version | 0.1.0 → 0.2.0, so
`diskgraph.__version__` matches the package |

### Statistics added to the pipeline (every col-stats consumer)

| Encoder and column type | Gap | Fix | Lines |
| --- | --- | --- | --- |
| `Vocabulary` over `timestamp` | Categorical timestamp columns had no
counts | `FileColStats::observe_timestamp` counts them, keyed by
index-clock ticks | ~5 |
| `Vocabulary` over `bytes` | Ingest never observed bytes values |
`encode_row_observed` calls `observe_bytes`; `FileColStats` counts
lowercase hex (`bytes_hex`, now shared with the Arrow driver) | ~17 |
| `Vocabulary` over decimals | Keys were the f64 rendering, so wide
decimals collided | `observe_decimal` gives categorical columns the
exact decimal string, on both routes | ~25 |
| `ZScore`/`Buckets` over `decimal256` | Ingest never observed
`decimal256` | Observed through `observe_decimal` | ~6 |
| Any encoder over `uint64` values of 2^63 and above | They were
observed as their bits reinterpreted as an `i64`, so moments, quantiles
and value bins saw negative numbers, and counts were keyed by them |
`observe_u64` on both routes: numerical statistics see the value as an
`f64`, and category counts key it by its exact decimal text | ~30 |
| Any encoder over `date32` or a decimal, recompute route | The Arrow
driver refused these types | `drive_from_arrow_column` reads them as
ingest observes them | ~25 |
| `Buckets(bins=N)` | Only q25/q50/q75 were published | Requested
t-digest quantiles appear as `"quantiles"` | ~15 |

## How it works

1. **Which encoders qualify** (`kumo/pytorch/column_stats.py:
table_column_encoders, _learns_from_stats`). An unpinned `Vocabulary`,
`ZScore` or `Buckets(bins=N)` qualifies when every use reads a stored
column directly; `ZScore` and `Buckets` additionally need a numeric
dtype. A `UseEncoding` shared by several stored columns combines them;
one shared with a per-anchor value keeps the old path.
2. **The request** (`column_stats.py: stats_request`,
`TableColumnEncoder.requests`).
- `Vocabulary` asks for its columns' `categorical` statistics (counts);
`ZScore` and `Buckets` ask for `numerical` (moments, t-digest, value
bins).
- A column read by several encoder kinds is requested once, with every
type it needs.
- Every request carries the quantile grid (1,025 probabilities), which
every numerical column publishes.
- Cutoffs that land on the same index-clock tick are requested once
(`materialization.py: ensure_diskgraph_index`).
3. **Ingest route** (`diskgraph-ingest/src/lib.rs`).
- In the Encode loop, `CutoffSinks` (`cutoff_col_stats.rs`) holds one
`FileColStats` per cutoff, built with #318's `new_with_stat_sets`.
- Before each row is encoded, `write_node_row_from_access` reads its
create time with `access.get_timestamp` and calls `start_row`, which
marks the cutoffs that include the row.
- The requested columns' observations are held in buffers reused across
rows (`Row`: one `Vec` of values, one `String`, one byte `Vec`). Once
warm, a row allocates nothing, except to format a categorical decimal's
exact text and to copy a list column parsed from text.
- After the row passes ingest's null-create-time drop and the
`MAX_NODE_DATA_LEN` check, `finish_row(true)` replays the observations
into each marked cutoff's `FileColStats`, which feeds every collector of
the column. A row the index doesn't store calls `finish_row(false)` and
counts nowhere.
   - Worker sinks are merged with `FileColStats::merge`.
- At the end of Encode, each cutoff's tables are published as described
in step 7.
4. **Recompute route** (`diskgraph-pybind/src/cutoff_col_stats.rs:
from_index`).
- Chunks of 65,536 nodes (`column_scan::node_chunks`) are scanned in
parallel with `scan_chunk`. It decodes rows one at a time into Arrow
builders with `decode_row_to_builders`, as the engine's feature fetch
does, and hands over a batch once its decoded values reach 128 MiB
(`builder_value_bytes`). This matters because dictionary, LZ4, BPE and
alphabet strings can decode to far more than they store.
- Before decoding a batch, a worker takes a permit from one
`ScanBudget`: ingest's `ByteBudget`, sized as ingest sizes Encode's (a
third of the machine's or cgroup's memory, at least 1 GiB). A batch that
ends below 128 MiB shrinks its permit to what it holds. One that ends
above, such as a single larger row, trades its permit for one of its
actual size, through ingest's oversized path.
- Each batch is filtered per cutoff (`create_times`, `at_cutoff`) and
driven through the existing `bp_col_stats::drive_from_arrow_column` into
the same sinks. Values are dispatched on their stored type, as ingest
observes them.
- Results merge in chunk order, then publish as in step 7. Windows of
four chunks per worker keep a few sinks per worker alive at once.
5. **In memory** (`engines/in_memory/source.py: column_stats`). The rows
of the requested tables, normalized to their dtypes, are written to
Parquet and ingested into one temporary index, and `read_column_stats`
computes the request from it.
6. **Encoders from the numbers** (`column_stats.py: fit_from_stats`).
- **`Vocabulary`**: from `category_counts`, ordered as `fit_encoder`
orders them, with `min_frequency` and `max_size` applied.
- **`ZScore`**: Welford's mean and sample standard deviation, converted
to the population standard deviation and combined exactly across
columns.
- **`Buckets`**: each column publishes its t-digest at the 1,025 grid
points. The N cuts are interpolated from the combined distribution of
the encoder's columns. `separate_zero` first removes the exact zeros,
counted from `value_bins`.
7. **Storage and reuse** (`column_stats.py: read_column_stats`;
`cutoff_col_stats.rs: publish`).
- `<dir>` is the first 16 hex characters of the sha256 of
`[COL_STATS_RECIPE, cutoff ticks, clock unit]`. `COL_STATS_RECIPE = 1`
is a format version, bumped whenever a request's statistics change.
- kumo-pytorch reads `<dir>/<table>.col_stats.json` for each requested
table and asks DiskGraph only for the column statistics those files
lack: `category_counts` for categorical, `mean` for numerical.
- DiskGraph writes each table with `write_col_stats` into a temporary
directory beside the files. Holding an exclusive lock on the directory's
`.lock` file, it adds the new columns, and the new keys of columns
already there, copying every value as written. It then syncs the file
and replaces the old one with a rename.
- An Encode retry deletes `col_stats/` with the rest of Encode's outputs
(`wipe_phase_outputs`), so a failed attempt's statistics never survive
into the retry.
   - `fitted=` and `inference=True` read nothing.

## Storage

`<index>/` after the first `materialize` (from the 200M-row benchmark
index):

```
before                         after
index/                         index/
├── diskgraph_config.json      ├── diskgraph_config.json
├── index_manifest.json        ├── index_manifest.json
├── index_metadata.json        ├── index_metadata.json
├── ingest_stats.json          ├── ingest_stats.json
└── nodes/…                    ├── nodes/…
                               └── col_stats/
                                   └── 3f2a91c0d4e5b678/          one per encoder cutoff
                                       ├── events.col_stats.json  DiskGraph's col_stats.json format, one table
                                       └── users.col_stats.json
```

From `events.col_stats.json` (lists truncated):

```json
{"events": {"amount": {"semantic_type": "numerical", "count": 150003117, "null_count": 0, "invalid_count": 0, "mean": 33.1167359324272, "std": 43.410330297599934, "q25": …, "quantiles": [0.08, 0.9098560657984863, …], "value_bins": [[0.078125, 1], …], …},
            "channel": {"semantic_type": "categorical", "count": 150003117, "null_count": 0, "category_counts": [["channel_01", 39380114], …], "category_counts_capped": false, …}}}
```

A column requested as both types holds both sets of keys; shared keys
(`semantic_type`, `count`, `num_unique`) come from the categorical
statistics.

## Semantics to check

- **Cutoff.** A string cutoff must read as `datetime.fromisoformat`
reads it, so impossible dates and bare digits are refused. Its value is
taken exactly from `diskgraph.resolve_temporal`, the parser ingest uses,
when that parses it too: `2024-01-01T00:00:00.000000001Z` is
`1704067200000000001`. A `date` or `datetime` is normalized by the same
parser, keeping a pandas `Timestamp`'s nanoseconds. An `int` stays epoch
seconds. The latest-anchor default converts the latest anchor time once,
through the same function, so it and an explicit cutoff at the same time
agree. The encoder cutoff floors to the index clock, as kumo-pytorch
floors anchors (`convert_ticks(..., rounding="floor")`, from
nanoseconds), so encoders count exactly the rows history can see. Before
the epoch, flooring and truncating differ: −0.5 s is second −1, not 0. A
row counts when its create time in index-clock ticks is at or before the
cutoff's tick. On a coarse clock, rows in the anchor's own tick are
excluded, because ingest rounds their create times up. A sub-second
cutoff on a nanosecond index is exact.
- **Rows the index doesn't store.** Ingest drops a row whose create time
is NULL or doesn't parse, and stores a row with more than 64 MiB of node
data without its values. Neither route counts these rows, at any cutoff
or at `None`.
- **`NON_TEMPORAL` tables** count every row at every cutoff.
- **A list of cutoffs.** One sink per cutoff; each row reaches every
cutoff that includes it.
- **`fit_split`** no longer limits these encoders. See the behaviour
change above.
- **One pass per column.** A column requested with several types is
observed once and feeds every collector. A decimal gives its categorical
collector the exact text and its numerical collector the value.
- **Statistics added later.** A column already in a file keeps every key
it has and gains the new ones, the rule #318 uses within one pass.
Adding numerical statistics to a categorical entry gives exactly the
one-pass entry. In the other order, the shared keys (`semantic_type`,
`num_unique`) come from the numerical pass; encoders don't read them,
and `count` and `null_count` agree either way.
- **Approximation.**
- Buckets cuts come from a t-digest; the tests accept each cut within
1.5 ranks of the exact quantile.
- The digest depends on how the index splits rows into shards, so a
3-shard and a 1-shard index give cuts up to a few ranks apart.
Conformance compares Buckets cuts across engines within 3 ranks
(`BUCKET_RANKS`), where a cut's rank is the number of values below it,
matching how encoding assigns a value equal to a cut to the upper
bucket.
  - `num_unique` is HyperLogLog.
- Means agree with exact values to about 1e-13 relative; across shard
counts they differ in the last bits.
- **Run-to-run variation.**
- Recompute is stable except for capped vocabularies: the same index
wrote byte-identical files twice, unless a column passes the 1M-value
cap, where which values concurrent workers admit first can differ (see
below).
- Ingest is not: encode workers pull batches from a shared stream, so
t-digest quantiles and the last bits of the mean can differ between two
ingests of the same data. Category counts below the cap do not.
- **Recompute memory.** Decoded values in flight stay within the
`ScanBudget`: each worker holds at most about one 128 MiB batch, plus at
most one row past it. Filtering a batch per cutoff copies at most one
more batch per worker, outside the budget.
- **Capped vocabularies.** Past 1M distinct values, the counts cover the
first 1M values DiskGraph admits as it scans, and those counts are
exact. A value first seen after the cap is not in the vocabulary, and a
warning names the column. With several encode or recompute workers,
which values are admitted can differ between runs.
- **uint64.** Both routes observe a `uint64` as unsigned. Values below
2^63 are observed as before. From 2^63 up, moments, quantiles and value
bins see the value as an `f64`, and category counts key it by its exact
decimal text.
- **Values near the float limits.** Buckets cuts stay finite for columns
near ±1.8e308.

## Back-compat

| Case | Behaviour |
| --- | --- |
| Indexes built before this PR | Work; statistics are computed on first
use into `col_stats/<dir>/<table>.col_stats.json` |
| Fitted states and artifacts written before this PR | Load unchanged; a
fit record without `statistics` is fine |
| Artifacts written by this PR, read by older kumo-pytorch | Load; the
extra `statistics` key is ignored |
| `diskgraph.ingest` without `cutoff_col_stats` | The same index files |
| Existing `col_stats.json` and `compute_col_stats_for_parquet` users |
Unchanged, except for the gaps filled above: categorical timestamp and
bytes columns now get counts, `decimal256` is observed, categorical
decimals are keyed exactly, and `uint64` values of 2^63 and above are
observed as unsigned (they were negative `i64` bits on ingest, and parse
failures in `compute_col_stats_for_parquet`). The Arrow driver gains
date and decimal arms, which only the recompute route reaches:
`compute_col_stats_for_parquet` still never receives those types,
because kumo's dtype map and `validate_stats_dtype` keep them out |
| DiskGraph builds without these functions | DiskGraph's version goes to
0.2.0 and kumo-pytorch requires `diskgraph>=0.2.0`, so an older build is
rejected at install instead of failing at fit time. kumo-core and
kumo-engine keep `diskgraph>=0.1.0`; they don't call the new functions.
|
| Supplied encoder state (`Vocabulary(values=...)`, `ZScore(mean=...,
scale=...)`, `Buckets(boundaries=...)`) | Unchanged; no statistics read
|
| Out-of-tree engines without `column_stats` | Keep the old fitting path
|

## Production questions

| Question | Answer |
| --- | --- |
| Cost (200M event rows, 64 cores; see the benchmark) | Ingest takes
34.3–37.3 s without the statistics and 37.9–41.3 s with them, on a
loaded box. Recompute from the index takes 13.6–15.2 s. Reuse reads one
file per table, and a later fit computes only the columns and statistics
those files lack. |
| Memory | Recompute holds at most about 128 MiB of decoded values per
worker, within ingest's Encode budget across workers, so wide or
dictionary-expanded strings no longer scale with the 65,536-row chunk:
70,000 rows of 40,000-character strings peaked at 0.28 GiB, down from
2.47 GiB. On the 200M-row benchmark, recompute peak RSS was 9.7 GiB,
down from 10.0 GiB, mostly mapped index pages. Ingest peak RSS was
20.7–20.9 GiB with or without the statistics. The category counts are
dropped at the end of Encode. |
| Concurrency | Each writer writes a table to its own randomly named
temporary directory, then, holding an exclusive lock on the cutoff
directory's `.lock` file, merges into the table's file, syncs it and
renames it into place. Readers take no lock and see the old or the new
file, never a partial one. Two writers never drop each other's columns.
|
| Read-only index | Fitting writes `col_stats/` into the index
directory, which must be writable. Scoring with `fitted=` writes
nothing. |

## Testing Done

On the final head e30b26d, with DiskGraph built from that tree,
targeted tests (the full suite, conformance and the benchmark table
below ran on 137c11a):

- `pytest diskgraph-pybind/python/tests/test_cutoff_col_stats.py`: 9
passed on e30b26d. At a cutoff and at `None`:
- ingest's counts, means, standard deviations and quantiles match a
`Counter` and numpy over the rows at or before the cutoff, for strings,
bytes, timestamps, dates, ints and decimals, with the create time an
int64 millisecond column;
- an int column and a decimal column are each requested as categorical
and numerical in one pass, and get both;
  - a table without a create time counts every row;
- a `uint64` column holding 0, 5, 2^63 and 2^64−1 gets exact counts, the
numpy mean and standard deviation, and quantiles within its range, as
categorical and numerical in one pass;
- recompute equals ingest, including that `uint64` column, when one
column's numerical statistics are added by a second request;
- a row whose create time doesn't parse, a NULL create time and a row
with 65 MiB of node data count on neither route, and ingest equals
recompute;
- refusals: repeated directories, and two kinds of category counts for
one column;
- on a milliseconds and a days clock, a row later in the cutoff's own
tick is excluded, and a sub-second cutoff on a nanosecond index is
exact; recompute counts these as ingest does;
- `convert_ticks` floors −0.5 s to −1 and truncates it to 0, and both
give 1 for 1.5 s;
- a recompute over 70,000 rows of 40,000-character strings (about 2.8 GB
decoded from a 1.1 MB index) counts correctly, in budgeted batches.
- `cargo test -p diskgraph-ingest --test column_scan`, on e30b26d:
70,000 rows of three 1 KiB dictionary-encoded strings (68 MiB decoded,
two chunks), scanned by two workers under a 1.5 MiB budget with 1 MiB
batches. Every batch holds at most 1 MiB plus one row, every row is
counted once, and the budget's high-water mark stays within 1.5 MiB.
- `pytest --require-imports tests` (kumo-pytorch, full suite, as CI runs
it), on 137c11a: 1907 passed, 3 skipped. On 9984c23,
`test_column_stats.py`, `test_fitted_state_persistence.py`,
`test_api_reference.py` and `conformance/test_field_semantics.py` gave
46 passed. They include:
- `tests/test_column_stats.py`: encoders against numpy on both engines
at three cutoffs; Buckets within 1.5 ranks; `Vocabulary` over every
stored column type on both engines; shared encoders; warnings; one
directory per cutoff with a file per table, one request for a column
that two encoder kinds read, and a later fit that requests only the
added column and leaves the file's other entries unchanged; a table
named `../items/x y` on both engines, in
`%2E%2E%2Fitems%2Fx%20y.col_stats.json`; Buckets over ±1.7e308 giving
finite, sorted cuts;
- `tests/test_field_outputs.py`: wide decimals and the other numeric
outputs keep engine and delivery parity;
- the updated expectations in `test_anchor_tables.py`,
`test_fitted_state_persistence.py` and
`conformance/test_field_semantics.py`, and `test_docs_code.py` with the
serving page's printed scores.
- `python -m conformance --engine all`, on 137c11a: 701 passed. On
9984c23, its `fitted_state` property: 5 passed.
- `cargo test -p diskgraph-ingest --lib`, on 137c11a: 488 passed. On
9984c23, diskgraph-core lib: 134 passed. On e3559b1,
diskgraph-rowpack: 318 passed; diskgraph-ingest lib: 488 passed;
diskgraph-pybind lib: 121 passed; `test_column_stats.py`: 13 passed.
`cargo clippy --workspace --all-targets -D warnings`, `ruff check`,
`ruff format --check` and vulture are clean.
- `pytest -m notebook tests/test_notebooks.py`: 3 passed on 4075e78;
the committed `output_schema.json` files reproduce. The commits since
change no fitted state.
- **Benchmark, on the final code.** 200M event rows plus 4M users, 64
cores, 8 shards; the cutoff keeps 150,003,117 events. Requested:
`events.amount` numerical, and `events.channel`, `events.quantity` and
`users.country` categorical. Each step ran in a fresh process on a
shared box.

  | Step | Runs | Wall | Peak RSS |
  | --- | --- | --- | --- |
  | Ingest, no statistics | 3 | 34.3–37.3 s | 20.8–20.9 GiB |
| Ingest with the statistics (`encoder_cutoffs`) | 3 | 37.9–41.3 s |
20.7–20.9 GiB |
| Recompute from the index (`cutoff_col_stats`) | 3 | 13.6–15.2 s |
11.5–11.8 GiB |

  Load average 25–34, with another test run on the box.

Bounded decode (e30b26d) against the commit before it (4d23550),
recompute only, alternating fresh processes, load average 1–38 and
rising:

| Recompute | Runs each | Before: wall, peak RSS | After: wall, peak RSS
| Cores |
  | --- | --- | --- | --- | --- |
| 200M-row benchmark | 6 | 9.1–14.6 s, 10.0 GiB | 8.9–13.9 s, 9.7 GiB |
49–53 both |
| 32M-row wide table, 4 columns | 3 | 3.22–3.25 s, 4.5 GiB | 3.25–3.28
s, 4.46 GiB | 30–32 before, 31–33 after |
| 70,000 rows of 40,000-character strings (two chunks) | 3 | 2.19–2.20
s, 2.47 GiB | 2.16 s, 0.28 GiB | 1.1 both |

The 200M walls are bimodal (about 9 s or 14 s) on both builds as the
load changed. Statistics are byte-identical between the builds, except
the wide table's capped `d0` vocabulary, which also differs between two
runs of the old build.

- **Wide table, on the final code.** 32M rows of 26 columns (8 strings,
6 decimals, 12 numbers and times), 4 requested at one cutoff (a float
and a decimal as numerical, a string and a decimal as categorical):
ingest takes 11.7–13.2 s without the statistics and 13.7–14.4 s with
them (3 runs), with identical statistics on every run.

- **GPU end to end:** not rerun on this code; the tiers need a rerun.

## Where to look

1. `packages/diskgraph/diskgraph-ingest/src/cutoff_col_stats.rs`: the
request, stat sets per column, the per-cutoff sinks, and `add_to_file`.
2. `packages/diskgraph/diskgraph-ingest/src/lib.rs`: the `start_row` and
`finish_row` calls in `write_node_row_from_access`, the cutoff branch of
the encode closure, and the publish after `write_col_stats`.
3. `packages/diskgraph/diskgraph-pybind/src/cutoff_col_stats.rs` and
`packages/diskgraph/diskgraph-ingest/src/column_scan.rs`: recompute from
the index.
4. The pipeline additions: `diskgraph-ingest/src/col_stats.rs`
(`observe_timestamp_at`, `observe_bytes_at`, `observe_decimal_at`,
`observe_u64_at`, `with_quantiles`, `collects`, `counts_categories`),
`diskgraph-rowpack/src/lib.rs` (`ColumnValueObserver`,
`encode_row_observed`) and `diskgraph-pybind/src/bp_col_stats.rs`
(`drive_from_arrow_column`).
5.
`packages/experimental/kumo-pytorch/src/kumo/pytorch/column_stats.py`:
qualification, `stats_request`, `read_column_stats` and
`fit_from_stats`.
6. `preparation.py` (`_pinned_from_stats`), `engines/diskgraph.py`,
`engines/in_memory/source.py`, `materialization.py` and `assembly.py`:
the flow.
7. The tests, `conformance/properties.py` (`BUCKET_RANKS`), then the
docs and regenerated outputs.

## Change map

[File-by-file change
map](#306 (comment)).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
The tokenizer trainer and token lengths read the column through #306's
byte-budgeted scan_chunk, as 32-bit strings, a chunk's batches adding into
its lengths.

Co-Authored-By: Claude <[email protected]>
@Vedaant-J
Vedaant-J marked this pull request as ready for review November 13, 2026 10:50
Co-Authored-By: Claude <[email protected]>

# Conflicts:
#	packages/diskgraph/diskgraph-ingest/src/column_scan.rs
#	packages/diskgraph/diskgraph-ingest/tests/column_scan.rs
#	packages/diskgraph/diskgraph-pybind/python/diskgraph/__init__.py
#	packages/diskgraph/diskgraph-pybind/src/cutoff_col_stats.rs
#	packages/diskgraph/third_party/artifact-manifest.json
#	packages/experimental/kumo-pytorch/docs/03-encodings-and-ids.md
#	packages/experimental/kumo-pytorch/docs/04-engines-and-data.md
#	packages/experimental/kumo-pytorch/docs/api/artifacts-and-serving.md
#	packages/experimental/kumo-pytorch/src/kumo/pytorch/artifact.py
#	packages/experimental/kumo-pytorch/src/kumo/pytorch/column_stats.py
#	packages/experimental/kumo-pytorch/src/kumo/pytorch/encoding.py
#	packages/experimental/kumo-pytorch/src/kumo/pytorch/engines/diskgraph.py
#	packages/experimental/kumo-pytorch/src/kumo/pytorch/engines/in_memory/source.py
#	packages/experimental/kumo-pytorch/src/kumo/pytorch/preparation.py
Co-Authored-By: Claude <[email protected]>

# Conflicts:
#	packages/experimental/kumo-pytorch/src/kumo/pytorch/preparation.py
@Vedaant-J
Vedaant-J had a problem deploying to gha-kumo-workflow-tests November 13, 2026 10:55 — with GitHub Actions Error
Base automatically changed from vedaant/text-from-index to main November 13, 2026 10:56
Vedaant-J added a commit that referenced this pull request Nov 13, 2026
…#307)

Based on main. #299 (`kumo.settings`), #318 (`StatSet`) and #306 (column
statistics with an encoder cutoff) are merged; #324 (fit without
samples) is stacked on this PR.

## Summary

A learned `Text` encoder over a **stored string column** now trains its
byte-level BPE tokenizer on that column's table rows created at or
before the encoder cutoff, like #306's table-column encoders. DiskGraph
trains it. `diskgraph.train_tokenizer` decodes the column through #306's
chunk decoder (`column_scan::scan_chunk`, byte-budgeted) and cutoff
filter, so it covers exactly the rows #306's statistics count. Each
worker pre-tokenizes the values it decoded into its own word counts; the
counts are summed, and the `tokenizers` crate's BPE trainer runs once on
them. The crate is pinned to the version and regex engine (Oniguruma)
the `tokenizers` Python wheel is built from, so the tokenizer JSON is
byte-for-byte what `train_from_iterator` produces on the same values.
Python receives only that JSON. The tokenizer is kept in the cutoff's
`<index>/col_stats/<dir>/` beside #306's statistics, and later tasks
reuse it.

A fit on the DiskGraph engine with `Batching.length_input` set also
records each event table's token cost per event, for the tables that
input reads: a constant for columns without `Text`, plus a raw `u16`
per-node file of `Text` pieces when the input reads `Text`. A batch
planner reads them before sampling (see "Per-row token lengths").

The PR also makes two batch-time changes, described under "Speedups"
below:
- text encoding writes into preallocated arrays;
- the length summary measures records in chunks.

> **Behaviour change.** A learned `Text` over a stored column learns
from that table's rows created at or before the encoder cutoff, whatever
`fit_split` selects, instead of from the training examples. `Text` over
per-anchor values (aggregates, calculations) still fits on the examples,
fed in batches. Supplied tokenizer state (`Text(state=...)`) is
unchanged, except that its padding no longer applies (see Back-compat).

As in #306, fitting still builds samples; the follow-up PR stacked on
this one removes that.

## What changes for users

| Where | API | What it does |
| --- | --- | --- |
| kumo-pytorch | none new | #306's `encoder_cutoff` now also applies to
a learned `Text` over a stored string column.
`DiskGraphEngine(encoder_cutoffs=...)` does not: ingest computes only
statistics, and a tokenizer trains on the first fit at its cutoff. |
| kumo-pytorch | `FitRecord["statistics"]["col_stats"]` | Also lists the
tokenizer file of each tokenizer read or trained. |
| DiskGraph Python | `diskgraph.train_tokenizer(index_dir, columns,
cutoff, *, vocab_size, min_frequency, special_tokens, unk_token,
num_threads=None) -> str` | The JSON of a byte-level BPE tokenizer
trained on the non-null values of `columns` (`(table, column)` pairs)
over the rows counted at `cutoff` (index-clock ticks; `None` counts
every row), as `tokenizers`' `train_from_iterator` trains it on those
values |
| DiskGraph Python | `diskgraph.TOKENIZER_TRAINER` | The `tokenizers`
crate and regex engine the trainer is built on (`"tokenizers 0.23.2
onig"`), part of the tokenizer cache key |
| DiskGraph Python | `diskgraph.token_lengths(index_dir, table, columns,
path, *, num_threads=None)` | Writes `path`: one little-endian `u16` per
node of `table`, its count over `columns` (a string column's pieces
under its tokenizer JSON, and a variable-length list's elements), NULL
counting 0, saturated at 65,535. A column with a fixed cost is refused
(see "Per-row token lengths") |
| kumo-pytorch | `column_stats.read_token_lengths(index, entry)` | A
table's `(constant, per_node)`: the per-event constant, and a read-only
memory map of the lengths file with one `uint16` per node ID, or `None`
without a file |
| kumo-pytorch | `FitRecord["statistics"]["token_lengths"]` | With
`Batching.length_input` set, `{"constant": n, "file": name or None}` for
each event table that input reads; `file` is relative to `col_stats/` |
| DiskGraph Rust | `column_scan::{stored_tables, StoredTable}`;
`node_chunks(table, size)` | The stored-table lookup the trainer shares
with #306's recompute; `node_chunks` takes a chunk size and is lazy |

`train_tokenizer` details:
- It decodes chunks of 1,024 nodes on `num_threads` threads with the GIL
released, and checks for Ctrl-C between windows of 1,024 chunks. The
final training step is not interruptible, as with `train_from_iterator`.
- It refuses an unknown table or column, and a non-string column (`…
holds Int64 values, not strings`), with `DiskgraphConfigError`, and
`num_threads=0`.

## How it works

1. **Which encoders.** `column_stats.py: _learns_from_stats` lets a
learned `Text` over a string column qualify.
`TableColumnEncoder.requests` is empty for it, because it needs no
col-stats.
2. **The trainer** (`diskgraph-pybind/src/cutoff_col_stats.rs:
train_tokenizer, word_counts`).
- `stored_tables` opens the tables and finds each create-time column;
each column must hold strings.
- Chunks of 1,024 nodes (`node_chunks`; #306's recompute keeps 65,536)
are decoded in parallel with #306's byte-budgeted `scan_chunk`, which
may hand a chunk over as several batches, and filtered with
`create_times` and `at_cutoff`. Between windows of 1,024 chunks the GIL
is taken back for `py.check_signals()`.
- The worker that decoded a chunk pre-tokenizes each non-null value with
the crate's `ByteLevel(add_prefix_space=false)` and counts the words in
its own map, one per pool thread. The maps are summed in thread order.
- `BpeTrainer::do_train` runs once on the summed counts, in the same
pool, with `train_text`'s settings: vocabulary size, minimum frequency,
special tokens, no progress bar, `BPE(unk_token)`. This is what
`train_from_iterator` does after its own word count, so the JSON is
identical. `min_frequency` stays where the trainer applies it, as the
stop condition of the merge loop.
- `tokenizers = "=0.23.2"`, default features off, only `onig`: the crate
and regex engine the 0.23.3 wheel is built from. `onig_sys` compiles the
Oniguruma C source it bundles.
3. **Per-anchor text** (`encoding.py: train_text`). Unchanged:
per-anchor `Text` trains with Python `tokenizers` on batches of 1,024
strings (`TRAIN_BATCH`, `_text_batches`). `TEXT_SPECIAL_TOKENS` and
`TEXT_UNKNOWN` are shared with the DiskGraph call.
4. **The cache** (`engines/diskgraph.py: DiskGraphSource.column_text`;
`column_stats.py: TableColumnEncoder.tokenizer_file`).
- Path:
`<index>/col_stats/<dir>/<table>.<column>.text-<settings>.tokenizer.json`.
`<dir>` is #306's cutoff directory (from the cutoff ticks, clock unit
and `COL_STATS_RECIPE`); `<table>.<column>` is the encoder's first
column; `<settings>` is the first 16 hex characters of the sha256 of
`[vocabulary_size, min_frequency, columns, TEXT_RECIPE,
diskgraph.TOKENIZER_TRAINER]`. A changed setting, recipe (`TEXT_RECIPE =
1`), trainer crate or regex engine never reuses a stale tokenizer. The
table and column are percent-encoded in the file name (#306's
`file_name_part`), and the cutoff reaches the index clock with
`convert_ticks(..., rounding="floor")`, from nanoseconds, as #306's
statistics cutoff does.
- The file holds `{"columns", "cutoff", "tokenizer", "sha256"}`. It is
reused when it exists and the sha256 of its tokenizer matches. A file
that doesn't parse, or whose digest doesn't match, is refused with `… is
not a valid tokenizer file; delete it to retrain`.
- It is written to an exclusively created, uniquely named file in the
same directory, with the umask's permissions, synced, then renamed over
the target.
5. **In memory** (`engines/in_memory/source.py: column_text`). Trains on
its own rows, normalized with the encoder's dtype, with the same filter
(create time at or before the cutoff; every row of a table without one)
using `train_text`. It gives the same tokenizer and caches nothing.

`<index>/col_stats/` after a materialize with a `Text` encoder on
`card_transactions.description`:

```
index/col_stats/
└── <dir>/                                                    one per encoder cutoff (#306)
    ├── card_transactions.col_stats.json                      #306's statistics
    └── card_transactions.description.text-<settings>.tokenizer.json
                                                              {"columns": [["card_transactions", "description"]],
                                                               "cutoff": {"value": 1733011200, "unit": "seconds"},
                                                               "tokenizer": "{\"version\":\"1.0\",…}", "sha256": "…"}
```

## Per-row token lengths

A fit on the DiskGraph engine with `Batching.length_input` set also
records, for each event table that input reads, the token cost of its
stored rows, for a planner that sizes batches before sampling. The cost
has two parts: a per-event constant for the columns whose cost does not
depend on the value, and a per-node count for the `Text` columns. The
counts describe the source data only. The per-input rules stay with the
consumer: `Tokens.max_tokens`, `missing`, Text's `empty="unknown"`,
Flatten markers and budget, `max_events`, aggregates and constants.

- **What a row counts.** The stored columns of the table that the
`Batching.length_input` input reads, each column once:
- a column whose cost does not depend on its value: 1, NULL included,
added to the constant. kumo-pytorch's stored columns are scalars, so
every non-`Text` column is one;
- a `Text` column: its pieces under the fitted tokenizer, with padding
off and no special tokens, as `FittedEncoder.encode_arrow` encodes it,
in the per-node file. A NULL text counts 0;
- a variable-length list: its element count, in the per-node file, with
a NULL list counting 0. Lists can't be declared yet (DG-NESTED-COLUMN),
so only `Text` reaches the file today.

  A row's cost is the constant plus its per-node count.
- A column the input reads through a Text encoder and another encoder is
a Text column, and counts its pieces once.
- Two Text encoders with different tokenizers on one column of the input
are refused as ambiguous.
- Columns only other inputs read are not counted, so adding or changing
another input leaves the record unchanged.
  - Graph-input node fields are not counted; only event rows are.
- Under `Tokens(missing="emit")` the constant equals each emitted
event's tokens, NULLs included. Under `missing="omit"`, the default, a
NULL value emits no token, so the constant overstates that event by its
NULLs.
- **What the record holds.** `FitRecord["statistics"]["token_lengths"]`
maps each event table to `{"constant": n, "file": name}`.
  - `n` is the per-event constant.
- `file` is the per-node file relative to `col_stats/`, or `None` when
the input reads no `Text` column of the table.
  - `FitRecord["statistics"]` also records `"cutoff"`.
- `read_token_lengths(index, entry)` returns `(constant, per_node)`.
`per_node` is a read-only memory-mapped `uint16` array indexed by node
ID, or `None` without a file.
- **Where.** `<index>/col_stats/<dir>/<table>.lengths-<hash>.bin`,
written only for a table with `Text` columns.
- `<dir>` is the fit's cutoff directory (#306), and `<table>` passes
through `file_name_part`.
- `<hash>` is the first 16 hex characters of the sha256 of the `Text`
columns, each one's tokenizer sha256, and `diskgraph.TOKENIZER_TRAINER`.
  - An existing file is reused.
  - The constant has no file: each fit derives it from the fitted plan.
- **Layout.** Raw little-endian `u16`, with no header: node ID `n` is at
byte offset `2 * n`.
- Node IDs run from 0, contiguous across shards, so no base or count is
recorded.
- A node stored without data (a row over the 64 MiB node-data limit), or
with empty data, gets 0 in the file. The constant still applies to it.
- Rows ingest dropped (NULL create time, duplicate keys) are not nodes
and have no slot.

```
index/col_stats/<dir>/
├── card_transactions.col_stats.json
├── card_transactions.description.text-<settings>.tokenizer.json
└── card_transactions.lengths-<hash>.bin      u16 LE per node ID: 03 00 05 00 00 00 …  → 3, 5, 0, …
```

Take `length_input="transactions"` reading `amount` (Buckets), `channel`
(Vocabulary) and `description` (Text) from `card_transactions`. The
record is `{"constant": 2, "file":
"<dir>/card_transactions.lengths-<hash>.bin"}`, and the file holds each
node's description pieces. Without `description`, the record is
`{"constant": 2, "file": None}` and no file is written.
- **Cap.** A per-node count above 65,535 saturates at 65,535; it is not
an error.
- **When.** On a fit of the inputs with the DiskGraph engine whose
`Batching.length_input` is set, after the encoders are fitted.
- `max_tokens` and `bucket_by_length` already require `length_input`, so
every budgeted or bucketed fit gets the record.
- The constant needs no scan. DiskGraph decodes a table only when the
input reads a `Text` column of it, so a fixed-width-only recipe runs no
pass and writes no file.
- Without `length_input` nothing runs, and `FitRecord["statistics"]` has
no `"token_lengths"`.
- Reusing fitted state (`fitted=`) writes nothing, and the in-memory
engine records none, since it has no index.
- **How.** `diskgraph.token_lengths` is called with the per-node columns
only. It refuses any other column with `DiskgraphConfigError` (`… has a
fixed token cost; pass only list columns and string columns with a
tokenizer`).
- It decodes 1,024-node chunks with #306's byte-budgeted `scan_chunk`,
which passes each row's node with every batch.
- It counts in parallel with the GIL released, checks for Ctrl-C between
windows of 1,024 chunks, and writes each window's block with the GIL
released.
- The output goes through a hidden, uniquely named temporary file, which
is synced and then renamed.
- **Cost.** Measured before the constant split, with the scalar counted
per node.
- 100M rows of about 6 words, Text plus one scalar, 64 threads:
42.0–42.6 s (2.35–2.38M rows/s), a 200 MB file and 1.9 GiB of process
growth.
  - 10.9M rows: 23.7 / 11.9 / 5.7 / 4.3 s at 8 / 16 / 32 / 64 threads.
  - Extrapolated: about 7 min per 1B rows.
  - A table read without `Text` now costs no pass and no file.

## Speedups

These two changes were not measured on their own, and the end-to-end
tiers use no `Text`.

- **Batch text encoding** (`FittedEncoder.encode_arrow`). The text
branch tokenizes 65,536 strings at a time (`TEXT_BATCH`) with
`encode_batch_fast`, and writes piece IDs and offsets straight into
int64 arrays: offsets are preallocated, and the ID array grows
geometrically. It no longer builds a Python list per string. Missing,
empty and unknown values are handled as before: a NULL becomes the
missing ID, and an empty string becomes no pieces, or the unknown ID
with `empty="unknown"`. The output is identical (tested against
one-string-at-a-time encoding).
- **Length summary** (`PreparedBatchPlan`, `_LENGTH_CHUNK = 4096`).
Records are measured 4,096 at a time, keeping one length per sample, so
peak memory no longer holds every record's encoded text at once. This
bounds memory; it is not meant as a speedup. A DiskGraph
`ModelSourceBatch` is still measured whole.

## Back-compat

| Case | Behaviour |
| --- | --- |
| `Text(state=...)` | Unchanged, except padding: encoding turns the
tokenizer's padding off, because the output is ragged IDs with offsets.
A padded state used to emit pad IDs that depended on which strings
shared an encode call; it now gives the unpadded IDs. |
| Learned `Text` over a per-anchor value | Fits on the examples, fed in
batches |
| Learned `Text` over a stored string column | Learns from table rows up
to the cutoff (the behaviour change) |
| Encoded batches | The same piece IDs and offsets as before for
unpadded tokenizers, NULL, empty and `empty="unknown"` included |
| Artifacts and fitted states | Unchanged format |
| Indexes from before this PR | Work; tokenizers are trained on first
use |
| DiskGraph builds without `train_tokenizer` | Builds older than 0.2.0
are rejected at install by #306's `diskgraph>=0.2.0` floor. This PR adds
`train_tokenizer` to the same, still unreleased, 0.2.0; kumo-pytorch's
CI builds DiskGraph from the same commit. |
| Engines without `column_text` | Keep the old fitting path |

## Production questions

| Question | Answer |
| --- | --- |
| Memory while training | Word counts take about 200 B per distinct word
(one entry per worker that saw the word, then the summed map); the
crate's trainer then takes about 0.8 KB per distinct word, as in
`train_from_iterator`. 10.9M rows (5,000 distinct): 0.26 GiB growth (was
0.29 GiB streamed, 3.31–3.33 GiB from one list). 100M rows (7.8M
distinct): counts 0.97 GB per-thread plus 0.48 GB summed, 6.9 GiB peak.
1B rows (45.8M distinct): 7.7 GB plus 1.9 GB, 36 GiB peak in the
trainer. |
| Speed | 10.9M rows, 64 threads: 3.55–4.26 s (was 20.7–21.1 s streamed,
18.7–19.8 s from a list), same tokenizer. 100M rows: 118–148 s, about
119 s in two of three runs (counting 31 s, summing 4 s, crate training
82 s), against 294 s for `train_from_iterator` fed from Parquet with the
same tokenizer. 1B rows: 969 s (counting 381 s at 2.6M rows/s, summing
35 s, training 552 s). At 2.6–3.2M rows/s, 25B rows would take about
2.2–2.7 h to count, an extrapolation; training time and memory follow
the number of distinct words. Reuse reads one file. |
| Determinism | DiskGraph threads {1, 4} × shards {1, 3} and both
engines train the same tokenizer (tested), byte-identical to
`train_from_iterator` (tested; by hand at 10.9M and 100M rows) |
| Concurrency | Each writer writes its own temporary file; two writers
write the same bytes, and the rename is atomic. The file gets normal
umask permissions, so other accounts sharing the index can read it. |
| Read-only index | As in #306, fitting writes `col_stats/`. Scoring
with `fitted=` reads nothing. |
| Native dependencies | Oniguruma, a C library: `onig_sys` compiles the
Oniguruma source it bundles, which is BSD-2-Clause. Its `COPYING` ships
in `THIRD-PARTY.txt`, and an `expression_overrides` entry in
`3rdparty/notices/policy.json` labels `onig_sys` `MIT AND BSD-2-Clause`
instead of the `MIT` its Cargo metadata declares. 29 new crates are in
`THIRD-PARTY.txt`. Wheels were built and tested only on x86_64 Linux: a
zig manylinux build gave a `cp311-abi3-manylinux_2_17_x86_64` wheel with
a GLIBC 2.17 floor; aarch64, Windows and macOS were not built. |

## Semantics to check

- The trainer counts exactly #306's rows: `create_time <= cutoff`, NULL
create times never stored, every row of a non-temporal table. As in
#306, rows the index doesn't store (an unparseable create time, more
than 64 MiB of node data) count nowhere.
- The tokenizer depends only on the word counts, not on row order or
thread count.
- `min_frequency` is the trainer's merge-loop stop condition, as in
`train_from_iterator`; rare words are not dropped before training.

## Testing Done

On 3ffaaa0 (main merged, the same tree as ecfcd73), with DiskGraph
built from that tree, targeted tests and the license checks; the full
suite and conformance last ran on 252c0db (full results below), and CI
runs them on this head:

- `pytest diskgraph-pybind/python/tests/test_train_tokenizer.py
diskgraph-pybind/python/tests/test_token_lengths.py
diskgraph-pybind/python/tests/test_cutoff_col_stats.py`: 13 passed. The
trainer part covers:
- at a cutoff the tokenizer learns the row at the cutoff and not the
next second's;
- the same JSON for train threads {1, 4} × index threads {1, 4} × shards
{1, 3};
- a table without a create time counts every row, and a row with a NULL
create time is never counted;
  - refusals raise `DiskgraphConfigError`.
- `test_token_lengths.py`: each node of a 3-shard table equals its
body's words under a whitespace tokenizer plus its list's elements, with
a NULL text or list counting 0, at threads {1, 4}; a node stored without
data gets 0; a 70,000-element list saturates at 65,535; no temporary
file is left. An unknown column, a scalar and a fixed-length array
(fixed token cost), a tokenizer on a non-string column, and
`num_threads=0` raise `DiskgraphConfigError`.
- `tests/test_text_from_index.py`, `test_column_stats.py` and
`test_fitted_state_persistence.py` on bc967fc, with
`test_api_reference.py`: 51 passed, the first including the mixed-script
column trained at 1 and 4 threads, byte-identical to `train_text`, and
the token-length tests: with `length_input` set, for a learned and for a
padded supplied tokenizer, the constant is 2 (amount, channel) and each
`card_transactions` node's file value is
`len(encoder.tokenizer.encode(description).ids)`, so constant plus file
equals the earlier per-row total, and a second fit reuses the file
untouched; a fixed-width-only budgeted recipe (Buckets + Vocabulary,
`Tokens(missing="emit")`, NULL channels) records `(2, None)` with
`diskgraph.token_lengths` patched to raise, writes no file, and every
emitted event has 2 tokens; a fit without `length_input` records
nothing; a second input reading `merchant_id` leaves the record and file
unchanged; a column a second encoder in the same input also reads counts
once, and two different tokenizers on one column are refused. `pytest
--require-imports tests` (kumo-pytorch, full suite), run once on the
tree just before 252c0db: 1911 passed, 3 skipped, 1 failed. The failure
was the thread-count test still deleting a `text-<hash>/` directory.
252c0db changes only that test, and `tests/test_text_from_index.py`
then passes 5 of 5. It covers:
- on both engines, the tokenizer equals one trained on the column
filtered to the cutoff;
- a second materialize reuses the kept file in the cutoff directory
untouched, and the file has the umask's permissions;
  - both engines and DiskGraph threads {1, 4} train the same tokenizer;
- a 2,000-row column of mixed scripts, emoji, combining marks, tabs,
newlines, runs of spaces and NULLs, trained from the index with 1 and 4
threads, equals `train_text`'s JSON exactly;
- chunked encoding equals one-string-at-a-time encoding across chunk
boundaries, also for a padding-enabled supplied state.
- `python -m conformance --engine all`, on 252c0db: 701 passed.
- License checks, as the `license_notice` and `licensing` jobs run them:
`check_cargo_license_metadata.py`, `generate_artifact_manifest.py
--check`, all five `gen_third_party.py --check` lines, the notice
generator unit tests (including the `expression_overrides` test),
`check_license_headers.py` and `check_python_license_metadata.py` all
pass. `cargo deny` was not run here.
- `cargo clippy --workspace --all-targets -D warnings` and rustfmt are
clean, and flake8 and isort are clean on the notice scripts. `ruff
check`, `ruff format --check` and vulture were clean on the kumo-pytorch
tree, which the change to Oniguruma doesn't touch.
- **Equality, by hand:** 3,000 Unicode rows × cutoffs {None, T0} ×
(vocabulary, min_frequency) {(300, 0), (2000, 2)} × threads {1, 4, 16} ×
shards {1, 3}: 24/24 byte-identical to `tokenizers` 0.23.3, also with
the zig-built manylinux wheel on Python 3.11. The 10.9M-row benchmark
gives `22c54696…`, and 100M rows gave `67ad5bf5…` from both routes.
- **Benchmark** (fresh process per run, 64 threads,
`Text(vocabulary_size=8000)`, shared box at load 12–80; measured on an
earlier head of this PR with the same trainer, before #306's
byte-budgeted scan):

  | Rows (distinct words) | Route | Wall | Peak RSS growth | Tokenizer |
  | --- | --- | --- | --- | --- |
| 10.9M (5,000) | DiskGraph trainer | 3.55 / 4.26 / 3.57 s | 0.26 GiB |
`22c54696…` |
| 10.9M | Before: streamed to Python | 20.7 / 21.1 s | 0.29 GiB |
`22c54696…` |
  | 10.9M | One Python list | 19.8 s | 3.33 GiB | `22c54696…` |
| 100M (7.8M) | DiskGraph trainer | 148 / 118 / 119 s | 6.8–6.9 GiB |
`67ad5bf5…` |
| 100M | Python `train_from_iterator` fed from Parquet | 294 s | 7.1 GiB
max RSS | `67ad5bf5…` (identical) |
| 1B (45.8M) | DiskGraph trainer, 1 run | 969 s | 36.3 GiB | `ebe76f99…`
|

- **Ctrl-C, by hand:** SIGINT 3.0 s into a 100M-row training raised
`KeyboardInterrupt` at 3.21 s.
- **GPU end to end:** not rerun on this code; the tiers need a rerun.

## Where to look

1. `packages/diskgraph/diskgraph-pybind/src/cutoff_col_stats.rs`:
`word_counts`, `train_tokenizer`, and `from_index` using
`stored_tables`.
2. `packages/diskgraph/diskgraph-ingest/src/column_scan.rs`:
`stored_tables`, `node_chunks`.
3.
`packages/experimental/kumo-pytorch/src/kumo/pytorch/engines/diskgraph.py:
DiskGraphSource.column_text`, and `column_stats.py:
TableColumnEncoder.tokenizer_file`: the cache.
4. `preparation.py: Plan._pinned_from_stats`: Text encoders pinned from
the tokenizer.
5. `encoding.py`: `train_text`, `_text_batches`,
`FittedEncoder.encode_arrow`; and `assembly.py`: the length summary.
6. `engines/in_memory/source.py: column_text`, the tests, then
`Cargo.toml`/`Cargo.lock`, the regenerated notices, and
`scripts/gen_third_party.py: validate` with the `expression_overrides`
entry in `3rdparty/notices/policy.json`.

## Change map

[File-by-file change
map](#307 (comment)).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
main is #307 squash-merged (cc54c40), whose tree equals 3ffaaa0, already merged here; every conflict resolves to this branch's side.

Co-Authored-By: Claude <[email protected]>
@Vedaant-J
Vedaant-J temporarily deployed to gha-kumo-workflow-tests November 13, 2026 10:57 — with GitHub Actions Inactive
@Vedaant-J
Vedaant-J merged commit 7e8f109 into main Nov 13, 2026
52 of 53 checks passed
@Vedaant-J
Vedaant-J deleted the vedaant/fit-without-samples branch November 13, 2026 10:59
Victsm added a commit that referenced this pull request Nov 13, 2026
…tatistics (#328)

Automatically fit scalar aggregate features and labels from statistics
of the selected training anchors. `Plan.materialize()` streams their
prepared values to Parquet and reuses DiskGraph's column collectors and
the existing encoder fitter; fitting no longer retrieves histories to
collect these values. Graph-field statistics keep their separate
global-cutoff contract.

Depends on #310/#332 and the merged encoder-fitting work
(#306/#307/#324). Native length planning is a separate child PR.

Validation: 55 focused materialization, fitting, type and native-batch
tests pass with a rebuilt native module; Python lint and formatting
pass. Ten typed-label/generated-boolean regressions fail before the
repair and pass afterward. Coverage includes exact training-split
membership, null/standard-deviation conventions, shared t-digest bucket
accuracy, target-only fitting, reopen and no history collection.

Statistics use bounded Parquet batches and existing collectors.
Vocabulary/category state retains the collector's existing cardinality
behavior; this does not claim constant memory for unlimited distinct
values. Text fitting remains the encoder-fitting path, not a new
aggregate-text fitter.

Earlier combined-source loader validation on a transaction-history
graph: 192,000 distinct anchors / 1,500 batches in each of two epochs;
preparation 7.25s, iteration plus model-batch adaptation 35.18s then
31.75s. Native cache work changes from 192,000 computed / 0 reused to 0
computed / 192,000 reused. This is loader validation, not a new
GPU-training speedup claim.

## Change map

#328 (comment)

Review fixes: reuse the graph-materialization dtype mapping (including
decimal metadata), use #306's bucket statistics without an
exact-quantile rescan, and store one column-statistics payload
referenced by lightweight metadata.


CI loading-parity repair: fit once and compare Parquet/request loading
with the same frozen fitted state. Independently fitting the shared
t-digest and legacy row recipes can legitimately yield different bucket
boundaries. All tensor, label and held-out assertions remain;
independent shared-statistics accuracy/selection regressions remain.
After rebasing on #310/#332, 54 focused tests pass.


Latest review repairs: reuse target-free fitted inputs without a new fit
split or statistics scan; omit temporary task-values paths from saved
provenance; remove the redundant fitted-state equality from the loading
parity test and document/independently test both bucket-fitting recipes.
Local verification: 37 materialization/loading and 121
persistence/anchor-table tests pass; both new behavior regressions fail
on the previous source.

---------

Co-authored-by: Min Shen <[email protected]>
Victsm added a commit that referenced this pull request Nov 13, 2026
…ths (#329)

Move length-aware sequence batch planning into the native AnchorTable
iterator. It shuffles anchors into bounded pools, uses fitted field
costs and optional text-token metadata to form history/token-budget
batches, and caches each anchor's measured lengths for later epochs. The
loading loop keeps the existing combined graph/anchor reader and native
capped cross-component history merge.

Depends on #328 (its parent), #310 and #332; encoder fitting
#306/#307/#324 is merged. The history length query is prepared once when
the iterator is attached; planning does not invoke encoders or
reconstruct Python per-anchor requests. Fixed-width inputs need only a
constant field cost, not a per-row token file.

Validation: the combined rebased stack passed 2,220 package tests (3
skipped, 47 deselected). After the parent’s final fetched-timestamp
repair, 180 focused clock/materialization/loading/planning/counting
tests pass; the Rust tree is unchanged. Tests compare delivered tensors,
verify shuffle/coverage/caps/padding/token budgets, and prove epoch-two
cache reuse without planning-time encoding. Ruff passes.

Limits: length planning currently requires a supported EventSource and
Packed/Padded/Nested layout. Unsupported derived-field validity recipes
are rejected explicitly. Existing refusal of distributed variable-token
schedules is preserved. The task-owned sparse mapped cache uses 4–12
bytes per anchor and is not a persistent cross-task cache.
`length_input` remains the cost-metadata gate; tokenized length
bucketing can need token counts without `max_tokens`.

Earlier combined-source loader validation on a transaction-history
graph: 192,000 distinct anchors / 1,500 batches in each of two epochs;
preparation 7.25s, iteration plus model-batch adaptation 35.18s then
31.75s. Native cache work changes from 192,000 computed / 0 reused to 0
computed / 192,000 reused. This is loader validation, not a new
GPU-training speedup claim.

## Change map

#329 (comment)

Bucketing review fix: sort by the cached model-input length (tokens for
token layouts, events for row layouts). Four regressions compare
flat/nested batch ordering and delivered tensors with the existing
planner and verify cache reuse; all fail before the fix. #332 supplies
empty-value/required-field counts and policy-keyed files. Native
planning consumes its dropped-row marker and updated saturation limit,
and rejects stale count recipes. New regressions cover the reported
empty-text budget overflow and required-field drops, including
second-epoch cache reuse.



Latest review repair: row inputs without max_tokens sort by the history
count actually stored in the compact one-field cache. Two regressions
compare Packed/Padded ordering, delivered tensors and epoch-two reuse
while retaining four bytes per anchor. Other native length_input sources
remain explicitly refused; documentation and two EntitySource cases make
that decision visible. Local verification: 86 combined tests and all 26
documentation checks pass with a rebuilt native module.

---------

Co-authored-by: Min Shen <[email protected]>

This branch was previously deployed

1 inactive deployment
gha-kumo-workflow-tests — f6da770f Deployed Nov 13, 2026 by Vedaant-J via import #2260
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.

2 participants