Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ PYTHON ?= python3
# Optional Linux FastText facade; retain the original binary/library targets.
fasttext-native:
mkdir -p build
$(CC) -std=c11 -O2 -fPIC -c native/meft_rows.c -o build/meft_rows_fasttext.o
$(CC) -std=c11 -O3 -fPIC -c native/meft_rows.c -o build/meft_rows_fasttext.o
$(CXX) $(CXXFLAGS) -O2 -DMEFT_NATIVE_FASTTEXT -Isrc -Inative $(INCLUDES) $(addprefix src/,$(OBJS:.o=.cc)) native/fasttext_bundle.cc src/main.cc build/meft_rows_fasttext.o $(LIBS) -lz -o build/fasttext-native

# Optional original-algorithm bridge; bundled archives require Linux x86-64.
Expand All @@ -36,8 +36,8 @@ NATIVE_EXT ?= so
NATIVE_CODEC_FLAGS ?=
native:
mkdir -p build
$(CC) -std=c11 -O2 -Wall -Wextra -Werror -fPIC $(NATIVE_SHARED) native/meft_rows.c -lz $(NATIVE_CODEC_FLAGS) -o build/libmeft_rows.$(NATIVE_EXT)
$(CC) -std=c11 -O2 -Wall -Wextra -Werror -Inative examples/native_gather.c native/meft_rows.c -lz $(NATIVE_CODEC_FLAGS) -o build/native_gather
$(CC) -std=c11 -O3 -Wall -Wextra -Werror -fPIC $(NATIVE_SHARED) native/meft_rows.c -lz $(NATIVE_CODEC_FLAGS) -o build/libmeft_rows.$(NATIVE_EXT)
$(CC) -std=c11 -O3 -Wall -Wextra -Werror -Inative examples/native_gather.c native/meft_rows.c -lz $(NATIVE_CODEC_FLAGS) -o build/native_gather

opt: CXXFLAGS += -O1 -funroll-loops
opt: fasttext $(LIBNAME).a index cut_ngram print_ngrams bench_ftindex
Expand Down
9 changes: 9 additions & 0 deletions docs/guides/native_ngram_memory.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,15 @@ 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.

`NativeRows.embedding_bag_array(ids, offsets, dtype="float32", mode="mean")`
provides NumPy-only ragged pooling. Offsets include the terminal ID count;
FP64 accumulation returns FP32 features. Default FP32 vectorized pooling is
1.71–1.80× faster per document and 2.98–3.12× at batch 32 on the measured raw
tables ([results and ablations](../../evidence/native_bag_vectorization_20261116/README.md)).
For lower temporary memory, open with `raw_bag_fusion=True`; on all-raw tables
this avoids the row matrix, with a throughput tradeoff. Compressed reads retain
bounded staging. `last_bag_staging_bytes` reports row-matrix capacity, not RSS.

## Native layout and construction

`MEFTNAT1` is a little-endian binary file: a versioned header, an optional
Expand Down
1 change: 1 addition & 0 deletions evidence/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ here: links in locked READMEs still point to them, and they forward to
| [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 |
| [Vectorized NumPy/native bags](native_bag_vectorization_20261116/README.md) | Default FP32 pooling is 1.71–1.80× faster for individual documents and 2.98–3.12× for batches of 32 on the existing raw AG News/DBpedia tables. Source features match byte-for-byte. Optional raw fusion removes a 2 MiB row matrix but is slower than staged vectorization; Zstd remains decode-bound |
| [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 |
Expand Down
121 changes: 121 additions & 0 deletions evidence/native_bag_vectorization_20261116/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
# Vectorized native embedding bags, with optional zero-row-staging fusion

The engine now exposes `NativeRows.embedding_bag_array`: a NumPy-only ragged
sum/mean API. FP32 has a dedicated dimension loop that GCC vectorizes without
changing original-row accumulation order, FP64 products/sums or final FP32
conversion. FP16/BF16 retain the existing decoder. Weighted native bags share
the optimization; their existing sum-only semantics remain unchanged.

The default retains bounded row staging because it is faster. All-raw tables
can opt into direct mmap accumulation with `raw_bag_fusion=True`, eliminating
the row matrix while retaining original-ID forwarding and chunk/block counters.
Compressed tables keep chunk staging. No table formats or stored vectors change.

## Default performance on frozen trained tables

Paired **public NumPy/C mean-pooling calls**, including input validation and C
reduction. Excludes tokenization, classifier head, GPU transfers and full models.

| Table, seed 3 | Original rows | Documents/call | Baseline p50 (µs) | Default vectorized p50 (µs) | Paired geometric speed ratio |
| --- | ---: | ---: | ---: | ---: | ---: |
| AG News, uniform | 6,989,612 | 1 | 116.16 | 67.68 | 1.71× |
| AG News, uniform | 6,989,612 | 32 | 2428.91 | 826.23 | 2.98× |
| AG News, zero | 6,989,612 | 1 | 114.27 | 65.87 | 1.73× |
| AG News, zero | 6,989,612 | 32 | 2370.31 | 769.23 | 3.12× |
| DBpedia, uniform | 34,050,161 | 1 | 134.11 | 73.48 | 1.80× |
| DBpedia, uniform | 34,050,161 | 32 | 2956.92 | 972.76 | 3.05× |
| DBpedia, zero | 34,050,161 | 1 | 136.10 | 75.36 | 1.77× |
| DBpedia, zero | 34,050,161 | 32 | 2922.80 | 954.64 | 3.07× |

Both arms read the same existing uncompressed/deduplicated table and each output
is compared byte-for-byte with independently computed source FP64 mean features,
rounded to FP32. All checked features match. Uniform-init byte dedup expands the
table; its inclusion tests the kernel and does not recommend dedup over raw.

- Models/data: the registered AG News/DBpedia classifiers, zero and uniform
initialization, seed 3; no retraining. 256 official test documents per dataset,
seed 20261112, original IDs and full lengths. OOV zero removed as in the
registered `StagedClassifier` protocol. Batches preserve document boundaries.
- Measurement: 2 warmup passes, 10 timed passes, 3 alternating paired rounds;
independent handles, preallocated outputs, zero native cache, chunk limit
4096. p50 columns are medians of round p50s. Five CPU jobs ran on distinct
pinned cores. Ratios are descriptive, not confidence intervals or application
accuracy/latency claims.
- AMD EPYC 7713, Linux 5.4, Python 3.11.15, NumPy 2.2.6, PyTorch 2.11.0, GCC
11.4.0, `-O3` without unsafe floating-point or architecture-specific flags.
Wheel and Makefile native builds use the same optimization level.
[Compiler diagnostics](tests/vectorization.log) confirm 16-byte vectorization.
- Source commit `4f6fa5a7a7c9e2eb42d5043784d39738150de23b`.
Existing CPU resources; no GPU, training or paid API. Energy/monetary costs
unmeasured. [Build and library hashes](build.json), [commands](run-status.json).

## Memory preference and ablations

Fusion alone (`f51f486`) saved row staging but measured **0.95–1.00×** speed.
Dedicated FP32 vectorization plus fusion (`854fd04`) improved the raw-table
calls, but an additional [same-vector-kernel comparison](fusion-ablation.json)
found staged reduction faster on both AG News batch-32 controls. Therefore the
final default is staged/vectorized; fusion is an explicit memory preference.
The comparison reused parent input hashes, rechecked original trace hashes and
compared every output against freshly read source features.

On the checked batch-32 raw calls, fusion reduces the allocated row matrix from
**2,097,152 bytes to zero**. This counter excludes query indexes, FP64 accumulator,
output, caches and total RSS. It is not a total-process memory guarantee.
`last_bag_staging_bytes` reports the actual row-matrix allocation capacity. A
failed optional raw counter-index allocation can fall back to staged reading.

The AG News zero-init Zstd batch-32 control stays about **1.01×** with the final
kernel; decompression still dominates. Both arms still stage 2 MiB. That control
uses 1 warmup, 3 repeats and 2 rounds. All earlier slow/no-gain results remain in
[raw/](raw/); [summary.json](summary.json) indexes all 27 timing cells.

## Use without PyTorch

```python
import numpy as np
from ngram_store import NativeRows

with NativeRows("memory.native/table.men") as memory:
pooled = memory.embedding_bag_array(
np.array([1, 42, 1], dtype=np.uint64),
np.array([0, 2, 3], dtype=np.uint64),
dtype="float32", mode="mean", chunk_rows=4096,
) # two original-ID bags, FP64 accumulation -> FP32 output

# Prefer zero row-matrix allocation on all-raw tables:
with NativeRows("memory.native/table.men", raw_bag_fusion=True) as memory:
pooled = memory.embedding_bag_array([1, 42, 1], [0, 2, 3])
assert memory.last_bag_staging_bytes == 0
```

Offsets include the terminal ID count. Empty bags return zero. `padding_id`
excludes that original row from sums and mean denominators. Optional `out`
requires a writable contiguous FP32 array of `(bags, dim)`. Dtype strings are
`float32`, `float16`, `bfloat16`; the caller owns the stored dtype contract.
Existing row/gather APIs and compiled-library default loading remain compatible.
Opt-in fusion requires rebuilding the C library. The C setter is
`meft_rows_set_raw_bag_fusion(store, 1)`.

## Verification and reproduction

[Tests](tests/): 381 local tests passed (149 optional skips), 45 local native
passed (5 optional skips), and 56 remote native/PyTorch bag tests passed without
skips. Local/remote ASan+UBSan passed, including raw fusion on mutated artifacts.
An additional 45-test local native run with `-O3` passed (5 optional skips),
and a fresh Python 3.12 package loaded outside the checkout passed NumPy bag
and mode-switch checks without importing Torch.
Coverage includes all three dtypes, weights, padding, empty bags, forwarding,
odd dimensions, chunk boundaries, compressed caches, output reuse and errors.

The general entry point is
[`tools/benchmark_native_bags.py`](../../tools/benchmark_native_bags.py);
[scripts/](scripts/) retain the exact existing-workspace launches and ablation.
The first two phases computed full table/code hashes. The final default run
explicitly inherited those immutable-input hashes from the parent vector run,
rechecked trace/metadata hashes and every source feature, and records parent
report hashes plus current file stats. It does not describe inherited hashes as
new full-file verification. Omitting `--hashes-from` recomputes full input hashes.

Timing records are gzip-compressed to keep the checkout small. Tables, weights,
query arrays and corpora remain in the experiment workspace.
54 changes: 54 additions & 0 deletions evidence/native_bag_vectorization_20261116/build.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
{
"commit": "4f6fa5a7a7c9e2eb42d5043784d39738150de23b",
"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",
"compile": "cc -std=c11 -O3 -fPIC -shared native/meft_rows.c -lz FLAGS -o LIBRARY",
"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",
"baseline_extra": "-DMEFT_DISABLE_RAW_BAG -DMEFT_DISABLE_FP32_BAG_VECTOR",
"headers_manifest": "/llm-align/duyimin/ngram-sparse-xor-20261115/results/build.json",
"files": {
"/llm-align/duyimin/ngram-direct-bags-20261116/runtime/native/meft_rows.c": {
"bytes": 46680,
"sha256": "254ff1e0452a670cd68b5fff4ec2e460376e252595b79de2af9fc766e8ae23e0"
},
"/llm-align/duyimin/ngram-direct-bags-20261116/runtime/native/meft_rows.h": {
"bytes": 9336,
"sha256": "42a4e76dc37b7afc16eee5cbef579203576e20e09e1e920e693887b1ef621d60"
},
"/llm-align/duyimin/ngram-direct-bags-20261116/runtime/tools/native_row_store.py": {
"bytes": 29450,
"sha256": "bd4db7acedadfdf7301246e036b5463350ef1bf1fa0462b8c545f5d91de52e49"
},
"/llm-align/duyimin/ngram-direct-bags-20261116/runtime/tools/benchmark_native_bags.py": {
"bytes": 8358,
"sha256": "7331bca667d43b6234f83a28ee65963f9775d1bc6dd4cc262054803910ea121a"
},
"/llm-align/duyimin/ngram-direct-bags-20261116/lib/candidate-vector.so": {
"bytes": 38712,
"sha256": "b12cf651f8d1f10511890b1153da378ae61663be9ae85313557ada8b3d2d2fc7"
},
"/llm-align/duyimin/ngram-direct-bags-20261116/lib/staged-vector.so": {
"bytes": 38624,
"sha256": "d1089329d120a0aaf8fb5d4a93dbe77555c3f061372dbaf13c3fc1bdb1ac848a"
},
"/llm-align/duyimin/ngram-direct-bags-20261116/lib/candidate.so": {
"bytes": 38712,
"sha256": "b71226b8354c790a66ab174a6facb3d65a1402c28c4c85bcfeb110fb6c8eaca3"
},
"/llm-align/duyimin/ngram-direct-bags-20261116/lib/baseline-final.so": {
"bytes": 38680,
"sha256": "608950f28393173a759cb26db59e8ffd039aa8d0c97f2fea0bd1648be09f0e59"
},
"/llm-align/duyimin/ngram-direct-bags-20261116/lib/baseline.so": {
"bytes": 38624,
"sha256": "6f714590455aa49910d49f9f32930c70c4324c7dbb76576c0ea91e6b36985195"
},
"/llm-align/duyimin/ngram-direct-bags-20261116/lib/candidate-final.so": {
"bytes": 38768,
"sha256": "7fabbd7281029cbdb41b3c161005e4b2c982a0cd94e21e532ccef105471465e7"
},
"/llm-align/duyimin/ngram-direct-bags-20261116/lib/baseline-vector.so": {
"bytes": 38624,
"sha256": "6f714590455aa49910d49f9f32930c70c4324c7dbb76576c0ea91e6b36985195"
}
}
}
Loading
Loading