diff --git a/docs/guides/native_ngram_memory.md b/docs/guides/native_ngram_memory.md index 795e184..05af07c 100644 --- a/docs/guides/native_ngram_memory.md +++ b/docs/guides/native_ngram_memory.md @@ -86,6 +86,14 @@ straight to `meft_rows_gather`. On uncompressed tables it halves lookup time compared with `rows` ([profile](../../evidence/host_query_profile_20261112/README.md)). +All-raw native tables now skip block sorting and copy directly after validating +original IDs and forwarding. On existing AG News/DBpedia seed-3 tables, paired +CPU gathers were 1.57–1.65× faster with unchanged bytes +([results](../../evidence/native_direct_gather_20261115/README.md)). Compressed +tables retain grouped reads. `NativeRows.last_xor_bytes` reports previous-row +XOR reconstruction separately from complete stream decompression; full-block +cache fills always reconstruct every row. + ## Native layout and construction `MEFTNAT1` is a little-endian binary file: a versioned header, an optional diff --git a/evidence/README.md b/evidence/README.md index 7381a63..d0fe363 100644 --- a/evidence/README.md +++ b/evidence/README.md @@ -52,6 +52,7 @@ here: links in locked READMEs still point to them, and they forward to | [1.85M-row CPU capacity](cpu_capacity_evidence_20261030/README.md) · [sparse blocks](sparse_blocks_evidence_20261030/README.md) | Smaller blocks cut native miss latency 16–27×; raw mmap remains faster | | [Large FP16/INT8 capacity](quantized_capacity_evidence_20261031/README.md) | FP16 native saves 52.29% vs raw FP32; INT8 native expands vs raw INT8 | | [Host query profile on AG News](host_query_profile_20261112/README.md) | Time is block decompression. On the twelve original tables, dedup without compression saves 85.0–85.8% (vs 85.7–86.6% with Zstd) and the GPU host path runs 1.09–1.23× raw with identical logits; on uniform-init tables raw is best. `ngram-store plan` predicts these layout sizes exactly and reports how the duplicates are distributed | +| [Direct native gathers](native_direct_gather_20261115/README.md) | All-raw tables bypass query sorting: 1.57–1.65× faster paired CPU gathers on existing AG News/DBpedia seed-3 tables, with unchanged original code bytes. Conditional XOR prefix reconstruction reduces work, but the eight saved Qwen controls show about 1.00× speed | | [Token-level n-grams do not transfer](token_ngram_duplicates_20261115/README.md) | WikiText-103 with the Qwen3 tokenizer, 124M tokens, 512-token windows: order 4 repeats 88.35%, but 85% of keys occur in one window and collapse there. Among keys seen in several windows deduplication saves 27.2%, and that falls to 10.5% at a count threshold of 3. Zero initialization only; no training involved | | [Native query/cache controls](native_query_evidence_20261030/README.md) · [decoded-block cache](native_cache_20261022.md) ([data](native_cache_evidence_20261022/)) | Cache sizing and hit/miss behaviour | | [XOR blocks](native_xor_compression_20261020.md) ([data](native_xor_evidence_20261020/)) · [streaming export](streaming_export_20261021.md) ([data](export_evidence_20261021/)) · [first native pilots](native_ngram_evidence_20261018/) | Codec and export-path development | diff --git a/evidence/native_direct_gather_20261115/README.md b/evidence/native_direct_gather_20261115/README.md new file mode 100644 index 0000000..64eaa11 --- /dev/null +++ b/evidence/native_direct_gather_20261115/README.md @@ -0,0 +1,93 @@ +# Direct native gathers on existing trained tables + +All-raw native tables now bypass block sorting and copy directly from their +contiguous physical payload after validating every requested original ID and +forwarding entry. Distinct-block counters use a reusable query-sized hash; +ordered queries avoid that hash. Allocation failure falls back to the grouped +reader. Original IDs, aliases, row bytes, file formats and existing C ABI remain +compatible. Cache budgets do not cause raw payload copies into a decoded cache. + +## Measured result + +Paired CPU **row gathers**, not complete classification or LLM inference: + +| Trained table | Original rows | Baseline p50 (µs) | Direct p50 (µs) | Paired geometric speed ratio | +| --- | ---: | ---: | ---: | ---: | +| AG News, uniform, seed 3 | 6,989,612 | 35.34 | 22.28 | 1.59× | +| AG News, zero, seed 3 | 6,989,612 | 32.90 | 21.02 | 1.57× | +| DBpedia, uniform, seed 3 | 34,050,161 | 45.68 | 27.17 | 1.65× | +| DBpedia, zero, seed 3 | 34,050,161 | 43.30 | 26.05 | 1.63× | + +Each arm reads the **same existing deduplicated, uncompressed artifact**; every +warmup and timed output is compared byte-for-byte with the original FP32 codes. +This reduces query overhead without changing stored capacity or model weights. +The previously measured [table savings and GPU host path](../host_query_profile_20261112/README.md) +remain separate measurements. Uniform-init byte dedup does not save capacity; +including that layout here tests the reader and does not recommend it over raw. + +- Source implementation: `4a89d3c55b77ce36830872271cdf726324ab2e49`. +- Data/models: existing registered AG News and DBpedia classifiers, zero and + uniform initialization, seed 3. 256 official test documents per dataset, + sampled without replacement with seed 20261112; OOV ID zero removed as in + `StagedClassifier`. The request IDs are never reordered or replicated. +- Measurement: 2 warmup passes, 10 timed passes, 3 paired rounds; baseline and + candidate alternate per request. Independent handles, preallocated inputs and + outputs, zero native cache, one pinned CPU core per model. Both use the same + optional-codec build. p50 columns are medians of the three round p50s. +- Environment: AMD EPYC 7713, Linux 5.4, Python 3.11.15, NumPy 2.2.6, + PyTorch 2.11.0, GCC 11.4.0. No GPU, retraining or paid API was used. + Energy and monetary costs are unmeasured. +- Scope: warm file-cache row lookup after addressing. Four jobs ran in parallel + on distinct cores; ratios are descriptive, not confidence intervals. This + does not measure quantizer decoding, reductions, transfer or full requests. + +## Conditional XOR optimization and negative control + +Previous-row XOR stream queries now reconstruct through the highest requested +physical row when a full decoded block will not enter the cache. Complete stream +decompression and validation still run; full-block cache fills reconstruct the +entire block. `NativeRows.last_xor_bytes` / `meft_rows_last_xor_bytes()` distinguish +this work from full decoded bytes. Chunked gathers and embedding bags aggregate +both counters. + +The first controlled run (`1e82e5e`) reused the saved 32 official MultiCounterFact +query traces of two trained Qwen memory tables (seed 3), at block sizes +16/64/256/1024. Across all eight cases, the speed ratio stayed **about 1.00×**. +Only two cases reconstructed any previous-row XOR at all; their XOR work fell +by 13% and 33%, but stream decompression dominated. This is a conditional work +reduction, not a demonstrated Qwen speedup. Plain/raw and independent row-packet +codecs are unaffected by this predictor change. + +## Checks and reproduction + +[Tests](tests/): local suite 379 tests passed (149 optional skips); local native +suite 43 passed (5 optional skips); remote native suite 43 passed without skips, +including PyTorch and optional LZ4/Zstd/libdeflate. ASan/UBSan passed locally and +remotely, including raw direct reads, malformed streams and cache growth. + +[summary.json](summary.json) indexes all twelve original timing records in +[raw/](raw/), compressed with gzip to keep the checkout small. Records include +commands, file and library SHA256s, source commit, environment, raw per-request +timings and logical-work counts. [build.json](build.json) records compiler, +headers, library hashes and baseline flags. Weights, tables, query arrays and +corpora are retained in the user's experiment workspace and are not added here. + +On the existing registered experiment workspace, compile both libraries using +`build.json`. The later baseline disables both optimizations with +`-DMEFT_DISABLE_RAW_GATHER -DMEFT_DISABLE_XOR_PREFIX`; the first Qwen control +disables only XOR prefixes. Run: + +```sh +PYTHONPATH=/llm-align/duyimin/ngram-sparse-xor-20261115/runtime \ + /llm-align/duyimin/ngram-counterfact-capacity-20261106/env/bin/python \ + evidence/native_direct_gather_20261115/scripts/run_raw.py \ + --work /llm-align/duyimin/ngram-sparse-xor-20261115 \ + --commit 4a89d3c55b77ce36830872271cdf726324ab2e49 +``` + +The general measurement entry point is +[`tools/benchmark_native_gather.py`](../../tools/benchmark_native_gather.py). +It rejects changed trace hashes, invalid IDs, table/code dimensions, byte +mismatches or changed decode work between the two arms. Rebuilding the trained +artifacts requires the original training protocol and data; these saved results +alone do not reproduce a new model-quality experiment. diff --git a/evidence/native_direct_gather_20261115/build.json b/evidence/native_direct_gather_20261115/build.json new file mode 100644 index 0000000..a3f3c8b --- /dev/null +++ b/evidence/native_direct_gather_20261115/build.json @@ -0,0 +1,67 @@ +{ + "source_commit": "4a89d3c55b77ce36830872271cdf726324ab2e49", + "compiler": "cc (Ubuntu 11.4.0-1ubuntu1~22.04.3) 11.4.0\nCopyright (C) 2021 Free Software Foundation, Inc.\nThis is free software; see the source for copying conditions. There is NO\nwarranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n", + "headers": { + "lz4.h": "https://raw.githubusercontent.com/lz4/lz4/v1.9.3/lib/lz4.h", + "zstd.h": "https://raw.githubusercontent.com/facebook/zstd/v1.4.8/lib/zstd.h", + "libdeflate.h": "https://raw.githubusercontent.com/ebiggers/libdeflate/v1.10/libdeflate.h" + }, + "files": { + "/llm-align/duyimin/ngram-sparse-xor-20261115/include/libdeflate.h": { + "sha256": "5ead6b5be40c415a11429e711480c6dbde1dee6508391f23b31f95bb1c5d87d8", + "bytes": 15154 + }, + "/llm-align/duyimin/ngram-sparse-xor-20261115/include/._libdeflate.h": { + "sha256": "08201127903639e30c8a3f1e75fcd92a11151e04683c2f884fd7098392413817", + "bytes": 163 + }, + "/llm-align/duyimin/ngram-sparse-xor-20261115/include/zstd.h": { + "sha256": "e5dd7935c6c7655dcafd868c265ecb97008a338c51286562ef093f43969c7b46", + "bytes": 138334 + }, + "/llm-align/duyimin/ngram-sparse-xor-20261115/include/lz4.h": { + "sha256": "c9b52a14c2c93fe5c435a09054cc8f1bf5d94a3ce1a38dc51296a92ce409f8e4", + "bytes": 40861 + }, + "/llm-align/duyimin/ngram-sparse-xor-20261115/include/._zstd.h": { + "sha256": "08201127903639e30c8a3f1e75fcd92a11151e04683c2f884fd7098392413817", + "bytes": 163 + }, + "/llm-align/duyimin/ngram-sparse-xor-20261115/include/._lz4.h": { + "sha256": "08201127903639e30c8a3f1e75fcd92a11151e04683c2f884fd7098392413817", + "bytes": 163 + }, + "/llm-align/duyimin/ngram-sparse-xor-20261115/lib/candidate-codecs.so": { + "sha256": "0fa6bc8604c6c20031a252ebf1a2d9c9cea148a6cdd38f9c860ad603a9504ec0", + "bytes": 34472 + }, + "/llm-align/duyimin/ngram-sparse-xor-20261115/lib/baseline-codecs.so": { + "sha256": "edb6e93484e90994c76288e31295d0ac59cfa791ff23e084218382f84367f036", + "bytes": 34472 + }, + "/llm-align/duyimin/ngram-sparse-xor-20261115/lib/candidate.so": { + "sha256": "4e41e56e80ab3244a1d6b3d4999a1f522ff9406952a938f478e5b0f0f323804b", + "bytes": 34048 + }, + "/llm-align/duyimin/ngram-sparse-xor-20261115/lib/baseline.so": { + "sha256": "ede1b2d6657cbaed7949f8d44b0956702c1fd956262b9fb1e1eb30f2335dcd76", + "bytes": 34048 + }, + "/llm-align/duyimin/ngram-sparse-xor-20261115/runtime/native/meft_rows.c": { + "sha256": "6a2908eb2e998fa0b2579739f80051b953c2093edc2eb70451bbd3c27cfc763c", + "bytes": 44978 + }, + "/llm-align/duyimin/ngram-sparse-xor-20261115/runtime/native/meft_rows.h": { + "sha256": "48198f4bc84777d35091e1ee86886324d7bffa011c5ef71a870c501100da2da5", + "bytes": 8675 + }, + "/llm-align/duyimin/ngram-sparse-xor-20261115/runtime/tools/benchmark_native_gather.py": { + "sha256": "c2d756f46d5a39c2e0512d869e6a8485e86e5a10fda0dbf11755b0016d2111f0", + "bytes": 8045 + } + }, + "codecs_flags": "-I/llm-align/duyimin/ngram-sparse-xor-20261115/include -DMEFT_USE_LZ4 -DMEFT_USE_ZSTD -DMEFT_USE_LIBDEFLATE -l:liblz4.so.1 -l:libzstd.so.1 -l:libdeflate.so.0", + "compile": "cc -std=c11 -O3 -fPIC -shared native/meft_rows.c -lz FLAGS -o LIBRARY", + "baseline_extra_flags": "-DMEFT_DISABLE_XOR_PREFIX -DMEFT_DISABLE_RAW_GATHER", + "first_xor_run": "1e82e5e, cc -std=c11 -O3 -fPIC -shared native/meft_rows.c -lz, baseline extra -DMEFT_DISABLE_XOR_PREFIX; baseline.so and candidate.so refer to this first run." +} \ No newline at end of file diff --git a/evidence/native_direct_gather_20261115/raw/ag_news-exact-uniform-s3-lr10-raw.json.gz b/evidence/native_direct_gather_20261115/raw/ag_news-exact-uniform-s3-lr10-raw.json.gz new file mode 100644 index 0000000..ed0407d Binary files /dev/null and b/evidence/native_direct_gather_20261115/raw/ag_news-exact-uniform-s3-lr10-raw.json.gz differ diff --git a/evidence/native_direct_gather_20261115/raw/ag_news-exact-zero-s3-lr10-raw.json.gz b/evidence/native_direct_gather_20261115/raw/ag_news-exact-zero-s3-lr10-raw.json.gz new file mode 100644 index 0000000..b10cb20 Binary files /dev/null and b/evidence/native_direct_gather_20261115/raw/ag_news-exact-zero-s3-lr10-raw.json.gz differ diff --git a/evidence/native_direct_gather_20261115/raw/dbpedia_14-exact-uniform-s3-lr3-raw.json.gz b/evidence/native_direct_gather_20261115/raw/dbpedia_14-exact-uniform-s3-lr3-raw.json.gz new file mode 100644 index 0000000..1b73f84 Binary files /dev/null and b/evidence/native_direct_gather_20261115/raw/dbpedia_14-exact-uniform-s3-lr3-raw.json.gz differ diff --git a/evidence/native_direct_gather_20261115/raw/dbpedia_14-exact-zero-s3-lr10-raw.json.gz b/evidence/native_direct_gather_20261115/raw/dbpedia_14-exact-zero-s3-lr10-raw.json.gz new file mode 100644 index 0000000..f22a761 Binary files /dev/null and b/evidence/native_direct_gather_20261115/raw/dbpedia_14-exact-zero-s3-lr10-raw.json.gz differ diff --git a/evidence/native_direct_gather_20261115/raw/qwen06-exact-s3-rows1024-zero.json.gz b/evidence/native_direct_gather_20261115/raw/qwen06-exact-s3-rows1024-zero.json.gz new file mode 100644 index 0000000..5d3bc3d Binary files /dev/null and b/evidence/native_direct_gather_20261115/raw/qwen06-exact-s3-rows1024-zero.json.gz differ diff --git a/evidence/native_direct_gather_20261115/raw/qwen06-exact-s3-rows16-zero.json.gz b/evidence/native_direct_gather_20261115/raw/qwen06-exact-s3-rows16-zero.json.gz new file mode 100644 index 0000000..d399c9a Binary files /dev/null and b/evidence/native_direct_gather_20261115/raw/qwen06-exact-s3-rows16-zero.json.gz differ diff --git a/evidence/native_direct_gather_20261115/raw/qwen06-exact-s3-rows256-zero.json.gz b/evidence/native_direct_gather_20261115/raw/qwen06-exact-s3-rows256-zero.json.gz new file mode 100644 index 0000000..8a990de Binary files /dev/null and b/evidence/native_direct_gather_20261115/raw/qwen06-exact-s3-rows256-zero.json.gz differ diff --git a/evidence/native_direct_gather_20261115/raw/qwen06-exact-s3-rows64-zero.json.gz b/evidence/native_direct_gather_20261115/raw/qwen06-exact-s3-rows64-zero.json.gz new file mode 100644 index 0000000..c6d0857 Binary files /dev/null and b/evidence/native_direct_gather_20261115/raw/qwen06-exact-s3-rows64-zero.json.gz differ diff --git a/evidence/native_direct_gather_20261115/raw/qwen35-exact-s3-rows1024-zero.json.gz b/evidence/native_direct_gather_20261115/raw/qwen35-exact-s3-rows1024-zero.json.gz new file mode 100644 index 0000000..b3ca708 Binary files /dev/null and b/evidence/native_direct_gather_20261115/raw/qwen35-exact-s3-rows1024-zero.json.gz differ diff --git a/evidence/native_direct_gather_20261115/raw/qwen35-exact-s3-rows16-zero.json.gz b/evidence/native_direct_gather_20261115/raw/qwen35-exact-s3-rows16-zero.json.gz new file mode 100644 index 0000000..cc263ec Binary files /dev/null and b/evidence/native_direct_gather_20261115/raw/qwen35-exact-s3-rows16-zero.json.gz differ diff --git a/evidence/native_direct_gather_20261115/raw/qwen35-exact-s3-rows256-zero.json.gz b/evidence/native_direct_gather_20261115/raw/qwen35-exact-s3-rows256-zero.json.gz new file mode 100644 index 0000000..0c13cc3 Binary files /dev/null and b/evidence/native_direct_gather_20261115/raw/qwen35-exact-s3-rows256-zero.json.gz differ diff --git a/evidence/native_direct_gather_20261115/raw/qwen35-exact-s3-rows64-zero.json.gz b/evidence/native_direct_gather_20261115/raw/qwen35-exact-s3-rows64-zero.json.gz new file mode 100644 index 0000000..751b896 Binary files /dev/null and b/evidence/native_direct_gather_20261115/raw/qwen35-exact-s3-rows64-zero.json.gz differ diff --git a/evidence/native_direct_gather_20261115/run-raw-status.json b/evidence/native_direct_gather_20261115/run-raw-status.json new file mode 100644 index 0000000..3260d30 --- /dev/null +++ b/evidence/native_direct_gather_20261115/run-raw-status.json @@ -0,0 +1,110 @@ +[ + { + "model": "ag_news-exact-zero-s3-lr10", + "returncode": 0, + "command": [ + "/llm-align/duyimin/ngram-counterfact-capacity-20261106/env/bin/python", + "-m", + "tools.benchmark_native_gather", + "--table", + "/llm-align/duyimin/ngram-host-profile-20261112/bundles/ag_news-exact-zero-s3-lr10/dedup-raw/rows.meft", + "--codes", + "/llm-align/duyimin/ngram-controlled-deployment-20261111/training-registered/ag_news-exact-zero-s3-lr10/rows.npy", + "--traces", + "/llm-align/duyimin/ngram-sparse-xor-20261115/traces/ag_news.npz", + "--baseline-library", + "/llm-align/duyimin/ngram-sparse-xor-20261115/lib/baseline-codecs.so", + "--library", + "/llm-align/duyimin/ngram-sparse-xor-20261115/lib/candidate-codecs.so", + "--output", + "/llm-align/duyimin/ngram-sparse-xor-20261115/results/ag_news-exact-zero-s3-lr10-raw.json", + "--commit", + "4a89d3c55b77ce36830872271cdf726324ab2e49", + "--core", + "40", + "--cache-bytes", + "0" + ] + }, + { + "model": "ag_news-exact-uniform-s3-lr10", + "returncode": 0, + "command": [ + "/llm-align/duyimin/ngram-counterfact-capacity-20261106/env/bin/python", + "-m", + "tools.benchmark_native_gather", + "--table", + "/llm-align/duyimin/ngram-host-profile-20261112/bundles/ag_news-exact-uniform-s3-lr10/dedup-raw/rows.meft", + "--codes", + "/llm-align/duyimin/ngram-controlled-deployment-20261111/training-registered/ag_news-exact-uniform-s3-lr10/rows.npy", + "--traces", + "/llm-align/duyimin/ngram-sparse-xor-20261115/traces/ag_news.npz", + "--baseline-library", + "/llm-align/duyimin/ngram-sparse-xor-20261115/lib/baseline-codecs.so", + "--library", + "/llm-align/duyimin/ngram-sparse-xor-20261115/lib/candidate-codecs.so", + "--output", + "/llm-align/duyimin/ngram-sparse-xor-20261115/results/ag_news-exact-uniform-s3-lr10-raw.json", + "--commit", + "4a89d3c55b77ce36830872271cdf726324ab2e49", + "--core", + "42", + "--cache-bytes", + "0" + ] + }, + { + "model": "dbpedia_14-exact-zero-s3-lr10", + "returncode": 0, + "command": [ + "/llm-align/duyimin/ngram-counterfact-capacity-20261106/env/bin/python", + "-m", + "tools.benchmark_native_gather", + "--table", + "/llm-align/duyimin/ngram-host-profile-20261112/bundles/dbpedia_14-exact-zero-s3-lr10/dedup-raw/rows.meft", + "--codes", + "/llm-align/duyimin/ngram-controlled-deployment-20261111/training-registered/dbpedia_14-exact-zero-s3-lr10/rows.npy", + "--traces", + "/llm-align/duyimin/ngram-sparse-xor-20261115/traces/dbpedia_14.npz", + "--baseline-library", + "/llm-align/duyimin/ngram-sparse-xor-20261115/lib/baseline-codecs.so", + "--library", + "/llm-align/duyimin/ngram-sparse-xor-20261115/lib/candidate-codecs.so", + "--output", + "/llm-align/duyimin/ngram-sparse-xor-20261115/results/dbpedia_14-exact-zero-s3-lr10-raw.json", + "--commit", + "4a89d3c55b77ce36830872271cdf726324ab2e49", + "--core", + "44", + "--cache-bytes", + "0" + ] + }, + { + "model": "dbpedia_14-exact-uniform-s3-lr3", + "returncode": 0, + "command": [ + "/llm-align/duyimin/ngram-counterfact-capacity-20261106/env/bin/python", + "-m", + "tools.benchmark_native_gather", + "--table", + "/llm-align/duyimin/ngram-host-profile-20261112/bundles/dbpedia_14-exact-uniform-s3-lr3/dedup-raw/rows.meft", + "--codes", + "/llm-align/duyimin/ngram-controlled-deployment-20261111/training-registered/dbpedia_14-exact-uniform-s3-lr3/rows.npy", + "--traces", + "/llm-align/duyimin/ngram-sparse-xor-20261115/traces/dbpedia_14.npz", + "--baseline-library", + "/llm-align/duyimin/ngram-sparse-xor-20261115/lib/baseline-codecs.so", + "--library", + "/llm-align/duyimin/ngram-sparse-xor-20261115/lib/candidate-codecs.so", + "--output", + "/llm-align/duyimin/ngram-sparse-xor-20261115/results/dbpedia_14-exact-uniform-s3-lr3-raw.json", + "--commit", + "4a89d3c55b77ce36830872271cdf726324ab2e49", + "--core", + "46", + "--cache-bytes", + "0" + ] + } +] \ No newline at end of file diff --git a/evidence/native_direct_gather_20261115/run-status.json b/evidence/native_direct_gather_20261115/run-status.json new file mode 100644 index 0000000..c9c6e4e --- /dev/null +++ b/evidence/native_direct_gather_20261115/run-status.json @@ -0,0 +1,218 @@ +[ + { + "label": "qwen06-exact-s3-rows16-zero", + "returncode": 0, + "command": [ + "/llm-align/duyimin/ngram-counterfact-capacity-20261106/env/bin/python", + "-m", + "tools.benchmark_xor_prefix", + "--table", + "/llm-align/duyimin/ngram-controlled-deployment-20261111/native-layouts/qwen06-exact-s3/bundles/fp32-rows16-xor/codes.meft", + "--codes", + "/llm-align/duyimin/ngram-complete-application-20261109/llm-frontier/qwen06-exact-s3/bundles/faiss-fp32/codes.npy", + "--traces", + "/llm-align/duyimin/ngram-controlled-deployment-20261111/application-frontier/native-cache/qwen06-exact-s3/traces.npz", + "--baseline-library", + "/llm-align/duyimin/ngram-sparse-xor-20261115/lib/baseline.so", + "--library", + "/llm-align/duyimin/ngram-sparse-xor-20261115/lib/candidate.so", + "--output", + "/llm-align/duyimin/ngram-sparse-xor-20261115/results/qwen06-exact-s3-rows16-zero.json", + "--commit", + "1e82e5ee1a8295d15d1d43259bfc16979ddd325f", + "--core", + "16", + "--cache-bytes", + "0" + ] + }, + { + "label": "qwen06-exact-s3-rows64-zero", + "returncode": 0, + "command": [ + "/llm-align/duyimin/ngram-counterfact-capacity-20261106/env/bin/python", + "-m", + "tools.benchmark_xor_prefix", + "--table", + "/llm-align/duyimin/ngram-controlled-deployment-20261111/native-layouts/qwen06-exact-s3/bundles/fp32-rows64-xor/codes.meft", + "--codes", + "/llm-align/duyimin/ngram-complete-application-20261109/llm-frontier/qwen06-exact-s3/bundles/faiss-fp32/codes.npy", + "--traces", + "/llm-align/duyimin/ngram-controlled-deployment-20261111/application-frontier/native-cache/qwen06-exact-s3/traces.npz", + "--baseline-library", + "/llm-align/duyimin/ngram-sparse-xor-20261115/lib/baseline.so", + "--library", + "/llm-align/duyimin/ngram-sparse-xor-20261115/lib/candidate.so", + "--output", + "/llm-align/duyimin/ngram-sparse-xor-20261115/results/qwen06-exact-s3-rows64-zero.json", + "--commit", + "1e82e5ee1a8295d15d1d43259bfc16979ddd325f", + "--core", + "18", + "--cache-bytes", + "0" + ] + }, + { + "label": "qwen06-exact-s3-rows256-zero", + "returncode": 0, + "command": [ + "/llm-align/duyimin/ngram-counterfact-capacity-20261106/env/bin/python", + "-m", + "tools.benchmark_xor_prefix", + "--table", + "/llm-align/duyimin/ngram-controlled-deployment-20261111/native-layouts/qwen06-exact-s3/bundles/fp32-rows256-xor/codes.meft", + "--codes", + "/llm-align/duyimin/ngram-complete-application-20261109/llm-frontier/qwen06-exact-s3/bundles/faiss-fp32/codes.npy", + "--traces", + "/llm-align/duyimin/ngram-controlled-deployment-20261111/application-frontier/native-cache/qwen06-exact-s3/traces.npz", + "--baseline-library", + "/llm-align/duyimin/ngram-sparse-xor-20261115/lib/baseline.so", + "--library", + "/llm-align/duyimin/ngram-sparse-xor-20261115/lib/candidate.so", + "--output", + "/llm-align/duyimin/ngram-sparse-xor-20261115/results/qwen06-exact-s3-rows256-zero.json", + "--commit", + "1e82e5ee1a8295d15d1d43259bfc16979ddd325f", + "--core", + "20", + "--cache-bytes", + "0" + ] + }, + { + "label": "qwen06-exact-s3-rows1024-zero", + "returncode": 0, + "command": [ + "/llm-align/duyimin/ngram-counterfact-capacity-20261106/env/bin/python", + "-m", + "tools.benchmark_xor_prefix", + "--table", + "/llm-align/duyimin/ngram-controlled-deployment-20261111/native-layouts/qwen06-exact-s3/bundles/fp32-rows1024-xor/codes.meft", + "--codes", + "/llm-align/duyimin/ngram-complete-application-20261109/llm-frontier/qwen06-exact-s3/bundles/faiss-fp32/codes.npy", + "--traces", + "/llm-align/duyimin/ngram-controlled-deployment-20261111/application-frontier/native-cache/qwen06-exact-s3/traces.npz", + "--baseline-library", + "/llm-align/duyimin/ngram-sparse-xor-20261115/lib/baseline.so", + "--library", + "/llm-align/duyimin/ngram-sparse-xor-20261115/lib/candidate.so", + "--output", + "/llm-align/duyimin/ngram-sparse-xor-20261115/results/qwen06-exact-s3-rows1024-zero.json", + "--commit", + "1e82e5ee1a8295d15d1d43259bfc16979ddd325f", + "--core", + "22", + "--cache-bytes", + "0" + ] + }, + { + "label": "qwen35-exact-s3-rows16-zero", + "returncode": 0, + "command": [ + "/llm-align/duyimin/ngram-counterfact-capacity-20261106/env/bin/python", + "-m", + "tools.benchmark_xor_prefix", + "--table", + "/llm-align/duyimin/ngram-controlled-deployment-20261111/native-layouts/qwen35-exact-s3/bundles/fp32-rows16-xor/codes.meft", + "--codes", + "/llm-align/duyimin/ngram-complete-application-20261109/llm-frontier/qwen35-exact-s3/bundles/faiss-fp32/codes.npy", + "--traces", + "/llm-align/duyimin/ngram-controlled-deployment-20261111/application-frontier/native-cache/qwen35-exact-s3/traces.npz", + "--baseline-library", + "/llm-align/duyimin/ngram-sparse-xor-20261115/lib/baseline.so", + "--library", + "/llm-align/duyimin/ngram-sparse-xor-20261115/lib/candidate.so", + "--output", + "/llm-align/duyimin/ngram-sparse-xor-20261115/results/qwen35-exact-s3-rows16-zero.json", + "--commit", + "1e82e5ee1a8295d15d1d43259bfc16979ddd325f", + "--core", + "24", + "--cache-bytes", + "0" + ] + }, + { + "label": "qwen35-exact-s3-rows64-zero", + "returncode": 0, + "command": [ + "/llm-align/duyimin/ngram-counterfact-capacity-20261106/env/bin/python", + "-m", + "tools.benchmark_xor_prefix", + "--table", + "/llm-align/duyimin/ngram-controlled-deployment-20261111/native-layouts/qwen35-exact-s3/bundles/fp32-rows64-xor/codes.meft", + "--codes", + "/llm-align/duyimin/ngram-complete-application-20261109/llm-frontier/qwen35-exact-s3/bundles/faiss-fp32/codes.npy", + "--traces", + "/llm-align/duyimin/ngram-controlled-deployment-20261111/application-frontier/native-cache/qwen35-exact-s3/traces.npz", + "--baseline-library", + "/llm-align/duyimin/ngram-sparse-xor-20261115/lib/baseline.so", + "--library", + "/llm-align/duyimin/ngram-sparse-xor-20261115/lib/candidate.so", + "--output", + "/llm-align/duyimin/ngram-sparse-xor-20261115/results/qwen35-exact-s3-rows64-zero.json", + "--commit", + "1e82e5ee1a8295d15d1d43259bfc16979ddd325f", + "--core", + "26", + "--cache-bytes", + "0" + ] + }, + { + "label": "qwen35-exact-s3-rows256-zero", + "returncode": 0, + "command": [ + "/llm-align/duyimin/ngram-counterfact-capacity-20261106/env/bin/python", + "-m", + "tools.benchmark_xor_prefix", + "--table", + "/llm-align/duyimin/ngram-controlled-deployment-20261111/native-layouts/qwen35-exact-s3/bundles/fp32-rows256-xor/codes.meft", + "--codes", + "/llm-align/duyimin/ngram-complete-application-20261109/llm-frontier/qwen35-exact-s3/bundles/faiss-fp32/codes.npy", + "--traces", + "/llm-align/duyimin/ngram-controlled-deployment-20261111/application-frontier/native-cache/qwen35-exact-s3/traces.npz", + "--baseline-library", + "/llm-align/duyimin/ngram-sparse-xor-20261115/lib/baseline.so", + "--library", + "/llm-align/duyimin/ngram-sparse-xor-20261115/lib/candidate.so", + "--output", + "/llm-align/duyimin/ngram-sparse-xor-20261115/results/qwen35-exact-s3-rows256-zero.json", + "--commit", + "1e82e5ee1a8295d15d1d43259bfc16979ddd325f", + "--core", + "28", + "--cache-bytes", + "0" + ] + }, + { + "label": "qwen35-exact-s3-rows1024-zero", + "returncode": 0, + "command": [ + "/llm-align/duyimin/ngram-counterfact-capacity-20261106/env/bin/python", + "-m", + "tools.benchmark_xor_prefix", + "--table", + "/llm-align/duyimin/ngram-controlled-deployment-20261111/native-layouts/qwen35-exact-s3/bundles/fp32-rows1024-xor/codes.meft", + "--codes", + "/llm-align/duyimin/ngram-complete-application-20261109/llm-frontier/qwen35-exact-s3/bundles/faiss-fp32/codes.npy", + "--traces", + "/llm-align/duyimin/ngram-controlled-deployment-20261111/application-frontier/native-cache/qwen35-exact-s3/traces.npz", + "--baseline-library", + "/llm-align/duyimin/ngram-sparse-xor-20261115/lib/baseline.so", + "--library", + "/llm-align/duyimin/ngram-sparse-xor-20261115/lib/candidate.so", + "--output", + "/llm-align/duyimin/ngram-sparse-xor-20261115/results/qwen35-exact-s3-rows1024-zero.json", + "--commit", + "1e82e5ee1a8295d15d1d43259bfc16979ddd325f", + "--core", + "30", + "--cache-bytes", + "0" + ] + } +] \ No newline at end of file diff --git a/evidence/native_direct_gather_20261115/scripts/run_raw.py b/evidence/native_direct_gather_20261115/scripts/run_raw.py new file mode 100644 index 0000000..d54e23a --- /dev/null +++ b/evidence/native_direct_gather_20261115/scripts/run_raw.py @@ -0,0 +1,41 @@ +"""Reuse the registered classifier tables and official test IDs; CPU only.""" +import argparse, concurrent.futures, hashlib, json, os, subprocess, sys +from pathlib import Path +import numpy as np +parser=argparse.ArgumentParser() +parser.add_argument('--work', type=Path, required=True) +parser.add_argument('--commit', required=True) +args=parser.parse_args(); work=args.work +root=Path('/llm-align/duyimin/ngram-controlled-deployment-20261111') +bundles=Path('/llm-align/duyimin/ngram-host-profile-20261112/bundles') +(work/'traces').mkdir(exist_ok=True) +env=dict(os.environ, PYTHONPATH=str(work/'runtime'), OPENBLAS_NUM_THREADS='1', OMP_NUM_THREADS='1') +traces={} +for dataset in ('ag_news','dbpedia_14'): + data=root/'data'/dataset + ids=np.load(data/'test-ids.npy',mmap_mode='r'); offsets=np.load(data/'test-offsets.npy',mmap_mode='r') + pick=np.sort(np.random.default_rng(20261112).choice(len(offsets)-1,size=256,replace=False)) + queries={}; records=[] + for i,doc in enumerate(pick): + q=np.ascontiguousarray(ids[offsets[doc]:offsets[doc+1]],dtype=np.uint64); q=q[q!=0] + queries['ids'+str(i)]=q + records.append({'document_index':int(doc),'ids_sha256':hashlib.sha256(q.tobytes()).hexdigest()}) + path=work/'traces'/f'{dataset}.npz';np.savez(path,**queries) + metadata={'domain':f'Official {dataset} test documents, original registered row IDs; OOV zero removed as in StagedClassifier. 256 seeded documents (20261112).','trace_sha256':hashlib.sha256(path.read_bytes()).hexdigest(),'requests':records,'dataset_source':str(data)} + path.with_suffix('.json').write_text(json.dumps(metadata,indent=2));traces[dataset]=path +jobs=[] +for dataset in ('ag_news','dbpedia_14'): + for init in ('zero','uniform'): + lr=10 if dataset=='ag_news' or init=='zero' else 3 + model=f'{dataset}-exact-{init}-s3-lr{lr}' + table=bundles/model/'dedup-raw/rows.meft' + cmd=[sys.executable,'-m','tools.benchmark_native_gather','--table',str(table),'--codes',str(root/'training-registered'/model/'rows.npy'),'--traces',str(traces[dataset]),'--baseline-library',str(work/'lib/baseline-codecs.so'),'--library',str(work/'lib/candidate-codecs.so'),'--output',str(work/'results'/f'{model}-raw.json'),'--commit',args.commit,'--core',str(40+len(jobs)*2),'--cache-bytes','0'] + jobs.append((model,cmd)) +def run(job): + model,cmd=job + with (work/'results'/f'{model}-raw.log').open('w') as out: + p=subprocess.run(cmd,env=env,stdout=out,stderr=subprocess.STDOUT,cwd=work/'runtime') + print(model,p.returncode,flush=True) + return {'model':model,'returncode':p.returncode,'command':cmd} +with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool: results=list(pool.map(run,jobs)) +(work/'results/run-raw-status.json').write_text(json.dumps(results,indent=2)) diff --git a/evidence/native_direct_gather_20261115/summary.json b/evidence/native_direct_gather_20261115/summary.json new file mode 100644 index 0000000..e08d153 --- /dev/null +++ b/evidence/native_direct_gather_20261115/summary.json @@ -0,0 +1,362 @@ +[ + { + "name": "ag_news-exact-uniform-s3-lr10-raw", + "commit": "4a89d3c55b77ce36830872271cdf726324ab2e49", + "raw": "raw/ag_news-exact-uniform-s3-lr10-raw.json.gz", + "raw_sha256": "65f0ae4ae84ec33b7064a693c18f9789c25bbdb7fc562bd06c6e7d538530fd05", + "rows": 6989612, + "row_bytes": 512, + "speed_ratio": 1.5877039933141825, + "p50_us": { + "baseline": 35.342, + "candidate": 22.282 + }, + "xor_bytes_per_round": { + "baseline": { + "blocks": 191580, + "decodes": 0, + "compressed_bytes": 0, + "decoded_bytes": 0, + "xor_bytes": 0 + }, + "candidate": { + "blocks": 191580, + "decodes": 0, + "compressed_bytes": 0, + "decoded_bytes": 0, + "xor_bytes": 0 + } + }, + "original_code_bytes_match": true + }, + { + "name": "ag_news-exact-zero-s3-lr10-raw", + "commit": "4a89d3c55b77ce36830872271cdf726324ab2e49", + "raw": "raw/ag_news-exact-zero-s3-lr10-raw.json.gz", + "raw_sha256": "e0e18a9639c6ad83cbc224cb83886aca8e553daa95fcc703a63cd9595ca2144a", + "rows": 6989612, + "row_bytes": 512, + "speed_ratio": 1.568304045708378, + "p50_us": { + "baseline": 32.898, + "candidate": 21.024 + }, + "xor_bytes_per_round": { + "baseline": { + "blocks": 162560, + "decodes": 0, + "compressed_bytes": 0, + "decoded_bytes": 0, + "xor_bytes": 0 + }, + "candidate": { + "blocks": 162560, + "decodes": 0, + "compressed_bytes": 0, + "decoded_bytes": 0, + "xor_bytes": 0 + } + }, + "original_code_bytes_match": true + }, + { + "name": "dbpedia_14-exact-uniform-s3-lr3-raw", + "commit": "4a89d3c55b77ce36830872271cdf726324ab2e49", + "raw": "raw/dbpedia_14-exact-uniform-s3-lr3-raw.json.gz", + "raw_sha256": "143e4734ae58f2e559b6557927792e6bf605ad1ddf2404d1943b16d70c6f0ae9", + "rows": 34050161, + "row_bytes": 512, + "speed_ratio": 1.64902184211652, + "p50_us": { + "baseline": 45.68, + "candidate": 27.171 + }, + "xor_bytes_per_round": { + "baseline": { + "blocks": 250440, + "decodes": 0, + "compressed_bytes": 0, + "decoded_bytes": 0, + "xor_bytes": 0 + }, + "candidate": { + "blocks": 250440, + "decodes": 0, + "compressed_bytes": 0, + "decoded_bytes": 0, + "xor_bytes": 0 + } + }, + "original_code_bytes_match": true + }, + { + "name": "dbpedia_14-exact-zero-s3-lr10-raw", + "commit": "4a89d3c55b77ce36830872271cdf726324ab2e49", + "raw": "raw/dbpedia_14-exact-zero-s3-lr10-raw.json.gz", + "raw_sha256": "abac1465eb5ce2adb87e1225d89fc9ebb4fbec06a1d0ee9f05c5278cda4a846d", + "rows": 34050161, + "row_bytes": 512, + "speed_ratio": 1.63274935459376, + "p50_us": { + "baseline": 43.305, + "candidate": 26.0535 + }, + "xor_bytes_per_round": { + "baseline": { + "blocks": 219960, + "decodes": 0, + "compressed_bytes": 0, + "decoded_bytes": 0, + "xor_bytes": 0 + }, + "candidate": { + "blocks": 219960, + "decodes": 0, + "compressed_bytes": 0, + "decoded_bytes": 0, + "xor_bytes": 0 + } + }, + "original_code_bytes_match": true + }, + { + "name": "qwen06-exact-s3-rows1024-zero", + "commit": "1e82e5ee1a8295d15d1d43259bfc16979ddd325f", + "raw": "raw/qwen06-exact-s3-rows1024-zero.json.gz", + "raw_sha256": "a886dde5933cebfbbf5401d89638b86886fda74d637a5d5f9c993c42da657f1e", + "rows": 580910, + "row_bytes": 128, + "speed_ratio": 0.9999579320257473, + "p50_us": { + "baseline": 26714.0615, + "candidate": 26706.553 + }, + "xor_bytes_per_round": { + "baseline": { + "blocks": 9510, + "decodes": 9510, + "compressed_bytes": 1156154610, + "decoded_bytes": 1244646400, + "xor_bytes": 0 + }, + "candidate": { + "blocks": 9510, + "decodes": 9510, + "compressed_bytes": 1156154610, + "decoded_bytes": 1244646400, + "xor_bytes": 0 + } + }, + "original_code_bytes_match": true + }, + { + "name": "qwen06-exact-s3-rows16-zero", + "commit": "1e82e5ee1a8295d15d1d43259bfc16979ddd325f", + "raw": "raw/qwen06-exact-s3-rows16-zero.json.gz", + "raw_sha256": "c2acc8b70c2fc231901834c005e55fa5af339bf030a4b4cdf059990092513f87", + "rows": 580910, + "row_bytes": 128, + "speed_ratio": 0.9995153623552974, + "p50_us": { + "baseline": 708.672, + "candidate": 708.637 + }, + "xor_bytes_per_round": { + "baseline": { + "blocks": 10080, + "decodes": 10080, + "compressed_bytes": 19515180, + "decoded_bytes": 20643840, + "xor_bytes": 0 + }, + "candidate": { + "blocks": 10080, + "decodes": 10080, + "compressed_bytes": 19515180, + "decoded_bytes": 20643840, + "xor_bytes": 0 + } + }, + "original_code_bytes_match": true + }, + { + "name": "qwen06-exact-s3-rows256-zero", + "commit": "1e82e5ee1a8295d15d1d43259bfc16979ddd325f", + "raw": "raw/qwen06-exact-s3-rows256-zero.json.gz", + "raw_sha256": "72cc2d85ef9022f089d7e3acf69de0e472f55d99e0220db7da35be4c3830f1ba", + "rows": 580910, + "row_bytes": 128, + "speed_ratio": 0.9995861522256088, + "p50_us": { + "baseline": 7242.9695, + "candidate": 7251.002 + }, + "xor_bytes_per_round": { + "baseline": { + "blocks": 10010, + "decodes": 10010, + "compressed_bytes": 304682580, + "decoded_bytes": 328007680, + "xor_bytes": 0 + }, + "candidate": { + "blocks": 10010, + "decodes": 10010, + "compressed_bytes": 304682580, + "decoded_bytes": 328007680, + "xor_bytes": 0 + } + }, + "original_code_bytes_match": true + }, + { + "name": "qwen06-exact-s3-rows64-zero", + "commit": "1e82e5ee1a8295d15d1d43259bfc16979ddd325f", + "raw": "raw/qwen06-exact-s3-rows64-zero.json.gz", + "raw_sha256": "762ef6a3b278dd78cfd98fc88060750ca8c74d2eceb9838d90ccd5eef0d1aacd", + "rows": 580910, + "row_bytes": 128, + "speed_ratio": 0.9995368865137088, + "p50_us": { + "baseline": 1955.624, + "candidate": 1960.2685000000001 + }, + "xor_bytes_per_round": { + "baseline": { + "blocks": 10080, + "decodes": 10080, + "compressed_bytes": 76827870, + "decoded_bytes": 82575360, + "xor_bytes": 161280 + }, + "candidate": { + "blocks": 10080, + "decodes": 10080, + "compressed_bytes": 76827870, + "decoded_bytes": 82575360, + "xor_bytes": 140800 + } + }, + "original_code_bytes_match": true + }, + { + "name": "qwen35-exact-s3-rows1024-zero", + "commit": "1e82e5ee1a8295d15d1d43259bfc16979ddd325f", + "raw": "raw/qwen35-exact-s3-rows1024-zero.json.gz", + "raw_sha256": "716524518fc7b65883672b4b6b30d6bc93da3741fe239dd1d74af10ce8eeda58", + "rows": 574330, + "row_bytes": 128, + "speed_ratio": 0.9999566243592297, + "p50_us": { + "baseline": 26461.214, + "candidate": 26484.8925 + }, + "xor_bytes_per_round": { + "baseline": { + "blocks": 9500, + "decodes": 9500, + "compressed_bytes": 1155632070, + "decoded_bytes": 1243983360, + "xor_bytes": 0 + }, + "candidate": { + "blocks": 9500, + "decodes": 9500, + "compressed_bytes": 1155632070, + "decoded_bytes": 1243983360, + "xor_bytes": 0 + } + }, + "original_code_bytes_match": true + }, + { + "name": "qwen35-exact-s3-rows16-zero", + "commit": "1e82e5ee1a8295d15d1d43259bfc16979ddd325f", + "raw": "raw/qwen35-exact-s3-rows16-zero.json.gz", + "raw_sha256": "d191e86f4b138fad017043a8369d3e7190e7fc6f1e8fb58ebf7ea3268effd26b", + "rows": 574330, + "row_bytes": 128, + "speed_ratio": 1.0023224456905866, + "p50_us": { + "baseline": 709.1265000000001, + "candidate": 709.545 + }, + "xor_bytes_per_round": { + "baseline": { + "blocks": 10010, + "decodes": 10010, + "compressed_bytes": 19378700, + "decoded_bytes": 20500480, + "xor_bytes": 38400 + }, + "candidate": { + "blocks": 10010, + "decodes": 10010, + "compressed_bytes": 19378700, + "decoded_bytes": 20500480, + "xor_bytes": 25600 + } + }, + "original_code_bytes_match": true + }, + { + "name": "qwen35-exact-s3-rows256-zero", + "commit": "1e82e5ee1a8295d15d1d43259bfc16979ddd325f", + "raw": "raw/qwen35-exact-s3-rows256-zero.json.gz", + "raw_sha256": "c80d13fc87a3a92309dafafce8b15a2693b471f7102f5263f6028ea8ecb92178", + "rows": 574330, + "row_bytes": 128, + "speed_ratio": 1.0003355354892143, + "p50_us": { + "baseline": 7203.017, + "candidate": 7196.4515 + }, + "xor_bytes_per_round": { + "baseline": { + "blocks": 9970, + "decodes": 9970, + "compressed_bytes": 303458740, + "decoded_bytes": 326696960, + "xor_bytes": 0 + }, + "candidate": { + "blocks": 9970, + "decodes": 9970, + "compressed_bytes": 303458740, + "decoded_bytes": 326696960, + "xor_bytes": 0 + } + }, + "original_code_bytes_match": true + }, + { + "name": "qwen35-exact-s3-rows64-zero", + "commit": "1e82e5ee1a8295d15d1d43259bfc16979ddd325f", + "raw": "raw/qwen35-exact-s3-rows64-zero.json.gz", + "raw_sha256": "cfa52096946add5226a3c3e850561f5742a377a9900550b44cf9484b62c865cb", + "rows": 574330, + "row_bytes": 128, + "speed_ratio": 0.9995899154138466, + "p50_us": { + "baseline": 1947.556, + "candidate": 1949.3375 + }, + "xor_bytes_per_round": { + "baseline": { + "blocks": 10000, + "decodes": 10000, + "compressed_bytes": 76235460, + "decoded_bytes": 81920000, + "xor_bytes": 0 + }, + "candidate": { + "blocks": 10000, + "decodes": 10000, + "compressed_bytes": 76235460, + "decoded_bytes": 81920000, + "xor_bytes": 0 + } + }, + "original_code_bytes_match": true + } +] diff --git a/evidence/native_direct_gather_20261115/tests/local-native-tests.log b/evidence/native_direct_gather_20261115/tests/local-native-tests.log new file mode 100644 index 0000000..2479a4d --- /dev/null +++ b/evidence/native_direct_gather_20261115/tests/local-native-tests.log @@ -0,0 +1,48 @@ +test_atomic_replacement_keeps_old_mmap_readers_on_original_bytes (tests.test_native_rows.NativeRowsTest) ... ok +test_bag_calls_aggregate_codec_bytes_and_reset_on_rejected_input (tests.test_native_rows.NativeRowsTest) ... ok +test_byte_cap_keeps_original_ids_with_compaction_permutation_and_tail (tests.test_native_rows.NativeRowsTest) ... ok +test_cache_consumes_later_hits_before_earlier_misses_evict_them (tests.test_native_rows.NativeRowsTest) ... ok +test_cache_hash_growth_eviction_and_budget_reset_match_lru_model (tests.test_native_rows.NativeRowsTest) ... ok +test_cache_preserves_older_library_loading_when_disabled (tests.test_native_rows.NativeRowsTest) ... ok +test_cache_raw_bypass_and_failed_decode_are_not_cached (tests.test_native_rows.NativeRowsTest) ... ok +test_cache_reuses_exact_blocks_and_respects_lru_byte_budget (tests.test_native_rows.NativeRowsTest) ... ok +test_cache_uses_budget_beyond_64_entries_and_invalid_query_is_atomic (tests.test_native_rows.NativeRowsTest) ... ok +test_chunked_query_preserves_bytes_order_and_aggregates_all_counters (tests.test_native_rows.NativeRowsTest) ... ok +test_chunked_query_rejects_limits_capacities_and_late_invalid_ids (tests.test_native_rows.NativeRowsTest) ... ok +test_codec_bytes_count_whole_blocks_chunk_redecodes_cache_hits_and_raw (tests.test_native_rows.NativeRowsTest) ... ok +test_direct_script_import_remains_compatible_with_legacy_demo_entrypoints (tests.test_native_rows.NativeRowsTest) ... ok +test_embedding_export_exposes_legacy_identity_format_option (tests.test_native_rows.NativeRowsTest) ... skipped 'optional PyTorch unavailable' +test_export_to_source_hardlink_does_not_modify_source (tests.test_native_rows.NativeRowsTest) ... ok +test_failed_flush_or_replace_preserves_target_and_cleans_temporary_file (tests.test_native_rows.NativeRowsTest) ... ok +test_failed_partial_write_never_publishes_a_partial_table (tests.test_native_rows.NativeRowsTest) ... ok +test_gather_array_matches_rows_and_rejects_bad_ids (tests.test_native_rows.NativeRowsTest) ... ok +test_implicit_header_rejects_inconsistent_counts_overflows_and_legacy_layout (tests.test_native_rows.NativeRowsTest) ... ok +test_implicit_identity_saves_exact_map_bytes_with_unchanged_codec_payloads (tests.test_native_rows.NativeRowsTest) ... ok +test_integer_grouping_matches_comparison_control_across_byte_boundaries (tests.test_native_rows.NativeRowsTest) ... ok +test_integer_xor_matches_reference_bytes_with_leading_and_trailing_zeros (tests.test_native_rows.NativeRowsTest) ... ok +test_native_coalesces_blocks_and_rejects_bad_file (tests.test_native_rows.NativeRowsTest) ... ok +test_native_preserves_arbitrary_bytes_ids_and_batches (tests.test_native_rows.NativeRowsTest) ... ok +test_native_torch_adapter_direct_output (tests.test_native_rows.NativeRowsTest) ... skipped 'optional PyTorch unavailable' +test_optional_fast_codecs_original_ids_odd_width_forwarding_cache_and_capabilities (tests.test_native_rows.NativeRowsTest) ... ok +test_ordinary_embedding_and_max_norm_boundary (tests.test_native_rows.NativeRowsTest) ... skipped 'optional PyTorch unavailable' +test_raw_direct_gather_preserves_forwarding_counters_and_error_output (tests.test_native_rows.NativeRowsTest) ... ok +test_row_cache_chunk_counters_and_failed_queries_preserve_output (tests.test_native_rows.NativeRowsTest) ... ok +test_row_cache_failed_decode_never_publishes_rows (tests.test_native_rows.NativeRowsTest) ... ok +test_row_cache_retains_sparse_queries_and_forwarded_aliases (tests.test_native_rows.NativeRowsTest) ... ok +test_row_packet_headers_and_queried_payloads_reject_malformed_offsets_and_masks (tests.test_native_rows.NativeRowsTest) ... ok +test_row_packets_preserve_original_ids_aliases_and_bounded_cache (tests.test_native_rows.NativeRowsTest) ... ok +test_row_packets_sparse_decode_work_and_uint32_offsets (tests.test_native_rows.NativeRowsTest) ... ok +test_small_causal_transformer_logits_match_with_untied_embedding (tests.test_native_rows.NativeRowsTest) ... skipped 'optional PyTorch unavailable' +test_small_queries_and_disabled_chunking_keep_older_library_compatibility (tests.test_native_rows.NativeRowsTest) ... ok +test_sparse_xor_prefix_keeps_full_stream_checks_and_cache_contents (tests.test_native_rows.NativeRowsTest) ... ok +test_sparse_xor_prefix_uses_forwarded_rows_and_aggregates_chunk_work (tests.test_native_rows.NativeRowsTest) ... ok +test_sparse_xor_work_accumulates_across_bags_without_changing_reductions (tests.test_native_rows.NativeRowsTest) ... ok +test_xor_codec_adapts_and_preserves_reordered_original_ids (tests.test_native_rows.NativeRowsTest) ... ok +test_xor_decoder_handles_unaligned_rows_and_word_tails (tests.test_native_rows.NativeRowsTest) ... ok +test_xor_empty_partial_blocks_and_invalid_permutations (tests.test_native_rows.NativeRowsTest) ... ok +test_xor_torch_reconstructs_nonfinite_bit_patterns (tests.test_native_rows.NativeRowsTest) ... skipped 'optional PyTorch unavailable' + +---------------------------------------------------------------------- +Ran 43 tests in 4.254s + +OK (skipped=5) diff --git a/evidence/native_direct_gather_20261115/tests/local-sanitizers.log b/evidence/native_direct_gather_20261115/tests/local-sanitizers.log new file mode 100644 index 0000000..6e2aeaf --- /dev/null +++ b/evidence/native_direct_gather_20261115/tests/local-sanitizers.log @@ -0,0 +1 @@ +ASan/UBSan: versions 1/2/3/6/7, 384 mutated/truncated files, direct raw gathers and 300-block cache growth/eviction checked; optional LZ4/Zstd cases run when enabled. diff --git a/evidence/native_direct_gather_20261115/tests/local-unit-tests.log b/evidence/native_direct_gather_20261115/tests/local-unit-tests.log new file mode 100644 index 0000000..a71d201 --- /dev/null +++ b/evidence/native_direct_gather_20261115/tests/local-unit-tests.log @@ -0,0 +1,64 @@ +.............sssssssss...ssssss...s..s....ssssss............sss...ssssss....s..retime-long 20 24 +.....{'llm_cpu_complete': 1, 'total': 12} +{'llm_cpu_complete': 2, 'total': 12} +{'llm_cpu_complete': 3, 'total': 12} +{'llm_cpu_complete': 4, 'total': 12} +{'llm_cpu_complete': 5, 'total': 12} +{'llm_cpu_complete': 6, 'total': 12} +{'llm_cpu_complete': 7, 'total': 12} +{'llm_cpu_complete': 8, 'total': 12} +{'llm_cpu_complete': 9, 'total': 12} +{'llm_cpu_complete': 10, 'total': 12} +{'llm_cpu_complete': 11, 'total': 12} +{'llm_cpu_complete': 12, 'total': 12} +..ssssssssssssssssssss.............s........ss...........................sssssssss.......ss...s........ssss.sssss.....sssssssssss....{'phase': 'retime-llm-gpu', 'complete': 1, 'expected': 12, 'current_failures': 0, 'gpu': 0} +{'phase': 'retime-llm-gpu', 'complete': 2, 'expected': 12, 'current_failures': 0, 'gpu': 2} +{'phase': 'retime-llm-gpu', 'complete': 3, 'expected': 12, 'current_failures': 0, 'gpu': 1} +{'phase': 'retime-llm-gpu', 'complete': 4, 'expected': 12, 'current_failures': 0, 'gpu': 5} +{'phase': 'retime-llm-gpu', 'complete': 5, 'expected': 12, 'current_failures': 0, 'gpu': 4} +{'phase': 'retime-llm-gpu', 'complete': 6, 'expected': 12, 'current_failures': 0, 'gpu': 3} +{'phase': 'retime-llm-gpu', 'complete': 7, 'expected': 12, 'current_failures': 0, 'gpu': 0} +{'phase': 'retime-llm-gpu', 'complete': 8, 'expected': 12, 'current_failures': 0, 'gpu': 2} +{'phase': 'retime-llm-gpu', 'complete': 9, 'expected': 12, 'current_failures': 0, 'gpu': 1} +{'phase': 'retime-llm-gpu', 'complete': 10, 'expected': 12, 'current_failures': 0, 'gpu': 5} +{'phase': 'retime-llm-gpu', 'complete': 11, 'expected': 12, 'current_failures': 0, 'gpu': 4} +{'phase': 'retime-llm-gpu', 'complete': 12, 'expected': 12, 'current_failures': 0, 'gpu': 3} +.....s..sss.................s..........s.s.......s.......s{"seed": 3, "backend": "source-mmap", "complete_model_bytes": 5852, "build_seconds": 0.0017918340000004918} +{"seed": 3, "backend": "int8", "complete_model_bytes": 4744, "build_seconds": 0.001494666999999339} +{"seed": 3, "backend": "ngram-bounded", "complete_model_bytes": 10446, "build_seconds": 0.6783434590000006} +{"seed": 3, "backend": "ngram-int8", "complete_model_bytes": 5050, "build_seconds": 0.008193666999998683} +{"seed": 3, "backend": "precomputed-words", "complete_model_bytes": 3221, "build_seconds": 0.009099791999998885} +{"backend": "precomputed-hybrid-source", "complete_model_bytes": 5715} +{"backend": "precomputed-hybrid-int8", "complete_model_bytes": 4986} +{"backend": "precomputed-hybrid-ngram-int8", "complete_model_bytes": 5275} +.s{"counts": {"original_rows": 3004, "selected_category_rows": 3003, "empty_rows": 1, "ag_input_overlap_rows": 1, "duplicate_rows": 1, "conflicting_category_duplicate_rows": 1}, "phase_stats": {"validation": {"documents": 600, "tokens": 1200, "oov_tokens": 600, "oov_heavy_documents": 600, "attempted_oov_ngrams": 4200, "missing_oov_ngrams": 4199, "truncated_documents": 0, "class_1": 600, "unique_oov_types": 600, "date_min": "2016-12-31", "date_max": "2017-01-01"}, "test": {"documents": 2400, "tokens": 4800, "oov_tokens": 2400, "oov_heavy_documents": 2400, "attempted_oov_ngrams": 16800, "missing_oov_ngrams": 16797, "truncated_documents": 0, "class_1": 2400, "unique_oov_types": 2400, "date_min": "2016-12-31", "date_max": "2017-01-01"}}} +......s.......s.sssusage: worker [-h] --phase {retime-long,retime-llm-cpu} --job JOB --output + OUTPUT --plan PLAN [--upstream UPSTREAM] --lane LANE --cohort + {parallel-shared-host,serial-reference} [--cache CACHE] + [--cached {0,1}] [--index {datrie,hash}] [--requests REQUESTS] + {worker} +worker: error: Fresh output and empty CUDA_VISIBLE_DEVICES required +.{'phase': 'retime-long', 'complete': 20, 'expected': 24} +{'phase': 'retime-long', 'serial_references': 1, 'expected': 16} +{'phase': 'retime-long', 'complete': 20, 'expected': 24} +{'phase': 'retime-long', 'serial_references': 1, 'expected': 16} +{'phase': 'retime-long', 'complete': 20, 'expected': 24} +..................ssss.ssssssssss.{"seed": 3, "backend": "source-resident", "complete_model_bytes": 2011, "build_seconds": 0.001472333000000603} +{"seed": 3, "backend": "source-mmap", "complete_model_bytes": 2008, "build_seconds": 0.0014699169999996542} +{"seed": 3, "backend": "linear-fused", "complete_model_bytes": 2009, "build_seconds": 0.004879834000000471} +{"seed": 3, "backend": "fp16", "complete_model_bytes": 2883, "build_seconds": 0.0015846250000013384} +{"seed": 3, "backend": "int8", "complete_model_bytes": 2946, "build_seconds": 0.0015784170000010533} +{"seed": 3, "backend": "ngram-bounded", "complete_model_bytes": 8002, "build_seconds": 0.029576750000000374} +{"seed": 3, "backend": "ngram-int8", "complete_model_bytes": 3605, "build_seconds": 0.00609245899999955} +{"seed": 3, "backend": "precomputed-words", "complete_model_bytes": 1670, "build_seconds": 0.008175459000000274} +....{"seed": 7, "backend": "source-mmap", "complete_model_bytes": 2013, "build_seconds": 0.002181833999999938} +{"seed": 7, "backend": "ngram-bounded", "complete_model_bytes": 8004, "build_seconds": 0.03261941600000107} +{"seed": 7, "backend": "ngram-int8", "complete_model_bytes": 3612, "build_seconds": 0.007925124999999866} +.s.ssssssssssssssssssssssss..{"retimed": 1, "expected": 40, "failures": 0} +{"retimed": 21, "expected": 40, "failures": 0} +{"retimed": 21, "expected": 40, "failures": 0} +........sssssss +---------------------------------------------------------------------- +Ran 379 tests in 15.210s + +OK (skipped=149) diff --git a/evidence/native_direct_gather_20261115/tests/remote-native-tests.log b/evidence/native_direct_gather_20261115/tests/remote-native-tests.log new file mode 100644 index 0000000..9eb44a3 --- /dev/null +++ b/evidence/native_direct_gather_20261115/tests/remote-native-tests.log @@ -0,0 +1,48 @@ +test_atomic_replacement_keeps_old_mmap_readers_on_original_bytes (tests.test_native_rows.NativeRowsTest.test_atomic_replacement_keeps_old_mmap_readers_on_original_bytes) ... ok +test_bag_calls_aggregate_codec_bytes_and_reset_on_rejected_input (tests.test_native_rows.NativeRowsTest.test_bag_calls_aggregate_codec_bytes_and_reset_on_rejected_input) ... ok +test_byte_cap_keeps_original_ids_with_compaction_permutation_and_tail (tests.test_native_rows.NativeRowsTest.test_byte_cap_keeps_original_ids_with_compaction_permutation_and_tail) ... ok +test_cache_consumes_later_hits_before_earlier_misses_evict_them (tests.test_native_rows.NativeRowsTest.test_cache_consumes_later_hits_before_earlier_misses_evict_them) ... ok +test_cache_hash_growth_eviction_and_budget_reset_match_lru_model (tests.test_native_rows.NativeRowsTest.test_cache_hash_growth_eviction_and_budget_reset_match_lru_model) ... ok +test_cache_preserves_older_library_loading_when_disabled (tests.test_native_rows.NativeRowsTest.test_cache_preserves_older_library_loading_when_disabled) ... ok +test_cache_raw_bypass_and_failed_decode_are_not_cached (tests.test_native_rows.NativeRowsTest.test_cache_raw_bypass_and_failed_decode_are_not_cached) ... ok +test_cache_reuses_exact_blocks_and_respects_lru_byte_budget (tests.test_native_rows.NativeRowsTest.test_cache_reuses_exact_blocks_and_respects_lru_byte_budget) ... ok +test_cache_uses_budget_beyond_64_entries_and_invalid_query_is_atomic (tests.test_native_rows.NativeRowsTest.test_cache_uses_budget_beyond_64_entries_and_invalid_query_is_atomic) ... ok +test_chunked_query_preserves_bytes_order_and_aggregates_all_counters (tests.test_native_rows.NativeRowsTest.test_chunked_query_preserves_bytes_order_and_aggregates_all_counters) ... ok +test_chunked_query_rejects_limits_capacities_and_late_invalid_ids (tests.test_native_rows.NativeRowsTest.test_chunked_query_rejects_limits_capacities_and_late_invalid_ids) ... ok +test_codec_bytes_count_whole_blocks_chunk_redecodes_cache_hits_and_raw (tests.test_native_rows.NativeRowsTest.test_codec_bytes_count_whole_blocks_chunk_redecodes_cache_hits_and_raw) ... ok +test_direct_script_import_remains_compatible_with_legacy_demo_entrypoints (tests.test_native_rows.NativeRowsTest.test_direct_script_import_remains_compatible_with_legacy_demo_entrypoints) ... ok +test_embedding_export_exposes_legacy_identity_format_option (tests.test_native_rows.NativeRowsTest.test_embedding_export_exposes_legacy_identity_format_option) ... ok +test_export_to_source_hardlink_does_not_modify_source (tests.test_native_rows.NativeRowsTest.test_export_to_source_hardlink_does_not_modify_source) ... ok +test_failed_flush_or_replace_preserves_target_and_cleans_temporary_file (tests.test_native_rows.NativeRowsTest.test_failed_flush_or_replace_preserves_target_and_cleans_temporary_file) ... ok +test_failed_partial_write_never_publishes_a_partial_table (tests.test_native_rows.NativeRowsTest.test_failed_partial_write_never_publishes_a_partial_table) ... ok +test_gather_array_matches_rows_and_rejects_bad_ids (tests.test_native_rows.NativeRowsTest.test_gather_array_matches_rows_and_rejects_bad_ids) ... ok +test_implicit_header_rejects_inconsistent_counts_overflows_and_legacy_layout (tests.test_native_rows.NativeRowsTest.test_implicit_header_rejects_inconsistent_counts_overflows_and_legacy_layout) ... ok +test_implicit_identity_saves_exact_map_bytes_with_unchanged_codec_payloads (tests.test_native_rows.NativeRowsTest.test_implicit_identity_saves_exact_map_bytes_with_unchanged_codec_payloads) ... ok +test_integer_grouping_matches_comparison_control_across_byte_boundaries (tests.test_native_rows.NativeRowsTest.test_integer_grouping_matches_comparison_control_across_byte_boundaries) ... ok +test_integer_xor_matches_reference_bytes_with_leading_and_trailing_zeros (tests.test_native_rows.NativeRowsTest.test_integer_xor_matches_reference_bytes_with_leading_and_trailing_zeros) ... ok +test_native_coalesces_blocks_and_rejects_bad_file (tests.test_native_rows.NativeRowsTest.test_native_coalesces_blocks_and_rejects_bad_file) ... ok +test_native_preserves_arbitrary_bytes_ids_and_batches (tests.test_native_rows.NativeRowsTest.test_native_preserves_arbitrary_bytes_ids_and_batches) ... ok +test_native_torch_adapter_direct_output (tests.test_native_rows.NativeRowsTest.test_native_torch_adapter_direct_output) ... ok +test_optional_fast_codecs_original_ids_odd_width_forwarding_cache_and_capabilities (tests.test_native_rows.NativeRowsTest.test_optional_fast_codecs_original_ids_odd_width_forwarding_cache_and_capabilities) ... ok +test_ordinary_embedding_and_max_norm_boundary (tests.test_native_rows.NativeRowsTest.test_ordinary_embedding_and_max_norm_boundary) ... ok +test_raw_direct_gather_preserves_forwarding_counters_and_error_output (tests.test_native_rows.NativeRowsTest.test_raw_direct_gather_preserves_forwarding_counters_and_error_output) ... ok +test_row_cache_chunk_counters_and_failed_queries_preserve_output (tests.test_native_rows.NativeRowsTest.test_row_cache_chunk_counters_and_failed_queries_preserve_output) ... ok +test_row_cache_failed_decode_never_publishes_rows (tests.test_native_rows.NativeRowsTest.test_row_cache_failed_decode_never_publishes_rows) ... ok +test_row_cache_retains_sparse_queries_and_forwarded_aliases (tests.test_native_rows.NativeRowsTest.test_row_cache_retains_sparse_queries_and_forwarded_aliases) ... ok +test_row_packet_headers_and_queried_payloads_reject_malformed_offsets_and_masks (tests.test_native_rows.NativeRowsTest.test_row_packet_headers_and_queried_payloads_reject_malformed_offsets_and_masks) ... ok +test_row_packets_preserve_original_ids_aliases_and_bounded_cache (tests.test_native_rows.NativeRowsTest.test_row_packets_preserve_original_ids_aliases_and_bounded_cache) ... ok +test_row_packets_sparse_decode_work_and_uint32_offsets (tests.test_native_rows.NativeRowsTest.test_row_packets_sparse_decode_work_and_uint32_offsets) ... ok +test_small_causal_transformer_logits_match_with_untied_embedding (tests.test_native_rows.NativeRowsTest.test_small_causal_transformer_logits_match_with_untied_embedding) ... ok +test_small_queries_and_disabled_chunking_keep_older_library_compatibility (tests.test_native_rows.NativeRowsTest.test_small_queries_and_disabled_chunking_keep_older_library_compatibility) ... ok +test_sparse_xor_prefix_keeps_full_stream_checks_and_cache_contents (tests.test_native_rows.NativeRowsTest.test_sparse_xor_prefix_keeps_full_stream_checks_and_cache_contents) ... ok +test_sparse_xor_prefix_uses_forwarded_rows_and_aggregates_chunk_work (tests.test_native_rows.NativeRowsTest.test_sparse_xor_prefix_uses_forwarded_rows_and_aggregates_chunk_work) ... ok +test_sparse_xor_work_accumulates_across_bags_without_changing_reductions (tests.test_native_rows.NativeRowsTest.test_sparse_xor_work_accumulates_across_bags_without_changing_reductions) ... ok +test_xor_codec_adapts_and_preserves_reordered_original_ids (tests.test_native_rows.NativeRowsTest.test_xor_codec_adapts_and_preserves_reordered_original_ids) ... ok +test_xor_decoder_handles_unaligned_rows_and_word_tails (tests.test_native_rows.NativeRowsTest.test_xor_decoder_handles_unaligned_rows_and_word_tails) ... ok +test_xor_empty_partial_blocks_and_invalid_permutations (tests.test_native_rows.NativeRowsTest.test_xor_empty_partial_blocks_and_invalid_permutations) ... ok +test_xor_torch_reconstructs_nonfinite_bit_patterns (tests.test_native_rows.NativeRowsTest.test_xor_torch_reconstructs_nonfinite_bit_patterns) ... ok + +---------------------------------------------------------------------- +Ran 43 tests in 13.110s + +OK diff --git a/evidence/native_direct_gather_20261115/tests/remote-sanitizers.log b/evidence/native_direct_gather_20261115/tests/remote-sanitizers.log new file mode 100644 index 0000000..6e2aeaf --- /dev/null +++ b/evidence/native_direct_gather_20261115/tests/remote-sanitizers.log @@ -0,0 +1 @@ +ASan/UBSan: versions 1/2/3/6/7, 384 mutated/truncated files, direct raw gathers and 300-block cache growth/eviction checked; optional LZ4/Zstd cases run when enabled. diff --git a/native/meft_rows.c b/native/meft_rows.c index 83cc5ad..19fe54a 100644 --- a/native/meft_rows.c +++ b/native/meft_rows.c @@ -49,6 +49,8 @@ struct meft_rows { size_t request_capacity; struct request *request_temporary; size_t temporary_capacity; + uint64_t *raw_seen; + size_t raw_seen_capacity; #ifdef MEFT_USE_LIBDEFLATE struct libdeflate_decompressor *decoder; #endif @@ -56,8 +58,8 @@ struct meft_rows { ZSTD_DCtx *zstd_decoder; #endif uint64_t last_blocks, last_decodes, last_hits, last_row_hits; - uint64_t last_compressed_bytes, last_decoded_bytes; - int cache_rows, implicit_identity; + uint64_t last_compressed_bytes, last_decoded_bytes, last_xor_bytes; + int cache_rows, implicit_identity, all_raw; size_t cache_budget, cache_used, cache_count; size_t cache_buckets; uint64_t cache_query; @@ -138,6 +140,7 @@ void meft_rows_close(meft_rows *s) { free(s->scratch); free(s->requests); free(s->request_temporary); + free(s->raw_seen); #ifdef MEFT_USE_LIBDEFLATE libdeflate_free_decompressor(s->decoder); #endif @@ -175,9 +178,11 @@ meft_rows *meft_rows_open(const char *path, char *err, size_t cap) { if (s->nblocks != s->unique / s->block_rows + (s->unique % s->block_rows != 0) || s->nblocks > (s->size - s->desc_start) / DESC) goto invalid; uint64_t previous_end = s->desc_start + s->nblocks * DESC; + s->all_raw = 1; for (uint64_t b = 0; b < s->nblocks; ++b) { const unsigned char *d = s->data + s->desc_start + b * DESC; uint64_t off = le64(d), stored = le64(d + 8), raw = le64(d + 16), codec = le64(d + 24); + if (codec) s->all_raw = 0; uint64_t rows = s->unique - b * s->block_rows; if (rows > s->block_rows) rows = s->block_rows; reason = "invalid block descriptor"; @@ -243,6 +248,7 @@ uint64_t meft_rows_last_block_reads(const meft_rows *s) { return s ? s->last_blo uint64_t meft_rows_last_decompressions(const meft_rows *s) { return s ? s->last_decodes : 0; } uint64_t meft_rows_last_compressed_bytes(const meft_rows *s) { return s ? s->last_compressed_bytes : 0; } uint64_t meft_rows_last_decoded_bytes(const meft_rows *s) { return s ? s->last_decoded_bytes : 0; } +uint64_t meft_rows_last_xor_bytes(const meft_rows *s) { return s ? s->last_xor_bytes : 0; } uint64_t meft_rows_last_cache_hits(const meft_rows *s) { return s ? s->last_hits : 0; } uint64_t meft_rows_last_row_cache_hits(const meft_rows *s) { return s ? s->last_row_hits : 0; } uint64_t meft_rows_cache_bytes(const meft_rows *s) { return s ? s->cache_used : 0; } @@ -273,6 +279,49 @@ static size_t cache_bucket(uint64_t block, size_t buckets) { block ^= block >> 31; return (size_t)block & (buckets - 1); } +#ifndef MEFT_DISABLE_RAW_GATHER +static int gather_raw(meft_rows *s, size_t count, void *out) { + /* Validated raw blocks form one contiguous physical-row payload, including + * reordered/deduplicated tables. No decode/cache grouping is necessary. + * Preserve distinct-block counters with query-sized scratch, not a bitmap + * proportional to the table. Optional allocation failure uses the grouped + * path. All IDs/forwarding entries were validated before touching output. */ + size_t buckets = 0; + size_t ordered = 1; + while (ordered < count && s->requests[ordered - 1].block <= s->requests[ordered].block) ++ordered; + if (ordered < count) { + if (count > SIZE_MAX / 2) return 1; + buckets = 8; + while (buckets < count * 2) { + if (buckets > SIZE_MAX / 2) return 1; + buckets *= 2; + } + if (buckets > SIZE_MAX / sizeof(*s->raw_seen)) return 1; + if (buckets > s->raw_seen_capacity) { + void *next = realloc(s->raw_seen, buckets * sizeof(*s->raw_seen)); + if (!next) return 1; + s->raw_seen = next; s->raw_seen_capacity = buckets; + } + memset(s->raw_seen, 0xff, buckets * sizeof(*s->raw_seen)); + } + const unsigned char *payload = s->data + s->desc_start + s->nblocks * DESC; + for (size_t i = 0; i < count; ++i) { + struct request *r = s->requests + i; + if (buckets) { + size_t bucket = cache_bucket(r->block, buckets); + while (s->raw_seen[bucket] != UINT64_MAX && s->raw_seen[bucket] != r->block) + bucket = (bucket + 1) & (buckets - 1); + if (s->raw_seen[bucket] == UINT64_MAX) { + s->raw_seen[bucket] = r->block; ++s->last_blocks; + } + } else if (!i || r->block != s->requests[i - 1].block) ++s->last_blocks; + uint64_t row = r->block * s->block_rows + r->within; + memcpy((unsigned char *)out + r->position * s->width, + payload + row * s->width, (size_t)s->width); + } + return 0; +} +#endif static void cache_unlink(meft_rows *s, struct cached_block *entry) { if (entry->previous) entry->previous->next = entry->next; else s->newest = entry->next; @@ -391,7 +440,7 @@ int meft_rows_gather(meft_rows *s, const uint64_t *ids, size_t count, void *out, size_t outbytes, char *err, size_t cap) { if (!s) return fail(err, cap, "null store"); s->last_blocks = s->last_decodes = s->last_hits = s->last_row_hits = 0; - s->last_compressed_bytes = s->last_decoded_bytes = 0; + s->last_compressed_bytes = s->last_decoded_bytes = s->last_xor_bytes = 0; if (count > SIZE_MAX / s->width || count * s->width > outbytes || count > SIZE_MAX / sizeof(struct request) || (count && (!ids || !out))) return fail(err, cap, "invalid output capacity or query size"); @@ -411,6 +460,9 @@ int meft_rows_gather(meft_rows *s, const uint64_t *ids, size_t count, requests[i].within = row % s->block_rows; requests[i].position = i; } +#ifndef MEFT_DISABLE_RAW_GATHER + if (s->all_raw && !gather_raw(s, count, out)) return 0; +#endif if (s->cache_count) { if (!++s->cache_query) { for (struct cached_block *entry = s->newest; entry; entry = entry->next) entry->query = 0; @@ -520,7 +572,22 @@ int meft_rows_gather(meft_rows *s, const uint64_t *ids, size_t count, * reconstructs original bits without floating-point arithmetic. */ if (codec == 2 || codec == 4 || codec == 6) { size_t width = (size_t)s->width; - for (size_t start = width; start < (size_t)raw; start += width) { + size_t reconstruct = (size_t)raw; +#ifndef MEFT_DISABLE_XOR_PREFIX + /* Stream decoding/checksums still cover the complete block. + * Reconstruct only through the last requested physical row when + * no full decoded block will enter the cache. Row-cache entries + * copy reconstructed requested rows, never the residual tail. + * A full-block cache always receives a fully reconstructed block. */ + if (s->cache_rows || s->cache_budget < raw) { + uint64_t last = requests[i].within; + for (size_t j = i + 1; j < count && requests[j].block == block; ++j) + if (requests[j].within > last) last = requests[j].within; + reconstruct = (size_t)(last + 1) * width; + } +#endif + s->last_xor_bytes += reconstruct - width; + for (size_t start = width; start < reconstruct; start += width) { unsigned char *current = s->scratch + start; const unsigned char *previous = current - width; size_t j = 0; @@ -557,13 +624,13 @@ int meft_rows_gather_chunked(meft_rows *s, const uint64_t *ids, size_t count, char *err, size_t cap) { if (!s) return fail(err, cap, "null store"); s->last_blocks = s->last_decodes = s->last_hits = s->last_row_hits = 0; - s->last_compressed_bytes = s->last_decoded_bytes = 0; + s->last_compressed_bytes = s->last_decoded_bytes = s->last_xor_bytes = 0; if (!max_query_rows || count > SIZE_MAX / s->width || count * s->width > outbytes || count > SIZE_MAX / sizeof(uint64_t) || (count && (!ids || !out))) return fail(err, cap, "invalid output capacity, query size or chunk limit"); uint64_t blocks = 0, decodes = 0, hits = 0, row_hits = 0; - uint64_t compressed_bytes = 0, decoded_bytes = 0; + uint64_t compressed_bytes = 0, decoded_bytes = 0, xor_bytes = 0; int status = 0; for (size_t start = 0; start < count;) { size_t n = count - start < max_query_rows ? count - start : max_query_rows; @@ -572,11 +639,13 @@ int meft_rows_gather_chunked(meft_rows *s, const uint64_t *ids, size_t count, n * (size_t)s->width, err, cap); blocks += s->last_blocks; decodes += s->last_decodes; hits += s->last_hits; row_hits += s->last_row_hits; compressed_bytes += s->last_compressed_bytes; decoded_bytes += s->last_decoded_bytes; + xor_bytes += s->last_xor_bytes; if (status) break; start += n; } s->last_blocks = blocks; s->last_decodes = decodes; s->last_hits = hits; s->last_row_hits = row_hits; s->last_compressed_bytes = compressed_bytes; s->last_decoded_bytes = decoded_bytes; + s->last_xor_bytes = xor_bytes; return status; } @@ -614,7 +683,7 @@ static int embedding_bag(meft_rows *s, const uint64_t *ids, size_t count, int weighted, const unsigned char *weights, size_t weights_bytes) { if (!s) return fail(err, cap, "null store"); s->last_blocks = s->last_decodes = s->last_hits = s->last_row_hits = 0; - s->last_compressed_bytes = s->last_decoded_bytes = 0; + s->last_compressed_bytes = s->last_decoded_bytes = s->last_xor_bytes = 0; size_t element = dtype == 1 ? 4 : 2; if (sizeof(float) != 4 || FLT_RADIX != 2 || FLT_MANT_DIG != 24 || dtype < 1 || dtype > 3 || (mean != 0 && mean != 1) || !chunk_rows || @@ -649,7 +718,7 @@ static int embedding_bag(meft_rows *s, const uint64_t *ids, size_t count, return fail(err, cap, "allocation failed"); } uint64_t blocks = 0, decodes = 0, hits = 0, row_hits = 0; - uint64_t compressed_bytes = 0, decoded_bytes = 0; + uint64_t compressed_bytes = 0, decoded_bytes = 0, xor_bytes = 0; int status = 0; size_t bag = 0, observed = 0; /* Coalesce blocks across bag boundaries, then consume restored ID order. @@ -660,6 +729,7 @@ static int embedding_bag(meft_rows *s, const uint64_t *ids, size_t count, status = meft_rows_gather(s, ids + start, n, rows, n * (size_t)s->width, err, cap); blocks += s->last_blocks; decodes += s->last_decodes; hits += s->last_hits; row_hits += s->last_row_hits; compressed_bytes += s->last_compressed_bytes; decoded_bytes += s->last_decoded_bytes; + xor_bytes += s->last_xor_bytes; if (status) goto done_bags; for (size_t i = 0; i < n; ++i) { while (bag < bags && offsets[bag + 1] <= start + i) { @@ -686,6 +756,7 @@ static int embedding_bag(meft_rows *s, const uint64_t *ids, size_t count, done_bags: s->last_blocks = blocks; s->last_decodes = decodes; s->last_hits = hits; s->last_row_hits = row_hits; s->last_compressed_bytes = compressed_bytes; s->last_decoded_bytes = decoded_bytes; + s->last_xor_bytes = xor_bytes; free(rows); free(sum); return status; } diff --git a/native/meft_rows.h b/native/meft_rows.h index a47b70a..c25e771 100644 --- a/native/meft_rows.h +++ b/native/meft_rows.h @@ -43,12 +43,14 @@ int meft_rows_set_cache_policy(meft_rows *store, int rows); uint64_t meft_rows_cache_bytes(const meft_rows *store); /* output must contain count * width bytes and must not overlap ids. * Failure may leave partial output; ignore it unless return value is zero. - * Reads are grouped by block and returned in original query order. + * Compressed reads are grouped by block; all-raw tables copy directly from + * the contiguous physical payload. Both return original query order and count + * distinct touched blocks. Raw counter scratch grows with query size. */ int meft_rows_gather(meft_rows *store, const uint64_t *ids, size_t count, void *output, size_t output_bytes, char *error, size_t error_capacity); /* Gather in chunks of at most max_query_rows>0 requests, directly into the - * caller's complete output. Bounds query-location/sort scratch, not output, + * caller's complete output. Bounds query-location/grouping scratch, not output, * decoded blocks, cache or total RSS. Each chunk groups its own block reads; * crossing chunks can repeat decoding. Last-query counters aggregate all chunks. * Each handle retains request scratch up to its largest earlier gather; @@ -114,6 +116,13 @@ uint64_t meft_rows_last_decompressions(const meft_rows *store); * work counters, not disk I/O, page faults or bytes resident in the OS cache. */ uint64_t meft_rows_last_compressed_bytes(const meft_rows *store); uint64_t meft_rows_last_decoded_bytes(const meft_rows *store); +/* Bytes reconstructed by previous-row XOR after stream decompression. Sparse + * zero/row-cache reads stop at the highest requested physical row per block. + * Populating a decoded-block cache reconstructs every row. The anchor row, + * raw/plain-stream/row-packet copies and cache hits contribute zero. Counters + * aggregate across chunk/bag calls; last_decoded_bytes still reports the full + * stream output and does not claim reduced compressed I/O or decompression. */ +uint64_t meft_rows_last_xor_bytes(const meft_rows *store); uint64_t meft_rows_last_cache_hits(const meft_rows *store); /* Distinct cached forwarded rows hit per gather, summed across chunk/bag calls. * Block hits remain separate and are zero in row mode (and vice versa). */ diff --git a/tests/test_native_rows.py b/tests/test_native_rows.py index 0d791f2..3e1ee69 100644 --- a/tests/test_native_rows.py +++ b/tests/test_native_rows.py @@ -21,6 +21,108 @@ def descriptor_start(data): class NativeRowsTest(unittest.TestCase): + def test_raw_direct_gather_preserves_forwarding_counters_and_error_output(self): + rng = random.Random(152) + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp); source = root / 'raw'; table = root / 'table' + width = 17; rows = [rng.randbytes(width) for _ in range(257)] + source.write_bytes(b''.join(rows + rows)) + control = root / 'grouped.so' + subprocess.run(['cc', '-std=c11', '-O2', '-fPIC', '-shared', '-DMEFT_DISABLE_RAW_GATHER', + str(ROOT / 'native/meft_rows.c'), '-lz', '-o', str(control)], check=True) + for options in ({'deduplicate': False}, {'deduplicate': True}, + {'deduplicate': False, 'row_order': list(reversed(range(514)))}, + {'deduplicate': False, 'representatives': [i % 257 for i in range(514)]}): + pack_native(source, table, width, 1, compress=False, **options) + for policy in ('rows', 'blocks'): + with self.subTest(options=tuple(options), policy=policy), NativeRows( + table, self.library, cache_bytes=4096, cache_policy=policy) as fast, NativeRows( + table, control, cache_bytes=4096, cache_policy=policy) as grouped: + for ids in ([513], list(range(514)), list(reversed(range(514))), + [rng.randrange(514) for _ in range(4096)], [256, 0, 256], []): + self.assertEqual(fast.rows(ids), grouped.rows(ids)) + self.assertEqual(fast.last_block_reads, grouped.last_block_reads) + self.assertEqual(fast.last_decompressions, 0) + self.assertEqual(fast.last_xor_bytes, 0) + self.assertEqual(fast.cache_bytes, 0) + ids = (ctypes.c_uint64 * 4)(513, 0, 514, 1) + out = ctypes.create_string_buffer(b'?' * (4 * width), 4 * width) + with self.assertRaisesRegex(ValueError, 'row ID out of bounds'): + fast.gather_into(ctypes.addressof(ids), 4, ctypes.addressof(out), len(out)) + self.assertEqual(out.raw, b'?' * (4 * width)) + self.assertEqual(fast.last_block_reads, 0) + ids[2] = 0 + fast.gather_into(ctypes.addressof(ids), 4, ctypes.addressof(out), len(out), max_query_rows=2) + self.assertEqual(out.raw, b''.join(rows[i % 257] for i in ids)) + grouped.gather_into(ctypes.addressof(ids), 4, ctypes.addressof(out), len(out), max_query_rows=2) + self.assertEqual(fast.last_block_reads, grouped.last_block_reads) + + def test_sparse_xor_prefix_keeps_full_stream_checks_and_cache_contents(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp); source = root / 'raw'; table = root / 'rows' + width = 17 + rows = [b'x' * 16 + bytes([i]) for i in range(37)] + source.write_bytes(b''.join(rows)) + meta = pack_native(source, table, width, 16, False, 'xor') + self.assertEqual(meta['xor_blocks'], 3) + ids = [17, 1, 3, 1, 32] + expected = b''.join(rows[i] for i in ids) + for policy, budget, xor_rows in (('blocks', 0, 4), ('blocks', 1, 4), + ('blocks', 4096, 34), ('rows', 4096, 4)): + with self.subTest(policy=policy, budget=budget), NativeRows( + table, self.library, cache_bytes=budget, cache_policy=policy) as reader: + self.assertEqual(reader.rows(ids), expected) + self.assertEqual(reader.last_xor_bytes, xor_rows * width) + self.assertEqual(reader.last_decoded_bytes, 37 * width) + if budget == 4096: + self.assertEqual(reader.rows([15, 16, 36]), b''.join(rows[i] for i in (15, 16, 36))) + # Full block-cache hits must return reconstructed tail + # rows even though the first query only needed prefixes. + if policy == 'blocks': + self.assertEqual(reader.last_decompressions, 0) + self.assertEqual(reader.last_xor_bytes, 0) + reader.rows([]); self.assertEqual(reader.last_xor_bytes, 0) + # The unused residual tail is still decompressed and CRC-checked. + valid = table.read_bytes(); off, stored, *_ = DESC.unpack_from(valid, descriptor_start(valid)) + corrupt = bytearray(valid); corrupt[off + stored - 1] ^= 1; table.write_bytes(corrupt) + with NativeRows(table, self.library) as reader: + with self.assertRaisesRegex(ValueError, 'decompression failed'): + reader.rows([0]) + + def test_sparse_xor_prefix_uses_forwarded_rows_and_aggregates_chunk_work(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp); source = root / 'raw'; table = root / 'rows' + width = 17; rows = [b'x' * 16 + bytes([i]) for i in range(37)] + source.write_bytes(b''.join(rows)) + pack_native(source, table, width, 16, False, 'xor', row_order=list(reversed(range(37)))) + with NativeRows(table, self.library) as reader: + self.assertEqual(reader.rows([36, 33, 35, 36]), b''.join(rows[i] for i in (36, 33, 35, 36))) + self.assertEqual(reader.last_xor_bytes, 3 * width) + source.write_bytes(b''.join(rows + rows)) + pack_native(source, table, width, 16, True, 'xor') + with NativeRows(table, self.library) as reader: + self.assertEqual(reader.rows([40, 3, 38]), b''.join(rows[i] for i in (3, 3, 1))) + self.assertEqual(reader.last_xor_bytes, 3 * width) + ids = (ctypes.c_uint64 * 3)(0, 17, 3); out = ctypes.create_string_buffer(3 * width) + reader.gather_into(ctypes.addressof(ids), 3, ctypes.addressof(out), len(out), max_query_rows=1) + self.assertEqual(out.raw, b''.join(rows[i] for i in (0, 17, 3))) + self.assertEqual(reader.last_xor_bytes, 4 * width) + with self.assertRaises(IndexError): reader.rows([74]) + reader.gather_into(0, 0, 0, 0); self.assertEqual(reader.last_xor_bytes, 0) + + def test_sparse_xor_work_accumulates_across_bags_without_changing_reductions(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp); source = root / 'raw'; table = root / 'rows' + rows = [struct.pack('<4f', i + .5, -i, i / 8., 1.) for i in range(37)] + source.write_bytes(b''.join(rows)); pack_native(source, table, 16, 16, False, 'xor') + with NativeRows(table, self.library) as reader: + ids = (ctypes.c_uint64 * 3)(0, 17, 3); offsets = (ctypes.c_uint64 * 3)(0, 2, 3) + out = (ctypes.c_float * 8)() + reader.embedding_bag_into(ctypes.addressof(ids), 3, ctypes.addressof(offsets), 2, + 1, False, ctypes.c_uint64(-1).value, 1, ctypes.addressof(out), 8) + self.assertEqual(list(out), [18., -17., 17 / 8., 2., 3.5, -3., 3 / 8., 1.]) + self.assertEqual(reader.last_xor_bytes, 4 * 16) + def test_row_packets_preserve_original_ids_aliases_and_bounded_cache(self): with tempfile.TemporaryDirectory() as tmp: root = Path(tmp); source = root / 'raw'; table = root / 'rows' diff --git a/tools/benchmark_native_gather.py b/tools/benchmark_native_gather.py new file mode 100644 index 0000000..60f80a7 --- /dev/null +++ b/tools/benchmark_native_gather.py @@ -0,0 +1,139 @@ +"""Paired CPU gathers of existing trained codes on saved original-ID traces. + +No training, repacking or GPU work. Both libraries read the same immutable +table; every result is compared with its original code bytes. This measures +row lookup after addressing, not quantizer decoding or complete LLM inference. +""" +import argparse +import ctypes +import hashlib +import importlib.metadata +import json +import math +import os +from pathlib import Path +import platform +import shlex +import statistics +import sys +import time + +import numpy as np + +from .native_row_store import NativeRows + + +def digest(path): + value = hashlib.sha256() + with Path(path).open('rb') as stream: + for block in iter(lambda: stream.read(1 << 20), b''): + value.update(block) + return value.hexdigest() + + +def benchmark(args): + if args.repeat < 1 or args.rounds < 1 or args.warmup < 0 or args.cache_bytes < 0: + raise ValueError('positive rounds/repeats and nonnegative warmup/cache required') + if args.core is not None: + os.sched_setaffinity(0, {args.core}) + trace_metadata = json.loads(args.traces.with_suffix('.json').read_text()) + if digest(args.traces) != trace_metadata['trace_sha256']: + raise ValueError('original trace changed') + source = np.load(args.codes, mmap_mode='r', allow_pickle=False) + trace = np.load(args.traces, allow_pickle=False) + queries = [] + for i, record in enumerate(trace_metadata['requests']): + ids = trace['ids' + str(i)] + if ids.dtype.kind not in 'iu' or ids.ndim != 1 or np.any(ids < 0) or np.any(ids >= len(source)): + raise ValueError('invalid original row IDs') + if hashlib.sha256(ids.tobytes()).hexdigest() != record['ids_sha256']: + raise ValueError('original query changed') + ids = np.ascontiguousarray(ids, dtype=np.uint64) + expected = source[ids].tobytes() + queries.append((ids, expected)) + width = int(source.shape[1] * source.dtype.itemsize) + result = {'commit': args.commit, 'command': shlex.join([sys.executable, *sys.argv]), + 'python': sys.version, 'numpy': np.__version__, 'os': platform.platform(), + 'cpu_affinity': sorted(os.sched_getaffinity(0)) if hasattr(os, 'sched_getaffinity') else None, + 'loadavg': list(os.getloadavg()), 'device': 'cpu', 'gpu': 'unused', + 'rows': len(source), 'row_bytes': width, 'repeat': args.repeat, 'rounds': args.rounds, + 'warmup': args.warmup, 'cache_bytes': args.cache_bytes, 'cache_policy': args.cache_policy, + 'trace_sha256': digest(args.traces), 'trace_metadata_sha256': digest(args.traces.with_suffix('.json')), + 'trace_domain': trace_metadata['domain'], + 'table_sha256': digest(args.table), 'codes_sha256': digest(args.codes), + 'libraries_sha256': {name: digest(path) for name, path in + (('baseline', args.baseline_library), ('candidate', args.library))}, + 'source_sha256': digest(__file__), 'round_results': [], + 'scope': 'Saved original canonical row queries on existing trained memory codes. Warm OS cache, single CPU core; paired rounds are descriptive, not confidence bounds or complete inference speedups. Original vectors, source codes and query IDs are not exported.', + 'cost': 'Existing CPU resources; no GPU, training or paid API. Energy/monetary costs unmeasured.'} + try: + result['torch'] = importlib.metadata.version('torch') + except importlib.metadata.PackageNotFoundError: + result['torch'] = 'unused, not installed' + cpuinfo = Path('/proc/cpuinfo') + result['cpu'] = next((line.split(':', 1)[1].strip() for line in cpuinfo.read_text().splitlines() + if line.startswith('model name')), platform.machine()) if cpuinfo.exists() else platform.machine() + for round_id in range(args.rounds): + with NativeRows(args.table, args.baseline_library, cache_bytes=args.cache_bytes, + cache_policy=args.cache_policy) as baseline, NativeRows( + args.table, args.library, cache_bytes=args.cache_bytes, + cache_policy=args.cache_policy) as candidate: + stores = {'baseline': baseline, 'candidate': candidate} + result['decoders'] = {name: store.decoder_name for name, store in stores.items()} + result['request_count'] = len(queries) + result['rows_per_request'] = [len(ids) for ids, _ in queries] + if any(s.header != {'n_rows': len(source), 'row_bytes': width} for s in stores.values()): + raise ValueError('table/source dimensions differ') + output = {name: [np.empty((len(ids), width), dtype=np.uint8) for ids, _ in queries] + for name in stores} + counts = {name: {key: 0 for key in ('blocks', 'decodes', 'compressed_bytes', 'decoded_bytes', 'xor_bytes')} + for name in stores} + samples = {name: [] for name in stores} + for repeat in range(-args.warmup, args.repeat): + for i, (ids, expected) in enumerate(queries): + order = ('baseline', 'candidate') if (round_id + repeat + i) % 2 else ('candidate', 'baseline') + work = {} + for name in order: + store = stores[name]; out = output[name][i] + started = time.perf_counter_ns() + store.gather_into(ids.ctypes.data, len(ids), out.ctypes.data, out.nbytes) + elapsed = time.perf_counter_ns() - started + if out.tobytes() != expected: + raise ValueError('original code bytes changed: ' + name) + work[name] = (store.last_block_reads, store.last_decompressions, + store.last_compressed_bytes, store.last_decoded_bytes, store.last_xor_bytes) + if repeat >= 0: + samples[name].append(elapsed / 1000.) + for key, count in zip(counts[name], work[name]): + counts[name][key] += count + if work['baseline'][:4] != work['candidate'][:4]: + raise ValueError('stream decode/cache work differs') + result['round_results'].append({'round': round_id, 'samples_us': samples, 'work': counts, + 'p50_us': {name: statistics.median(values) for name, values in samples.items()}, + 'p95_us': {name: sorted(values)[math.ceil(.95 * len(values)) - 1] for name, values in samples.items()}, + 'paired_geometric_speed_ratio': math.exp(statistics.mean(math.log(a / b) for a, b in + zip(samples['baseline'], samples['candidate']))), 'original_code_bytes_match': True}) + result['status'] = 'passed' + result['geometric_speed_ratio'] = math.exp(statistics.mean(math.log(r['paired_geometric_speed_ratio']) + for r in result['round_results'])) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(result, indent=2, allow_nan=False) + '\n') + print(json.dumps({'status': 'passed', 'output': str(args.output), 'speed_ratio': result['geometric_speed_ratio']}), flush=True) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + for name in ('table', 'codes', 'traces', 'baseline-library', 'library', 'output'): + parser.add_argument('--' + name, type=Path, required=True) + parser.add_argument('--commit', required=True) + parser.add_argument('--core', type=int) + parser.add_argument('--repeat', type=int, default=10) + parser.add_argument('--rounds', type=int, default=3) + parser.add_argument('--warmup', type=int, default=2) + parser.add_argument('--cache-bytes', type=int, default=0) + parser.add_argument('--cache-policy', choices=('blocks', 'rows'), default='blocks') + benchmark(parser.parse_args()) + + +if __name__ == '__main__': + main() diff --git a/tools/check_native_sanitizers.py b/tools/check_native_sanitizers.py index 3fd21e9..ad4899b 100644 --- a/tools/check_native_sanitizers.py +++ b/tools/check_native_sanitizers.py @@ -47,6 +47,10 @@ def main(): if packed["raw_blocks"]: raise AssertionError("cache sanitizer fixture must use compressed blocks") subprocess.run([str(driver), str(table)], check=True) + # Exercise direct raw gathers, forwarding, query hashes and invalid IDs. + for implicit in (False, True): + pack_native(source, table, 128, 1, False, compress=False, implicit_identity=implicit) + subprocess.run([str(driver), str(table)], check=True) flags = os.environ.get('MEFT_NATIVE_TEST_FLAGS', '') for implicit in (False, True): packed = pack_native(source, table, 128, 64, False, predictor='none', implicit_identity=implicit, codec='row-xor') @@ -74,7 +78,7 @@ def main(): changed = changed[:rng.randrange(len(changed))] table.write_bytes(changed) subprocess.run([str(driver), str(table)], check=True) - print("ASan/UBSan: versions 1/2/3/6/7, 384 mutated/truncated files and 300-block cache growth/eviction checked; optional LZ4/Zstd cases run when enabled.") + print("ASan/UBSan: versions 1/2/3/6/7, 384 mutated/truncated files, direct raw gathers and 300-block cache growth/eviction checked; optional LZ4/Zstd cases run when enabled.") if __name__ == "__main__": diff --git a/tools/native_row_store.py b/tools/native_row_store.py index d61707e..53ca230 100644 --- a/tools/native_row_store.py +++ b/tools/native_row_store.py @@ -476,6 +476,13 @@ def last_compressed_bytes(self): def last_decoded_bytes(self): return self._counter("last_decoded_bytes") + @property + def last_xor_bytes(self): + """Previous-row XOR reconstruction work, separate from stream output.""" + if not hasattr(self.lib, "meft_rows_last_xor_bytes"): + raise ValueError("XOR work counters require rebuilding the row library") + return self._counter("last_xor_bytes") + def close(self): if self.handle: self.lib.meft_rows_close(self.handle)