Author SHA1 Message Date
Muse c6a13f189c integration: record fresh benchmark numbers in docs/INTEGRATION.md
bench-integration.sh (best-of-3, mixed set + 1 MiB random) plus the
codec-name fix for the intlv speed run. Headline fresh numbers:
intlv-d64 enc 3.77 / dec 1.72 MB/s at 5.40% overhead; ldpc-r90 enc
4.08 / dec 1.07 at 10.94%; recovery 1.000 on the mixed blob for all
three ECC winners. Dict is +2.7% worse on the repo-sources-only code
corpus (branch -2.1% was header-heavy code) -- recorded honestly.
2026-12-02 15:47:38 +00:00
Muse fddd00c784 integration: fix codec name in smoke tests (intlv-d64-bch1k-t32)
The bench codec is intlv-d{D}-bch1k-t{T}; the bare intlv-d64-t32
name matched nothing, so the clean round-trip and speed checks
failed on unknown-codec (the burst check already used the right
name and passed 1.0000).
2026-12-02 15:38:54 +00:00
Muse 0f2cb105fc integration: build corpora from varied tree content, not repetition
Repeating the docs x12 still gave a 30 KiB lzip blob (LZMA eats
repeats). Use every text file in the tree for the text corpus and
every C file for the code corpus: ~1 MB raw -> 188 KiB blob (text),
~120 KiB blob (code). Same fix in bench-integration.sh.
2026-12-02 15:35:10 +00:00
Muse e53455bf07 integration: fix smoke-test corpus size + commit benchmark script
The docs corpus (86 KiB raw) compresses to 30 KiB under lzip -6,
below the 64 KiB bench window: repeat it x12 (~1 MB raw, ~90 KiB
blob) and the C sources x3. Also commits bench-integration.sh, the
best-of-3 benchmark harness used for the integration numbers.
2026-12-02 15:28:50 +00:00
Muse f60ca9fd73 integration: wire winners into the build + tests, document in docs/INTEGRATION.md
- make exp / make experiments build the integrated winners
  (exp/bench + diags; experiments/rans_tool + dict + bchcheck)
- make test runs tests/run_integration_tests.sh: clean round-trips
  for all three ECC codecs, intlv-d64 burst survival + uninterleaved
  control, bch1k BER survival + as-shipped control, LDPC BER survival,
  rANS round-trip, dict+lzip round-trip, bchcheck 8-flip recovery and
  32-flip expected failure, LZPL v5 archive round-trip
- docs/INTEGRATION.md: the four winners with measured numbers, the
  rejects with numbers, build/test instructions
- README.md: Integrated experiments section; branch READMEs carry a
  pointer to docs/INTEGRATION.md
Archive format unchanged (LZPL v5); wiring interleave/LDPC into
lzply -e levels would be a format change and is future work.
2026-12-02 14:42:57 +00:00
Muse bf8efab2b7 integration: drop rejected families (polar, UEP, lzrans, BWT, PPM)
The experiment branches measured these and rejected them; only their
numbers stay (in the READMEs and results/*.csv), the code does not
carry over to the integrated tree:
- polar SC: 0.00 at BER 1e-3 at every design point, dec 0.58 MB/s
- UEP: whole-file recovery dominated by the weak tier (0.00 at 1e-3);
  its prefix-survival property needs a salvage mode lzply lacks
- lzrans: ~75% relative ratio gap to lzip on text, static rANS
- BWT: 0.05 MB/s encode, loses to lzip everywhere
- PPM order-2: 32.84% on text vs lzip 3.56%, 6 MB/s encode
Winners kept: interleave d64 + bch1k, LDPC r90, dict transform,
rANS core.
2026-12-02 14:40:39 +00:00
Muse 1239bd9c64 experiments: BWT, PPM, dict transform, BCH corruption harness + results
BWT+MTF+rANS (cyclic-doubling SA; linear sort is NOT rotation
order, sentinel does not fix it), order-2 PPM + WNC arithmetic
coder, word-dictionary transform + lzip, bchcheck (BCH t=8
corruption harness), bench1 single-run harness. Results:
BWT text 6.35 / code 12.31 / bin 42.76 (encode ~3 min/8 MB);
PPM text 32.84 / code 30.82 / mixed 39.18; dict+lzip6 code
9.19 vs plain 9.38 (+2.1%, only code wins); BCH: dict+lzip
code blob survives 8 flips (8 corrected, bit-identical), fails
at 32 flips as expected. No family beats lzip on ratio; rANS
core kept as infrastructure, dict conditional on code. Full
tables + verdicts in experiments/README.md. BWT mixed/rand
still benching at commit time.
2026-12-02 14:40:06 +00:00
Muse 2932575441 experiments: rANS core + order-0 tool, LZ77+rANS (lazy/optimal), bench harness
rANS entropy coder (12-bit probs, 23-bit window) with byte and
general-alphabet layers; standalone order-0 tool (enc 30-38 MB/s)
and an LZ77+rANS prototype (hash chains, 1 MiB window, lazy and
optimal-parse modes). Bench harness + deterministic corpora builder
(text/code/bin/mixed 8 MiB, rand 4 MiB) and baseline numbers:
lzip -6 text 3.56% / code 9.38% / bin 32.61% / mixed 17.41%.
lzrans-lazy: text 6.26% / code 13.52% / bin 41.84%; optimal
parsing recovers only ~1-3% relative, so the gap is LZMA adaptive
entropy modelling, not parsing -- lzrans rejected as a lzip
replacement (see experiments/README.md). All round-trips sha256-verified.
2026-12-02 14:40:06 +00:00
Muse 4c32b542ba exp: gitignore the diag binaries 2026-12-02 14:39:53 +00:00
Muse c07d986cd9 exp: final README — pass-2 verdict (0/875), speeds, cross-corpus, totals
- Pass 2: 35 rows x 25 trials = 875, rescued 0. Repo's own test
  agrees (t+1 0/100, t+2 0/100).
- Isolated speed table (sequential): interleave costs nothing
  measurable; LDPC dec 0.91 MB/s; polar dec 0.58 MB/s.
- Cross-corpus (bin.lz, rand.lz) reproduces text.lz exactly.
- Test totals: 51,875 matrix trials + diagnostics.
- hot_chicago verification BLOCKED (tunnel down 4 attempts);
  snapshot zips staged on old VPS for a later retry.
2026-12-02 14:39:53 +00:00
Muse 0022cd76e0 exp: fix Makefile mangled by a sed (ldpc_diag/pass2_diag recipes)
The previous commit's sed ate the $(CC)/$(CFLAGS) variables and
moved the ldpc_diag recipe under pass2_diag. Rewrote the Makefile
cleanly; all four binaries build.
2026-12-02 14:39:53 +00:00
Muse 40d4d996d6 exp: results write-up + pass-2 diagnostic (pass 2 rescues nothing)
README now carries the measured tables for all four families.
pass2_diag.c: targeted sweep of BCH pass-2 recovery. Finding: the
repo's own bch_test reports t+1 recovered 0/100, t+2 0/100; this
harness's pass-2 matrix shows rescued=0 in every setting; the
targeted sweep (m=13 t=16, k=t+1..t+8) rescues 0/50 at every k.
Pass 2's demonstrated value is the loud-failure guarantee (0
silent miscorrections), not recovery -- its residual-BM mechanism
addresses pass-1 miscorrection, which essentially never happens
for random errors. Relevant to the sibling deep-repair job.
2026-12-02 14:39:53 +00:00
Muse acedd368df exp: interleave groups merge the short tail (no weak tail group)
A burst landing in the final partial group (4 blocks of a 68-block
blob) hit each of its blocks with L/4 bytes instead of L/64 -- that
is why 64 B bursts measured 0.94 instead of 1.00. Groups are now
formed so the last partial group is absorbed into the previous one
(every group >= depth). Re-measured, 50 trials: d16/d32/d64-t32 at
64 B bursts 1.00 (was 0.94); d64-t32 at 256 B and 64x4 bursts 1.00
(was 0.95 / 0.83).
2026-12-02 14:39:53 +00:00
Muse 8d268167f8 exp: regular LDPC codec, PEG construction + min-sum BP (family 2)
n=8192, column weight 3; r90 (m=768, rate 0.906) and r95 (m=384,
rate 0.953). PEG construction (the greedy 4-cycle-rejection builder
deadlocked in the endgame -- replaced, see comment). Systematic
encoding via Gauss-Jordan; normalized min-sum (0.8), 50 iters.
Single-block diagnostics (ldpc_diag): r90 clean to 37 errors/block,
first failures ~38-40; r95 starts failing at 6 errors/block -- the
high-rate regular (3,64) code is genuinely weak, an honest negative
for naive regular LDPC at rate 0.95. Clean round-trips bit-identical.
2026-12-02 14:39:53 +00:00
Muse 5c65f3cd89 exp: byte interleaver over small-block BCH (family 1)
Zero extra parity: groups of D blocks are read column-wise, so a
burst of L bytes hits any one block with at most ceil(L/D) bytes
instead of killing a block outright. Random-error performance is
unchanged by construction (same BCH underneath); burst tolerance
improves ~Dx. Smoke test on text.lz: d64-t32 survives 256 B bursts
at 0.95 (plain bch1k-t32: 0.00), clean round-trips bit-identical,
overhead identical to bch1k-t32 (5.40%).
2026-12-02 14:39:53 +00:00
Muse fe90ef37b2 exp: corruption-matrix harness + BCH baseline codecs
bench.c measures every ECC family the same way: encode a blob window,
corrupt the stored bytes (random bit flips at a BER, or randomized
byte bursts), decode, check exact recovery (memcmp + SHA-256).
bch_wrap.c wraps the shipped BCH two ways: as-shipped (auto-pick poly
for the whole blob) and forced 1 KiB blocks. Pass 2 is wired to
recover_verified; --nopass2 skips it for matrix speed.
Stubs for interleave/ldpc/polar/uep return NULL until implemented.
Corpora + results are generated, gitignored.
2026-12-02 14:39:53 +00:00
Muse 73e333f6f3 Baseline: full corruption matrix results + pass-2 analysis
200 trials/setting on slice1m (-6 -e 4, t=8, single block):
scattered bits <=8 recover 200/200, 9/16/32 recover 0/200;
bursts: 1B 200/200, 2B 117-135/200, >=4B 0/200; silent-bad 0/2800.
Pass 2 is wired in (entry_decode -> bch_decode_candidates) but
rescues nothing beyond t at this block size — the gap the
deep-repair work must close. Also: harness gains MATRIX_ONLY /
MATRIX_WORKDIR for concurrent runs; docs/BASELINE.md section 7
notes the blocked hot_chicago run.
2026-12-02 14:39:50 +00:00
Muse 911b3c998f Baseline: codebase survey, bench harness, corruption matrix, docs/BASELINE.md (matrix table TBD)
Survey + reproducible yardstick for the parallel ECC/compression
experiments: bench/bench.sh (ratio/speed/RSS), bench/corrupt_matrix.py
(200 trials/setting, scattered bits + bursts), docs/BASELINE.md with
the full codebase map, format summary, test results and the
enwik8/Silesia corpus checksums.
2026-12-02 14:39:50 +00:00
385 changed files with 4240 additions and 19373 deletions

No files matched your search

+7 -8
View File
@@ -20,11 +20,10 @@
/crc16_test
/lzply_deep_repair
/testwork-deep/
randfec/m2/dmg/
randfec/m2/*.lzply
randfec/m2/damage
randfec/m2/gilsim
randfec/m2/fit1.log
randfec/m2/fit2.log
randfec/m2/fit2b.log
randfec/m2/p3-driver.log
# compression experiments (integrated winners only; lzrans/bwt/ppm rejected)
/experiments/corpora/
/experiments/rans_tool
/experiments/dict
/experiments/bchcheck
/testwork-int/
/testwork-bench/
-97
View File
@@ -1,97 +0,0 @@
# CUDA Chase-1 (deep repair) — experiments/cuda-chase
GPU port of the Chase-1 scan (`bch_chase1_block`, bch.c) for the
`-e4` case (m=22, t=8): one CUDA thread per trial position runs
Berlekamp-Massey + the lambda-splits test; a second kernel runs the
Chien search in parallel for the few survivors; the host verifies
each by the syndrome-zero check. Candidate order and counts match
the CPU exactly.
## Files
- `chase_cuda.h` / `chase_cuda.cu` — the CUDA implementation
(`chase_cuda_scan1`, `chase_cuda_available`). Only t=8 is
implemented; other t values return -2.
- `chase_bench.c` — benchmark harness: builds one 524,265-byte
block, flips N bits (default 9, seed 12345), checks the standard
decode fails, then times `--cpu` (`bch_chase1_block`) or `--cuda`
(`chase_cuda_scan1`) and prints trials / split_pass / codewords /
candidates / seconds / trials/s / a hash of the candidate set in
order / whether the original is among the candidates.
- `bch_block_syndrome()` (bch.c/bch.h) — new public accessor for
the syndrome S_1..S_2t of a received word (thin wrapper around the
existing static `compute_syndrome`). Returns 0 with S filled,
1 if the remainder is zero (clean word), -1 on bad input.
## Why the GPU version is exactly equivalent
1. **Splits test.** The CPU test is gcd(lambda, x^(2^m)-x) of
degree L. x^(2^m)-x is squarefree, so that gcd has degree L iff
lambda divides x^(2^m)-x iff x^(2^m) mod lambda == x. The kernel
computes h = x^(2^m) mod lambda by m repeated squarings and
passes iff h == x — no gcd at all. L <= 1 always splits,
matching the CPU.
2. **BM early exit.** BM's L is non-decreasing, so a trial whose L
exceeds t at any point is doomed; the kernel exits early and
never writes C beyond index t. Exactly equivalent: any such
write would only raise the degree past t (deg(C) after an
update equals the new L).
3. **Verification.** The corrected word's syndrome is
S ^ col(trial) ^ XOR col(root), and syndrome zero iff remainder
zero: the syndrome's roots close under conjugation to the
generator, so a degree-<r binary remainder with all 2t syndrome
roots is 0. The host checks this with the host exp table
(no per-candidate decode needed).
4. **Order.** The kernel's atomic-append order is nondeterministic,
so the host sorts survivors by position ascending before
verification; candidate order then reproduces the CPU's
(suspects first in order, then ascending).
## Measured (hot_house, RTX 3080 Ti, Dec 3 2026)
One 524,265-byte block, m=22, t=8, 9 errors, 4,194,296 trials.
| case | CPU | CUDA | hash |
|---|---|---|---|
| seed 12345, 9 errors | 171.571 s (24,446 trials/s) | 0.335–0.379 s (11.1–12.5M trials/s) | 0xca5f43bdeb9d8c96 (both) |
| seed 999, 10 errors | 158.573 s (26,450 trials/s) | 0.328 s (12.8M trials/s) | 0x5003477cf2b5970d (both) |
- seed 12345: trials 4,194,296, split_pass 135, codewords 135,
candidates 15, original among candidates YES (both).
- seed 999 (10 errors): split_pass 72, codewords 72, candidates 8,
original NO on both — Chase-1 cannot fix t+2 errors (one trial
flip leaves 9 > t=8); the 8 candidates are other codewords.
That is the algorithm's limit, not an implementation difference.
- Seeds 2/3/4 (suspect-path cases, 6/6/9 suspects) validated
against the CPU the same way (hash match) — see
/root/chase-cpu-seed{2,3,4}.log and the CUDA runs.
Speedup on the timed scan: **171.571 / 0.335 ≈ 512×** (worst
repeat 171.571 / 0.379 ≈ 453×). End-to-end wall clock including
process start + CUDA context init: ~0.9 s vs ~172 s (~190×).
## Build
```
# CPU-only bench
gcc -O2 -Wall -Wextra -o chase_bench_cpu chase_bench.c bch.c
# CUDA bench (nvcc pattern from the cuda-bch job)
/usr/local/cuda/bin/nvcc -O3 -arch=sm_86 -Xcompiler -O2 -c -o chase_cuda.o chase_cuda.cu
gcc -O2 -Wall -Wextra -DHAVE_CUDA -c -o chase_bench.o chase_bench.c
gcc -O2 -Wall -Wextra -c -o bch.o bch.c
/usr/local/cuda/bin/nvcc -arch=sm_86 -o chase_bench_cuda chase_bench.o bch.o chase_cuda.o
```
## Limits / not done
- t=8 only. Other t values need a template instantiation per t
(the kernel is written with CT=8; the BM/splits code is
t-generic in structure).
- Chase-2 is not ported (pair scan; the same per-trial kernel
applies, but the pair enumeration and candidate ordering need
their own pass).
- Counts are full-scan counts: if max_cands is hit, the CPU stops
the scan early (partial stats) while the GPU runs the whole scan
and then truncates. The candidate set still matches (first
max_cands in CPU order). Not an issue for the benchmark
(15 < 64 candidates).
+23 -47
View File
@@ -3,17 +3,6 @@ CFLAGS = -O2 -Wall -Wextra
LDLIBS = -llz
PREFIX = /usr/local
# CUDA Chase-1 (optional): nvcc lives here on hot_house (not on PATH
# by default). When it exists, chase_cuda.o is built and linked into
# lzply and lzply_deep_repair; otherwise deep_repair.c falls back to
# the CPU Chase via its weak references and the build is unchanged.
NVCC ?= /usr/local/cuda/bin/nvcc
NVCCFLAGS = -O3 -arch=sm_86 -Xcompiler -O2
CHASE_CUDA_OBJ =
ifneq ($(wildcard $(NVCC)),)
CHASE_CUDA_OBJ = chase_cuda.o
endif
all: lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyper lz_rs lzply_deep_repair
# Shared core: the v5 archive format, the per-entry pipeline
@@ -33,15 +22,11 @@ sha256.o: sha256.c sha256.h
bch.o: bch.c bch.h bch_polys.h
$(CC) $(CFLAGS) -c -o $@ bch.c
lzply.o: lzply.c lzply_lib.h bch.h bch_polys.h deep_repair.h repair_cmd.h
lzply.o: lzply.c lzply_lib.h bch.h bch_polys.h
$(CC) $(CFLAGS) -c -o $@ lzply.c
lzply: lzply.o deep_repair.o repair_cmd.o liblzrs.a liblzply.a $(CHASE_CUDA_OBJ)
ifeq ($(CHASE_CUDA_OBJ),)
$(CC) $(CFLAGS) -o $@ lzply.o deep_repair.o repair_cmd.o liblzrs.a liblzply.a $(LDLIBS)
else
$(NVCC) -arch=sm_86 -o $@ lzply.o deep_repair.o repair_cmd.o liblzrs.a liblzply.a $(CHASE_CUDA_OBJ) $(LDLIBS)
endif
lzply: lzply.o liblzply.a
$(CC) $(CFLAGS) -o $@ lzply.o liblzply.a $(LDLIBS)
# FUSE filesystem. Needs libfuse3-dev; no pkg-config on the server, so
# the flags are explicit (-D_FILE_OFFSET_BITS=64 is required by FUSE).
@@ -102,23 +87,6 @@ lzply_hyper: lzply_hyper.o bch.o sha256.o
bch_test: bch.c bch_test.c bch.h bch_polys.h
$(CC) $(CFLAGS) -o $@ bch.c bch_test.c
# CUDA Chase-1 bench (experiments/cuda-chase): GPU port of the
# deep-repair Chase-1 scan (t=8 only). Needs CUDA 13.x; NVCC is
# /usr/local/cuda/bin/nvcc on hot_house (not on PATH by default).
# NVCC / NVCCFLAGS are defined at the top of this file.
chase_bench_cpu: chase_bench.c bch.c bch.h bch_polys.h
$(CC) $(CFLAGS) -o $@ chase_bench.c bch.c
chase_bench.o: chase_bench.c bch.h chase_cuda.h
$(CC) $(CFLAGS) -DHAVE_CUDA -c -o $@ chase_bench.c
chase_cuda.o: chase_cuda.cu chase_cuda.h bch.h bch_polys.h
$(NVCC) $(NVCCFLAGS) -c -o $@ chase_cuda.cu
chase_bench_cuda: chase_bench.o bch.o chase_cuda.o
$(NVCC) -arch=sm_86 -o $@ chase_bench.o bch.o chase_cuda.o
# Reed-Solomon codec (rs.c) and the LZRS v1 archive layer
# (lzrs_lib.c: LZRS entry encode/decode + header I/O + scan).
# lz_rs links both plus the shared v4 core (liblzply.a).
@@ -151,18 +119,11 @@ crc16_test: crc16_test.c liblzply.a
deep_repair.o: deep_repair.c deep_repair.h lzply_lib.h lzrs_lib.h bch.h rs.h sha256.h
$(CC) $(CFLAGS) -c -o $@ deep_repair.c
lzply_deep_repair.o: lzply_deep_repair.c deep_repair.h lzply_lib.h lzrs_lib.h bch.h repair_cmd.h
lzply_deep_repair.o: lzply_deep_repair.c deep_repair.h lzply_lib.h lzrs_lib.h bch.h
$(CC) $(CFLAGS) -c -o $@ lzply_deep_repair.c
repair_cmd.o: repair_cmd.c repair_cmd.h deep_repair.h lzply_lib.h lzrs_lib.h bch.h
$(CC) $(CFLAGS) -c -o $@ repair_cmd.c
lzply_deep_repair: lzply_deep_repair.o repair_cmd.o deep_repair.o liblzrs.a liblzply.a $(CHASE_CUDA_OBJ)
ifeq ($(CHASE_CUDA_OBJ),)
$(CC) $(CFLAGS) -o $@ lzply_deep_repair.o repair_cmd.o deep_repair.o liblzrs.a liblzply.a $(LDLIBS)
else
$(NVCC) -arch=sm_86 -o $@ lzply_deep_repair.o repair_cmd.o deep_repair.o liblzrs.a liblzply.a $(CHASE_CUDA_OBJ) $(LDLIBS)
endif
lzply_deep_repair: lzply_deep_repair.o deep_repair.o liblzrs.a liblzply.a
$(CC) $(CFLAGS) -o $@ lzply_deep_repair.o deep_repair.o liblzrs.a liblzply.a $(LDLIBS)
# bch_polys.h is generated by gen_bch_polys.py from the rssearch data
# (~/workspace/rssearch/polys.txt + finds.txt) and checked in; it is
@@ -208,6 +169,21 @@ test: testdata bch_test rs_test crc16_test lzply lzply_mount lzply_stat lzply_he
elif [ -x ../tests/run_hyper_tests.sh ]; then \
../tests/run_hyper_tests.sh ./lzply_hyper; \
else echo "run_hyper_tests.sh not found"; exit 1; fi
if [ -x ./tests/run_integration_tests.sh ]; then \
./tests/run_integration_tests.sh; \
elif [ -x ../tests/run_integration_tests.sh ]; then \
../tests/run_integration_tests.sh; \
else echo "run_integration_tests.sh not found"; exit 1; fi
# Integrated experiment winners (docs/INTEGRATION.md): the ECC harness
# (interleave d64, small-block BCH, LDPC r90) and the compression
# prototypes (rANS core, dict transform). Not part of `all`: the archive
# format is unchanged (LZPL v5); these are standalone tools.
exp:
$(MAKE) -C exp bench ldpc_diag pass2_diag
experiments:
$(MAKE) -C experiments
install: lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyper lz_rs lzply_deep_repair
mkdir -p $(PREFIX)/bin
@@ -223,6 +199,6 @@ install: lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply
install -m 755 mount.lzply /sbin/mount.lzply
clean:
rm -f lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyper lz_rs lzply_deep_repair bch_test rs_test crc16_test chase_bench_cpu chase_bench_cuda *.o liblzply.a liblzrs.a
rm -f lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyper lz_rs lzply_deep_repair bch_test rs_test crc16_test *.o liblzply.a liblzrs.a
.PHONY: all test install clean
.PHONY: all test install clean exp experiments
+31 -19
View File
@@ -191,8 +191,7 @@ is the only LZRS format.
## Deep repair — past the BCH limit
`lzply_deep_repair` -- also built into the main tool as `lzply -r` --
recovers entries whose bit errors exceed the
`lzply_deep_repair` recovers entries whose bit errors exceed the
BCH correction limit t, in escalating levels, reporting per-level
timing ("time of arrival": how long each level took and at which
level the repair landed):
@@ -228,9 +227,7 @@ CRC-checked, 1,024 rejected by CRC, 0 false accepts.
Limits, measured honestly: Chase scans are O(nbits) trials at
~7,800 trials/s on m=22 blocks (a full scan of a 524 KiB block
takes ~9 minutes on the CPU; ~0.35 s on a CUDA build -- the L1
scan runs on the GPU when a device is present, with CPU fallback),
so beyond-t repair of large blocks is bounded
takes ~9 minutes), so beyond-t repair of large blocks is bounded
by the time budget (default 120 s per entry) and reports partial
coverage rather than pretending. Two bugs found by measurement
and fixed: the trial flip was not applied to the reconstructed
@@ -239,9 +236,7 @@ candidates before trying them, truncating the list before the
genuine candidate arrived (a 600 KiB file with 9 errors in one
block failed at a 60 s budget before the fix; it recovers after
it). Full design, bounds, and measured numbers:
`docs/deep-repair.md`. CUDA Chase write-up:
https://www.lzply.com/cuda-chase-500x-deep-repair/ . Tests:
`tests/run_deep_repair_tests.sh`
`docs/deep-repair.md`. Tests: `tests/run_deep_repair_tests.sh`
(round-trips, old-format rejection, corruption matrix,
false-accept measurement).
@@ -443,6 +438,34 @@ Set `LZPLY_TEST_ROOT` to point the suite at a different tree root
(default: the parent of the `tests/` directory, so it works both
from the repo layout `~/workspace/lzply` and from `/opt/lzply/src`).
## Integrated experiments — interleaving, small-block BCH, LDPC, dict
The open-ended research branches (`experiments/baseline`,
`experiments/ecc`, `experiments/comp`) were merged onto current main
on `experiments/integration`. Four winners, measured numbers only,
full write-up in `docs/INTEGRATION.md`:
* **Byte interleaving d64 over small-block BCH** (`exp/`): zero extra
parity; a 256 B burst that kills uninterleaved BCH (0.00 recovery)
is recovered 1.00. Same 5.40% overhead as the BCH underneath.
* **Small-block BCH, 1 KiB blocks** (`exp/`): `bch1k-t32` survives
BER 1e-3 at 1.00 where as-shipped `bch-t32` scores 0.00, at 5.40%
overhead vs 0.12%.
* **Regular LDPC r90** (`exp/`): 1.00 at BER 1e-3, 0.97 at 3e-3
where `bch1k-t32` scores 0.01; 10.94% overhead, ~4x slower decode.
* **Dictionary transform, code-only** (`experiments/`): -2.1% vs
plain lzip -6 on code; worse everywhere else, so opt-in only.
The rANS core is kept as supporting infrastructure.
Rejected with numbers (code not carried over): polar SC (0.00 at
BER 1e-3), UEP (whole-file recovery dominated by the weak tier),
LZ77+rANS, BWT, and PPM order-2 — none beats lzip on ratio.
The archive format is unchanged (LZPL v5); the winners are
standalone tools, built with `make exp` / `make experiments` and
smoke-tested by `tests/run_integration_tests.sh` as part of
`make test`.
## Limitations (v5)
* Whole files are buffered in memory (compress, BCH, and
@@ -725,14 +748,3 @@ Full documentation — config format, commands (`-init`, `write`,
`read`, `list`, `check`, `-rebuild`), the parity scheme, the
1/2/3-stripe-loss demos, and the 56-test suite — is in
`README-hyper.md`.
## Random FEC search (experiments/randfec)
`randfec/` hunts for random equations with FEC-like properties
(random CRC polynomials, ROT/XOR mixes, 2D/3D product codes,
nonlinear CRC hybrids), scored on d_min / burst length / cost
against CRC-16, shortened BCH, and RS. Full report:
`randfec/RANDFEC.md`. Headline: random CRC polynomials beat
shortened BCH at n<=32 and at n=64 when searched at the target
size; ROT/XOR, product, and nonlinear families do not. Research
only — nothing integrated into lzply core.
-22
View File
@@ -1290,28 +1290,6 @@ static int compute_syndrome(const uint8_t *in, size_t in_len, size_t data_len,
return 0;
}
/* Public syndrome accessor, for the CUDA Chase scan (and any other
* caller that needs S without a full decode). Same return codes as
* compute_syndrome: 0 with S filled, 1 if the remainder is zero
* (clean word), -1 on bad input. */
int bch_block_syndrome(const uint8_t *in, size_t in_len, size_t data_len,
const bch_poly_t *p, uint32_t *S)
{
if (!in || !p || !S)
return -1;
bch_ctx_t *ctx = bch_ctx_new(p);
if (!ctx)
return -1;
const gf_tables_t *tab = gf_tables_for(p->m);
if (!tab) {
bch_ctx_free(ctx);
return -1;
}
int rc = compute_syndrome(in, in_len, data_len, p, ctx, tab, S);
bch_ctx_free(ctx);
return rc;
}
/* Column of the parity-check matrix for bit position pos:
* col_j = alpha^(j*(nbits-1-pos)), j = 1..2t. Fills col[0..2t-1]. */
static void col_at(size_t pos, size_t nbits, int t, const gf_tables_t *tab,
-6
View File
@@ -157,12 +157,6 @@ int bch_remainder_bruteforce(const uint8_t *data, size_t data_len,
/* weight-(t+2) pattern. The list is what buys the rate. */
/* ------------------------------------------------------------------ */
/* Syndrome S_1..S_2t of the received word (for the CUDA Chase scan).
* Returns 0 with S filled, 1 if the remainder is zero (clean word),
* -1 on bad input. S must hold 2*t uint32_t. */
int bch_block_syndrome(const uint8_t *in, size_t in_len, size_t data_len,
const bch_poly_t *p, uint32_t *S);
/* Maximum distinct candidate blocks returned per chase call. */
#define BCH_CHASE_MAX_CANDS 64
/* Maximum suspect positions considered by chase2. */
+88
View File
@@ -0,0 +1,88 @@
#!/bin/sh
# Benchmarks for the integrated winners vs plain lzply at b27b345.
# Runs on hot_newyork in the integrated checkout. The lzply core is
# untouched by the integration (binaries md5-identical to pristine
# b27b345), so the lzply numbers below ARE the plain-b27b345 numbers.
# Each timed measurement is best-of-3; sizes are exact.
# Output: stdout + results file $OUT.
set -u
ROOT=$PWD
W=$ROOT/testwork-bench
OUT=$W/bench-results.txt
mkdir -p "$W"
: > "$OUT"
say() { printf '%s\n' "$*" | tee -a "$OUT"; }
# t3 <label> <cmd...>: best-of-3 wall seconds
t3() {
label=$1; shift
best=""
for i in 1 2 3; do
s=$(date +%s.%N)
"$@" >/dev/null 2>&1
e=$(date +%s.%N)
d=$(awk -v s="$s" -v e="$e" 'BEGIN{printf "%.3f", e-s}')
if [ -z "$best" ] || [ "$(awk -v a="$d" -v b="$best" 'BEGIN{print (a<b)?1:0}')" = 1 ]; then best=$d; fi
done
say "$label best-of-3: ${best}s"
echo "$best"
}
say "== benchmark run $(date -u +%Y-%m-%dT%H:%M:%SZ) hot_newyork $(nproc) cores load: $(uptime | sed 's/.*average: //')"
say "== data set =="
# mixed set: repo docs (text) + repo C sources (code) + system binaries
mkdir -p "$W/mixed"
# Varied content only: repetition compresses to ~nothing under lzip.
find "$ROOT" -type f \( -name "*.md" -o -name "*.c" -o -name "*.h" -o -name "*.sh" -o -name "*.py" -o -name "*.txt" \) -not -path "$ROOT/testwork*" -not -path "$ROOT/.git/*" -not -path "$ROOT/testdata/*" -print0 2>/dev/null | sort -z | xargs -0 cat > "$W/mixed/text.txt"
find "$ROOT" -type f \( -name "*.c" -o -name "*.h" \) -not -path "$ROOT/testwork*" -not -path "$ROOT/.git/*" -print0 2>/dev/null | sort -z | xargs -0 cat > "$W/mixed/code.c"
cp /bin/ls /bin/cat /usr/bin/lzip "$W/mixed/" 2>/dev/null
head -c 1048576 /dev/urandom > "$W/rand1m.bin"
ls -l "$W/mixed" | tee -a "$OUT"
say "mixed dir bytes: $(du -sb "$W/mixed" | cut -f1); rand1m: 1048576"
lzip -6 -c "$W/mixed/text.txt" > "$W/text.lz"
lzip -6 -c "$W/mixed/code.c" > "$W/code.lz"
cat "$W/text.lz" "$W/code.lz" > "$W/mixed.lz"
say "lzip -6 blobs: text.lz $(stat -c%s "$W/text.lz"), code.lz $(stat -c%s "$W/code.lz"), mixed.lz $(stat -c%s "$W/mixed.lz")"
say ""
say "== plain lzply at b27b345 (integrated binary, md5 = pristine) =="
"$ROOT/lzply" -c -y -6 "$W/mixed" "$W/mixed.lzply" >/dev/null 2>&1
say "lzply -c -6 mixed: $(stat -c%s "$W/mixed.lzply") bytes"
t3 "lzply -c -6 mixed" "$ROOT/lzply" -c -y -6 "$W/mixed" "$W/mixed.lzply" > /dev/null
mkdir -p "$W/mixed-out"
t3 "lzply -d mixed" "$ROOT/lzply" -d -y "$W/mixed.lzply" "$W/mixed-out" > /dev/null
"$ROOT/lzply" -c -y -6 -e 0 "$W/mixed" "$W/mixed-e0.lzply" >/dev/null 2>&1
say "lzply -c -6 -e 0 mixed: $(stat -c%s "$W/mixed-e0.lzply") bytes (no BCH)"
"$ROOT/lzply" -c -y -6 "$W/rand1m.bin" "$W/rand.lzply" >/dev/null 2>&1
say "lzply -c -6 rand1m: $(stat -c%s "$W/rand.lzply") bytes (stored, level 0 expected)"
t3 "lzply -c -6 rand1m" "$ROOT/lzply" -c -y -6 "$W/rand1m.bin" "$W/rand.lzply" > /dev/null
t3 "lzply -d rand1m" "$ROOT/lzply" -d -y "$W/rand.lzply" "$W/rand-out" > /dev/null
say ""
say "== exp bench --speed, 64 KiB windows, mixed.lz blob =="
for c in bch-t32 bch1k-t32 intlv-d64-bch1k-t32 ldpc-r90; do
"$ROOT/exp/bench" --codec "$c" --blob "$W/mixed.lz" --size 65536 --speed --out "$W/speed-$c.csv" 2>&1 | sed 's/^/ /' | tee -a "$OUT"
done
say "CSV (codec,corpus,win,trials,mode,param,success,rescued,rate,enc_MBps,dec_MBps,rss_kb,ovh_pct):"
cat "$W"/speed-*.csv | tee -a "$OUT"
say ""
say "== exp bench: recovery on the mixed blob (20 trials) =="
"$ROOT/exp/bench" --codec intlv-d64-bch1k-t32 --blob "$W/mixed.lz" --size 65536 --trials 20 --burst 256,1 --out "$W/mixed-intlv-burst.csv" 2>&1 | sed 's/^/ /' | tee -a "$OUT"
"$ROOT/exp/bench" --codec bch1k-t32 --blob "$W/mixed.lz" --size 65536 --trials 20 --ber 1e-3 --out "$W/mixed-bch1k-ber.csv" 2>&1 | sed 's/^/ /' | tee -a "$OUT"
"$ROOT/exp/bench" --codec ldpc-r90 --blob "$W/mixed.lz" --size 65536 --trials 10 --ber 1e-3 --out "$W/mixed-ldpc-ber.csv" 2>&1 | sed 's/^/ /' | tee -a "$OUT"
say ""
say "== dict transform vs plain lzip -6 (sizes, bytes) =="
for f in text code; do
if [ "$f" = text ]; then SRC="$W/mixed/text.txt"; else SRC="$W/mixed/code.c"; fi
lzip -6 -c "$SRC" > "$W/$f.plain.lz"
"$ROOT/experiments/dict" c "$SRC" "$W/$f.dict" && lzip -6 -k -f "$W/$f.dict"
say "$f: plain lzip6 $(stat -c%s "$W/$f.plain.lz") vs dict+lzip6 $(stat -c%s "$W/$f.dict.lz")"
done
say ""
say "== rANS order-0 (infrastructure context) =="
"$ROOT/experiments/rans_tool" c "$W/mixed/text.txt" "$W/text.rans"
say "text: plain $(stat -c%s "$W/mixed/text.txt") -> rANS order-0 $(stat -c%s "$W/text.rans")"
t3 "rans_tool c text" "$ROOT/experiments/rans_tool" c "$W/mixed/text.txt" "$W/text.rans" > /dev/null
t3 "rans_tool d text" "$ROOT/experiments/rans_tool" d "$W/text.rans" "$W/text.rans.out" > /dev/null
say "== done =="
Executable
+43
View File
@@ -0,0 +1,43 @@
#!/bin/bash
# Baseline ratio / speed / memory benchmark for lzply (experiments/baseline).
# Usage: bench.sh <lzply-binary> <corpus-dir> <work-dir>
# Corpus dir: enwik8 + silesia files (see docs/BASELINE.md for checksums).
# Each setting: encode once, decode once, timed with /usr/bin/time -v
# (max RSS), sizes from stat. Clean round-trips verified bit-identical
# with diff -r (any mismatch is reported in the roundtrip field).
set -u
LZPLY="$1"; CORPUS="$2"; WORK="$3"
mkdir -p "$WORK"
cd "$WORK" || exit 1
( cd "$CORPUS" && sha256sum enwik8 dickens mozilla mr nci ooffice osdb reymont samba sao webster x-ray xml > "$WORK/corpus.sha256" )
echo "corpus total bytes: $(du -sb "$CORPUS" | cut -f1)"
run_one() { # run_one <label> <input-path> <lzply -c flags...>
local label="$1" input="$2"; shift 2
local arc="$WORK/$label.lzply" out="$WORK/$label.out"
rm -rf "$arc" "$out"
/usr/bin/time -v "$LZPLY" -c "$@" "$input" "$arc" > "$WORK/$label.enc.log" 2> "$WORK/$label.enc.time"
local enc_rc=$?
local enc_wall=$(grep "Elapsed (wall clock)" "$WORK/$label.enc.time" | awk '{print $NF}')
local enc_rss=$(grep "Maximum resident" "$WORK/$label.enc.time" | awk '{print $NF}')
local arc_size=$(stat -c%s "$arc" 2>/dev/null || echo 0)
/usr/bin/time -v "$LZPLY" -d -y "$arc" "$out" > "$WORK/$label.dec.log" 2> "$WORK/$label.dec.time"
local dec_rc=$?
local dec_wall=$(grep "Elapsed (wall clock)" "$WORK/$label.dec.time" | awk '{print $NF}')
local dec_rss=$(grep "Maximum resident" "$WORK/$label.dec.time" | awk '{print $NF}')
local rt="?"
if [ $dec_rc -eq 0 ]; then
if diff -r -q "$input" "$out/$(basename "$input")" > /dev/null 2>&1; then rt="IDENTICAL"; else rt="MISMATCH"; fi
else rt="DECODE-FAILED"; fi
echo "$label enc_rc=$enc_rc enc_wall=$enc_wall enc_maxrss_kb=$enc_rss arc_bytes=$arc_size dec_rc=$dec_rc dec_wall=$dec_wall dec_maxrss_kb=$dec_rss roundtrip=$rt"
}
run_one enwik8-l1 "$CORPUS/enwik8" -1 -e 4
run_one enwik8-l6 "$CORPUS/enwik8" -6 -e 4
run_one enwik8-l9 "$CORPUS/enwik8" -9 -e 4
run_one corpus-l6e4 "$CORPUS" -6 -e 4
run_one corpus-l6e0 "$CORPUS" -6 -e 0
run_one corpus-l6e7 "$CORPUS" -6 -e 7
run_one mozilla-l6 "$CORPUS/mozilla" -6 -e 4
echo DONE
+104
View File
@@ -0,0 +1,104 @@
#!/usr/bin/env python3
"""Corruption-matrix harness for lzply baseline (experiments/baseline).
Builds a single-entry archive of a 1 MiB text slice (default -6 -e 4),
then for each setting runs N trials: copy the archive, corrupt ONLY the
stored-data region (headers untouched), run `lzply -t`, and on success
also extract + verify SHA-256 of the recovered file. Reports
recovered / failed-loud / silent-bad counts per setting.
Settings:
scattered N bits: N in {1,2,4,8,9,16,32} random distinct bit positions
burst L bytes: L in {1,2,4,8,16} consecutive bytes replaced with
random bytes at a random offset (up to 8*L bit errors)
Usage: corrupt_matrix.py <lzply> <archive> <trials> [seed]
Archive must have exactly one file entry; data offset is parsed from
the v4 headers (global 16 + entry 78 + path_len).
Env: MATRIX_WORKDIR (default /tmp/lzply-matrix), MATRIX_ONLY
(comma list of kinds to run, default "bits,burst") — used to run
the burst settings as a second concurrent process with its own
workdir and seed while the bits run continues.
"""
import hashlib
import os
import random
import shutil
import struct
import subprocess
import sys
LZPLY, ARCHIVE, TRIALS = sys.argv[1], sys.argv[2], int(sys.argv[3])
SEED = int(sys.argv[4]) if len(sys.argv) > 4 else 20261202
with open(ARCHIVE, "rb") as f:
raw = f.read()
assert raw[:4] == b"LZPL", "not an LZPL archive"
assert raw[4] == 4, "not v4"
path_len = struct.unpack_from("<H", raw, 16)[0]
data_off = 16 + 78 + path_len
# entry header (78 bytes from offset 16): path_len u16, level/rs_level/
# flags/reserved u8 x4, orig_size u64 @22, stored_size u64 @30,
# blob_size u64 @38, sha256[32] @46, mode u32, mtime u64, header_crc32 u32
orig_size, stored_size, blob_size = struct.unpack_from("<QQQ", raw, 22)
sha = raw[46:78].hex()
print("archive: %s data_off=%d stored=%d blob=%d orig=%d sha256=%s..."
% (ARCHIVE, data_off, stored_size, blob_size, orig_size, sha[:16]),
flush=True)
data_end = data_off + stored_size
assert data_end <= len(raw), "stored data overruns file"
work = os.environ.get("MATRIX_WORKDIR", "/tmp/lzply-matrix")
shutil.rmtree(work, ignore_errors=True)
os.makedirs(work)
def trial(rng, kind, n):
p = os.path.join(work, "t.lzply")
buf = bytearray(raw)
if kind == "bits":
positions = rng.sample(range(data_off * 8, data_end * 8), n)
for pos in positions:
buf[pos // 8] ^= 1 << (pos % 8)
else: # burst: n consecutive bytes -> random bytes
start = rng.randrange(data_off, data_end - n + 1)
for i in range(n):
buf[start + i] = rng.randrange(256)
with open(p, "wb") as f:
f.write(buf)
r = subprocess.run([LZPLY, "-t", p], capture_output=True)
if r.returncode != 0:
return "failed-loud"
# -t passed: extract and verify content hash to catch silent damage
outdir = os.path.join(work, "out")
shutil.rmtree(outdir, ignore_errors=True)
r2 = subprocess.run([LZPLY, "-d", "-y", p, outdir],
capture_output=True)
if r2.returncode != 0:
return "failed-loud"
got = None
for root, _, files in os.walk(outdir):
for fn in files:
with open(os.path.join(root, fn), "rb") as f:
got = hashlib.sha256(f.read()).hexdigest()
return "recovered" if got == sha else "SILENT-BAD"
rng = random.Random(SEED)
results = {}
only = os.environ.get("MATRIX_ONLY", "bits,burst").split(",")
for kind, sizes in (("bits", [1, 2, 4, 8, 9, 16, 32]),
("burst", [1, 2, 4, 8, 16])):
if kind not in only:
continue
for n in sizes:
counts = {"recovered": 0, "failed-loud": 0, "SILENT-BAD": 0}
for _ in range(TRIALS):
counts[trial(rng, kind, n)] += 1
results[(kind, n)] = counts
print("%-5s n=%-3d: recovered %3d/%d failed-loud %3d silent-bad %d"
% (kind, n, counts["recovered"], TRIALS,
counts["failed-loud"], counts["SILENT-BAD"]), flush=True)
bad = sum(c["SILENT-BAD"] for c in results.values())
print("TOTAL silent-bad: %d (must be 0)" % bad)
sys.exit(1 if bad else 0)
-181
View File
@@ -1,181 +0,0 @@
/* chase_bench.c - CPU vs CUDA Chase-1 benchmark for deep repair.
*
* Reproduces the GPU-day baseline: Chase-1 exhaustive scan of one
* 524265-byte BCH block (m=22, t=8, -e4), 9 errors, nbits=4,194,296
* trials, ~181 s single-core (~23,200 trials/s).
*
* Usage: chase_bench --cpu | --cuda [--nerr N] [--seed S]
* --cpu : time bch_chase1_block (CPU reference)
* --cuda : time the CUDA Chase-1 scan (chase_cuda.cu)
* Prints: trials, split_pass, codewords, candidates, seconds,
* trials/s, and whether the original data is among the candidates.
* Exit 0 iff the original data is among the candidates.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <time.h>
#include "bch.h"
#ifdef HAVE_CUDA
#include "chase_cuda.h"
#endif
#define DFLT_D 524265
#define DFLT_T 8
#define DFLT_NERR 9
static uint64_t rng_state;
static uint64_t xr(void)
{
uint64_t x = rng_state;
x ^= x >> 12;
x ^= x << 25;
x ^= x >> 27;
rng_state = x;
return x * 0x2545F4914F6CDD1DULL;
}
static double now_s(void)
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return ts.tv_sec + ts.tv_nsec * 1e-9;
}
static void flip_bit(uint8_t *buf, size_t pos)
{
buf[pos >> 3] ^= (uint8_t)(1u << (7 - (pos & 7)));
}
/* FNV-1a hash over the candidate set, in order, for CPU/CUDA comparison. */
static uint64_t cands_hash(const uint8_t *cands, int nc, size_t D)
{
uint64_t h = 0xcbf29ce484222325ULL;
for (int i = 0; i < nc; i++) {
const uint8_t *c = cands + (size_t)i * D;
for (size_t j = 0; j < D; j++) {
h ^= c[j];
h *= 0x100000001b3ULL;
}
}
return h;
}
int main(int argc, char **argv)
{
int use_cuda = 0;
int nerr = DFLT_NERR;
uint64_t seed = 12345;
for (int i = 1; i < argc; i++) {
if (!strcmp(argv[i], "--cuda"))
use_cuda = 1;
else if (!strcmp(argv[i], "--cpu"))
use_cuda = 0;
else if (!strcmp(argv[i], "--nerr") && i + 1 < argc)
nerr = atoi(argv[++i]);
else if (!strcmp(argv[i], "--seed") && i + 1 < argc)
seed = strtoull(argv[++i], NULL, 10);
else {
fprintf(stderr, "usage: %s [--cpu|--cuda] [--nerr N] [--seed S]\n",
argv[0]);
return 2;
}
}
size_t D = DFLT_D;
int t = DFLT_T;
const bch_poly_t *p = bch_poly_for_data(D, t);
if (!p) {
fprintf(stderr, "no poly for D=%zu t=%d\n", D, t);
return 1;
}
size_t slen = bch_block_stored_len(D, p);
size_t nbits = (size_t)8 * D + (size_t)p->r;
printf("poly: m=%d t=%d r=%d id=%04x D=%zu stored=%zu nbits=%zu\n",
p->m, p->t, p->r, p->id, D, slen, nbits);
fflush(stdout);
uint8_t *data = malloc(D), *enc = malloc(slen), *dec = malloc(D);
uint8_t *cands = malloc((size_t)BCH_CHASE_MAX_CANDS * D);
if (!data || !enc || !dec || !cands)
return 1;
rng_state = seed;
for (size_t i = 0; i < D; i++)
data[i] = (uint8_t)xr();
if (bch_encode_block(data, D, p, enc) != 0) {
fprintf(stderr, "encode failed\n");
return 1;
}
/* flip nerr distinct bit positions, deterministic */
rng_state = seed ^ 0x9e3779b97f4a7c15ULL;
size_t *errpos = malloc(sizeof(size_t) * (size_t)nerr);
for (int i = 0; i < nerr; i++) {
size_t pos;
int dup;
do {
pos = (size_t)(xr() % nbits);
dup = 0;
for (int j = 0; j < i; j++)
if (errpos[j] == pos)
dup = 1;
} while (dup);
errpos[i] = pos;
flip_bit(enc, pos);
}
printf("flipped %d bits at:", nerr);
for (int i = 0; i < nerr; i++)
printf(" %zu", errpos[i]);
printf("\n");
fflush(stdout);
/* control: standard decode must fail */
if (bch_decode_block(enc, slen, D, p, dec, NULL) == 0) {
fprintf(stderr,
"control FAILED: standard decode succeeded on %d-error word\n",
nerr);
return 1;
}
printf("control: standard decode fails as expected\n");
fflush(stdout);
size_t *susp = malloc(sizeof(size_t) * BCH_CHASE_MAX_SUSPECTS);
int ns = bch_suspect_positions(enc, slen, D, p, susp, BCH_CHASE_MAX_SUSPECTS);
printf("suspects: %d\n", ns);
fflush(stdout);
double t0 = now_s();
long trials = 0, split_pass = 0, codewords = 0;
int nc = 0;
if (!use_cuda) {
bch_chase_stats_t cs;
nc = bch_chase1_block(enc, slen, D, p, cands, BCH_CHASE_MAX_CANDS,
susp, ns, &cs, -1);
trials = cs.trials;
split_pass = cs.split_pass;
codewords = cs.codewords;
printf("cpu: nc=%d partial=%d\n", nc, cs.partial);
} else {
#ifdef HAVE_CUDA
nc = chase_cuda_scan1(enc, slen, D, p, cands, BCH_CHASE_MAX_CANDS,
susp, ns, &trials, &split_pass, &codewords);
printf("cuda: nc=%d\n", nc);
#else
fprintf(stderr, "built without CUDA support\n");
return 1;
#endif
}
double dt = now_s() - t0;
if (nc < 0) {
fprintf(stderr, "scan failed\n");
return 1;
}
printf("trials=%ld split_pass=%ld codewords=%ld candidates=%d\n",
trials, split_pass, codewords, nc);
printf("time=%.3f s rate=%.0f trials/s\n", dt, trials / dt);
printf("cands_hash=0x%016llx\n",
(unsigned long long)cands_hash(cands, nc, D));
int found = 0;
for (int i = 0; i < nc; i++)
if (memcmp(cands + (size_t)i * D, data, D) == 0)
found = 1;
printf("original among candidates: %s\n", found ? "YES" : "NO");
return found ? 0 : 1;
}
-611
View File
@@ -1,611 +0,0 @@
/* chase_cuda.cu - CUDA Chase-1 scan for deep repair (t=8, -e4).
*
* GPU mirror of bch_chase1_block (bch.c). One thread per trial
* position runs Berlekamp-Massey + the lambda-splits test. Two
* facts make the GPU version exactly equivalent to the CPU:
*
* 1. The CPU splits test is gcd(lambda, x^(2^m)-x) of degree L.
* x^(2^m)-x is squarefree, so that gcd has degree L iff lambda
* divides x^(2^m)-x iff x^(2^m) mod lambda == x. The kernel
* therefore computes h = x^(2^m) mod lambda by m repeated
* squarings and passes iff h == x, with no gcd at all.
* L <= 1 always splits, matching the CPU.
* 2. BM's L is non-decreasing, so a trial whose L exceeds t at any
* point is doomed; the kernel exits early, and never writes C
* beyond index t. That is exactly equivalent: any such write
* would only raise the degree past t, and the final L would
* still exceed t (deg(C) after an update equals the new L).
*
* After the scan, a second kernel runs the Chien search in parallel
* for the (few) positions that passed: one thread per (position,
* codeword bit) evaluates lambda at that bit by Horner. The host
* then verifies each survivor by the syndrome-zero check: the
* syndrome of the corrected word is S ^ col(trial) ^
* XOR col(root), and syndrome zero iff remainder zero (the
* syndrome's roots close under conjugation to the generator, so a
* degree-<r binary remainder with all 2t syndrome roots is 0).
*
* GF arithmetic on the device is shift-and-XOR in registers (like
* gf_mul_slow); division uses log/exp tables (only ~12 divs per
* trial, and the BM early exit usually fires before many).
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <cuda_runtime.h>
extern "C" {
#include "bch.h"
}
#include "chase_cuda.h"
/* Only t=8 (-e4) is implemented: the benchmark case. */
#define CT 8
#define CT2 (2 * CT)
#define CHASE_CUDA_MAX_PASS 1048576u /* 1M passing positions (expect ~135) */
/* ---- GF(2^m) device helpers ---- */
/* Shift-and-XOR multiply (identical to gf_mul_slow in bch.c). */
__device__ __forceinline__ uint32_t cu_gf_mul(uint32_t a, uint32_t b, uint32_t P, int m)
{
uint32_t r = 0;
while (b) {
if (b & 1)
r ^= a;
b >>= 1;
a <<= 1;
if (a & (1u << m))
a ^= P;
}
return r;
}
/* Division via log/exp tables (identical to gf_div_tab; b != 0 by
* construction - a previous discrepancy). */
__device__ __forceinline__ uint32_t cu_gf_div_tab(uint32_t a, uint32_t b,
const uint32_t *d_log,
const uint32_t *d_exp,
uint32_t N)
{
if (!a)
return 0;
int d = (int)d_log[a] - (int)d_log[b];
if (d < 0)
d += (int)N;
return d_exp[d];
}
/* Berlekamp-Massey on 2*CT syndromes. Returns L (0..CT) with
* lambda[0..L] filled, or -1 if L exceeds CT at any point (trial
* doomed: L never decreases, so the CPU would reject it too). */
__device__ int cu_bm(const uint32_t *S, const uint32_t *d_log,
const uint32_t *d_exp, uint32_t N, uint32_t P, int m,
uint32_t *lambda)
{
uint32_t C[CT + 1], B[CT + 1], Tm[CT + 1];
#pragma unroll
for (int i = 0; i <= CT; i++)
C[i] = B[i] = 0;
C[0] = B[0] = 1;
int L = 0, shift = 1;
uint32_t b = 1;
for (int n = 0; n < CT2; n++) {
uint32_t d = S[n];
#pragma unroll
for (int i = 1; i <= CT; i++)
if (i <= L && C[i] && n - i >= 0)
d ^= cu_gf_mul(C[i], S[n - i], P, m);
if (d == 0) {
shift++;
continue;
}
#pragma unroll
for (int i = 0; i <= CT; i++)
Tm[i] = C[i];
uint32_t coef = cu_gf_div_tab(d, b, d_log, d_exp, N);
int lim = CT - shift;
#pragma unroll
for (int i = 0; i <= CT; i++)
if (i <= lim && B[i])
C[i + shift] ^= cu_gf_mul(coef, B[i], P, m);
if (2 * L <= n) {
L = n + 1 - L;
if (L > CT)
return -1;
#pragma unroll
for (int i = 0; i <= CT; i++)
B[i] = Tm[i];
b = d;
shift = 1;
} else {
shift++;
}
}
#pragma unroll
for (int i = 0; i <= L; i++)
lambda[i] = C[i];
return L;
}
/* out = a^2 mod mod (mod monic of degree L, 1 <= L <= CT). */
__device__ void cu_square_mod(const uint32_t *a, int L, const uint32_t *mod,
uint32_t P, int m, uint32_t *out)
{
uint32_t prod[2 * CT + 1];
#pragma unroll
for (int i = 0; i <= 2 * CT; i++)
prod[i] = 0;
#pragma unroll
for (int i = 0; i < CT; i++)
if (i < L && a[i])
prod[2 * i] ^= cu_gf_mul(a[i], a[i], P, m);
for (int k = 2 * L - 2; k >= L; k--) {
uint32_t c = prod[k];
if (!c)
continue;
prod[k] = 0;
#pragma unroll
for (int j = 0; j < CT; j++)
if (j < L && mod[j])
prod[k - L + j] ^= cu_gf_mul(c, mod[j], P, m);
}
#pragma unroll
for (int i = 0; i <= CT; i++)
out[i] = (i < L) ? prod[i] : 0;
}
/* Splits test: h = x^(2^m) mod lambda; splits iff h == x (see the
* header comment for why this is exactly the CPU's gcd test). */
__device__ int cu_lambda_splits(const uint32_t *lambda, int L, int m, uint32_t P)
{
if (L <= 1)
return 1;
uint32_t cur[CT + 1], nxt[CT + 1];
#pragma unroll
for (int i = 0; i <= CT; i++)
cur[i] = nxt[i] = 0;
cur[1] = 1;
for (int i = 0; i < m; i++) {
cu_square_mod(cur, L, lambda, P, m, nxt);
#pragma unroll
for (int j = 0; j <= CT; j++)
cur[j] = nxt[j];
}
cur[1] ^= 1; /* h = cur - x */
#pragma unroll
for (int j = 0; j < CT; j++)
if (j < L && cur[j])
return 0;
return 1;
}
/* ---- kernel 1: BM + splits scan, one thread per trial position ---- */
__global__ void chase1_scan_kernel(const uint32_t *d_S, const uint32_t *d_exp,
const uint32_t *d_log, uint32_t N, uint32_t P,
int m, size_t nbits, uint32_t *d_pass,
uint32_t *d_pass_lambda, uint32_t *d_pass_L,
unsigned int *d_npass, unsigned long long *d_split_pass)
{
size_t pp = (size_t)blockIdx.x * blockDim.x + threadIdx.x;
if (pp >= nbits)
return;
uint32_t K = (uint32_t)(nbits - 1 - pp);
uint32_t Sp[CT2];
#pragma unroll
for (int j = 1; j <= CT2; j++) {
uint32_t e = (uint32_t)(((uint64_t)j * K) % N);
Sp[j - 1] = d_S[j - 1] ^ d_exp[e];
}
uint32_t lambda[CT + 1];
int L = cu_bm(Sp, d_log, d_exp, N, P, m, lambda);
if (L < 0)
return;
uint32_t inv = cu_gf_div_tab(1, lambda[L], d_log, d_exp, N);
uint32_t mono[CT + 1];
#pragma unroll
for (int i = 0; i <= L; i++)
mono[i] = cu_gf_mul(lambda[i], inv, P, m);
if (!cu_lambda_splits(mono, L, m, P))
return;
atomicAdd(d_split_pass, 1ULL);
unsigned int idx = atomicAdd(d_npass, 1u);
if (idx >= CHASE_CUDA_MAX_PASS)
return;
d_pass[idx] = (uint32_t)pp;
d_pass_L[idx] = (uint32_t)L;
#pragma unroll
for (int i = 0; i <= CT; i++)
d_pass_lambda[(size_t)idx * (CT + 1) + i] = (i <= L) ? mono[i] : 0;
}
/* ---- kernel 2: parallel Chien search for the survivors ----
* One thread per (survivor, codeword bit): evaluates lambda at
* x_p = alpha^(p-(n-1)) by Horner and records p if it is a root. */
__global__ void chase1_chien_kernel(const uint32_t *d_pass_lambda,
const uint32_t *d_pass_L,
const uint32_t *d_exp, uint32_t N,
uint32_t P, int m, size_t nbits,
unsigned int npass, uint32_t *d_roots,
uint32_t *d_nroots)
{
size_t tid = (size_t)blockIdx.x * blockDim.x + threadIdx.x;
size_t total = (size_t)npass * nbits;
if (tid >= total)
return;
unsigned int pi = (unsigned int)(tid / nbits);
size_t p = tid % nbits;
uint32_t L = d_pass_L[pi];
const uint32_t *lam = d_pass_lambda + (size_t)pi * (CT + 1);
long long off = (long long)p - (long long)(nbits - 1);
long long em = off % (long long)N;
if (em < 0)
em += (long long)N;
uint32_t x = d_exp[em];
uint32_t v = lam[L];
for (int j = (int)L - 1; j >= 0; j--)
v = cu_gf_mul(v, x, P, m) ^ lam[j];
if (v == 0) {
unsigned int idx = atomicAdd(&d_nroots[pi], 1u);
if (idx < (unsigned int)CT)
d_roots[(size_t)pi * CT + idx] = (uint32_t)p;
}
}
/* ---- host side ---- */
int chase_cuda_available(void)
{
int n = 0;
if (cudaGetDeviceCount(&n) != cudaSuccess)
return 0;
return n > 0;
}
/* GF(2^m) exp/log tables, built once per m and cached (host + device). */
typedef struct {
int m;
uint32_t N, P;
uint32_t *h_exp; /* host copy, for the syndrome-zero check */
uint32_t *d_exp, *d_log;
} cu_tables_t;
static cu_tables_t g_tab;
static uint32_t gf_mul_alpha_h(uint32_t x, uint32_t P, int m)
{
uint32_t top = (x >> (m - 1)) & 1u;
x <<= 1;
if (top)
x ^= P;
return x & ((1u << m) - 1);
}
static int cu_tables_for(int m)
{
if (g_tab.m == m && g_tab.d_exp)
return 0;
uint32_t P = bch_prim_poly[m];
uint32_t N = (1u << m) - 1;
uint32_t *exp = (uint32_t *)malloc((size_t)(N + 1) * sizeof(uint32_t));
uint32_t *log = (uint32_t *)malloc((size_t)(N + 1) * sizeof(uint32_t));
if (!exp || !log) {
free(exp);
free(log);
return -1;
}
uint32_t x = 1;
for (uint32_t i = 0; i <= N; i++) {
exp[i] = x;
log[x] = i;
x = gf_mul_alpha_h(x, P, m);
}
log[0] = 0;
uint32_t *d_exp = NULL, *d_log = NULL;
if (cudaMalloc(&d_exp, (size_t)(N + 1) * sizeof(uint32_t)) != cudaSuccess ||
cudaMalloc(&d_log, (size_t)(N + 1) * sizeof(uint32_t)) != cudaSuccess ||
cudaMemcpy(d_exp, exp, (size_t)(N + 1) * sizeof(uint32_t),
cudaMemcpyHostToDevice) != cudaSuccess ||
cudaMemcpy(d_log, log, (size_t)(N + 1) * sizeof(uint32_t),
cudaMemcpyHostToDevice) != cudaSuccess) {
cudaFree(d_exp);
cudaFree(d_log);
free(exp);
free(log);
return -1;
}
free(g_tab.h_exp);
g_tab.m = m;
g_tab.N = N;
g_tab.P = P;
g_tab.h_exp = exp;
g_tab.d_exp = d_exp;
g_tab.d_log = d_log;
free(log); /* device copy kept; host log not needed */
return 0;
}
static void flip_bit(uint8_t *buf, size_t pos)
{
buf[pos >> 3] ^= (uint8_t)(1u << (7 - (pos & 7)));
}
int chase_cuda_scan1(const uint8_t *in, size_t in_len, size_t data_len,
const bch_poly_t *p, uint8_t *cands, int max_cands,
const size_t *suspects, int nsuspects,
long *trials_out, long *split_pass_out,
long *codewords_out)
{
if (!in || !p || !cands || max_cands <= 0 || !trials_out ||
!split_pass_out || !codewords_out)
return -1;
if (p->t != CT)
return -2; /* only t=8 implemented */
if (!chase_cuda_available())
return -2;
size_t stored = bch_block_stored_len(data_len, p);
if (in_len != stored)
return -1;
int r = p->r, m = p->m;
uint32_t N = (1u << m) - 1;
uint32_t P = bch_prim_poly[m];
size_t nbits = (size_t)8 * data_len + (size_t)r;
/* syndrome; also the clean-word early out (same as chase_setup) */
uint32_t S[CT2];
int src = bch_block_syndrome(in, in_len, data_len, p, S);
if (src < 0)
return -1;
if (src == 1) {
*trials_out = 0;
*split_pass_out = 0;
*codewords_out = 0;
return 0;
}
if (cu_tables_for(m) != 0)
return -2;
uint32_t *d_S = NULL, *d_pass = NULL, *d_pass_lambda = NULL,
*d_pass_L = NULL, *d_roots = NULL, *d_nroots = NULL;
unsigned int *d_npass = NULL;
unsigned long long *d_split_pass = NULL;
unsigned int npass = 0;
unsigned long long split_pass = 0;
int rc = -2;
long codewords = 0;
int nc = 0;
uint32_t *h_pass = NULL, *h_pass_L = NULL, *h_roots = NULL, *h_nroots = NULL;
if (cudaMalloc(&d_S, CT2 * sizeof(uint32_t)) != cudaSuccess ||
cudaMalloc(&d_pass, CHASE_CUDA_MAX_PASS * sizeof(uint32_t)) != cudaSuccess ||
cudaMalloc(&d_pass_lambda, (size_t)CHASE_CUDA_MAX_PASS * (CT + 1) * sizeof(uint32_t)) != cudaSuccess ||
cudaMalloc(&d_pass_L, CHASE_CUDA_MAX_PASS * sizeof(uint32_t)) != cudaSuccess ||
cudaMalloc(&d_npass, sizeof(unsigned int)) != cudaSuccess ||
cudaMalloc(&d_split_pass, sizeof(unsigned long long)) != cudaSuccess)
goto out;
if (cudaMemcpy(d_S, S, CT2 * sizeof(uint32_t), cudaMemcpyHostToDevice) != cudaSuccess)
goto out;
if (cudaMemset(d_npass, 0, sizeof(unsigned int)) != cudaSuccess ||
cudaMemset(d_split_pass, 0, sizeof(unsigned long long)) != cudaSuccess)
goto out;
/* kernel 1: BM + splits scan */
{
int block = 256;
size_t grid = (nbits + (size_t)block - 1) / (size_t)block;
chase1_scan_kernel<<<grid, block>>>(d_S, g_tab.d_exp, g_tab.d_log, N, P, m,
nbits, d_pass, d_pass_lambda, d_pass_L,
d_npass, d_split_pass);
if (cudaDeviceSynchronize() != cudaSuccess)
goto out;
}
if (cudaMemcpy(&npass, d_npass, sizeof(unsigned int), cudaMemcpyDeviceToHost) != cudaSuccess ||
cudaMemcpy(&split_pass, d_split_pass, sizeof(unsigned long long), cudaMemcpyDeviceToHost) != cudaSuccess)
goto out;
*split_pass_out = (long)split_pass;
*trials_out = (long)nbits;
if (npass > CHASE_CUDA_MAX_PASS)
npass = CHASE_CUDA_MAX_PASS; /* truncated; not expected (~135) */
if (npass > 0) {
h_pass = (uint32_t *)malloc((size_t)npass * sizeof(uint32_t));
h_pass_L = (uint32_t *)malloc((size_t)npass * sizeof(uint32_t));
h_roots = (uint32_t *)malloc((size_t)npass * CT * sizeof(uint32_t));
h_nroots = (uint32_t *)malloc((size_t)npass * sizeof(uint32_t));
if (!h_pass || !h_pass_L || !h_roots || !h_nroots)
goto out;
if (cudaMemcpy(h_pass, d_pass, (size_t)npass * sizeof(uint32_t),
cudaMemcpyDeviceToHost) != cudaSuccess ||
cudaMemcpy(h_pass_L, d_pass_L, (size_t)npass * sizeof(uint32_t),
cudaMemcpyDeviceToHost) != cudaSuccess)
goto out;
if (cudaMalloc(&d_roots, (size_t)npass * CT * sizeof(uint32_t)) != cudaSuccess ||
cudaMalloc(&d_nroots, (size_t)npass * sizeof(uint32_t)) != cudaSuccess)
goto out;
if (cudaMemset(d_nroots, 0, (size_t)npass * sizeof(uint32_t)) != cudaSuccess)
goto out;
/* kernel 2: parallel Chien search for the survivors */
{
int block = 256;
size_t total = (size_t)npass * nbits;
size_t grid = (total + (size_t)block - 1) / (size_t)block;
chase1_chien_kernel<<<grid, block>>>(d_pass_lambda, d_pass_L,
g_tab.d_exp, N, P, m, nbits,
npass, d_roots, d_nroots);
if (cudaDeviceSynchronize() != cudaSuccess)
goto out;
}
if (cudaMemcpy(h_roots, d_roots, (size_t)npass * CT * sizeof(uint32_t),
cudaMemcpyDeviceToHost) != cudaSuccess ||
cudaMemcpy(h_nroots, d_nroots, (size_t)npass * sizeof(uint32_t),
cudaMemcpyDeviceToHost) != cudaSuccess)
goto out;
/* sort survivors by position ascending: the kernel's
* atomic-append order is nondeterministic, but the CPU
* scans ascending, so candidate order must be sorted. */
for (unsigned int i = 0; i < npass; i++) {
for (unsigned int j = i + 1; j < npass; j++) {
if (h_pass[j] < h_pass[i]) {
uint32_t t;
t = h_pass[i]; h_pass[i] = h_pass[j]; h_pass[j] = t;
t = h_pass_L[i]; h_pass_L[i] = h_pass_L[j]; h_pass_L[j] = t;
t = h_nroots[i]; h_nroots[i] = h_nroots[j]; h_nroots[j] = t;
for (int k = 0; k < CT; k++) {
t = h_roots[(size_t)i * CT + k];
h_roots[(size_t)i * CT + k] = h_roots[(size_t)j * CT + k];
h_roots[(size_t)j * CT + k] = t;
}
}
}
}
}
/* host verification, in CPU order: suspects first in order, then
* ascending positions skipping suspects. For each survivor with
* a full root set, the corrected word's syndrome is
* S ^ col(trial) ^ XOR col(root); it is a codeword iff that is
* zero. Identical to the CPU's zero-remainder check. */
{
uint8_t *seen = (uint8_t *)malloc((size_t)max_cands * data_len);
uint32_t *syn = (uint32_t *)malloc(CT2 * sizeof(uint32_t));
if (!seen || !syn) {
free(seen);
free(syn);
goto out;
}
/* order: suspects (that passed) first, then the rest ascending */
unsigned char *is_susp = (unsigned char *)calloc(npass, 1);
if (!is_susp) {
free(seen);
free(syn);
goto out;
}
for (int s = 0; s < nsuspects && nc < max_cands; s++) {
for (unsigned int pi = 0; pi < npass; pi++) {
if (is_susp[pi] || h_pass[pi] != (uint32_t)suspects[s])
continue;
is_susp[pi] = 1;
/* verify survivor pi */
if (h_nroots[pi] != h_pass_L[pi])
break;
uint32_t K = (uint32_t)(nbits - 1 - h_pass[pi]);
for (int j = 1; j <= CT2; j++) {
uint32_t e = (uint32_t)(((uint64_t)j * K) % N);
syn[j - 1] = S[j - 1] ^ g_tab.h_exp[e];
}
for (uint32_t ri = 0; ri < h_nroots[pi]; ri++) {
uint32_t Kr = (uint32_t)(nbits - 1 - h_roots[(size_t)pi * CT + ri]);
for (int j = 1; j <= CT2; j++) {
uint32_t e = (uint32_t)(((uint64_t)j * Kr) % N);
syn[j - 1] ^= g_tab.h_exp[e];
}
}
int zero = 1;
for (int j = 0; j < CT2; j++)
if (syn[j]) {
zero = 0;
break;
}
if (!zero)
break;
codewords++;
/* build the candidate data bytes and dedup */
uint8_t *work = (uint8_t *)malloc(in_len);
if (!work) {
free(seen);
free(syn);
free(is_susp);
goto out;
}
memcpy(work, in, in_len);
flip_bit(work, h_pass[pi]);
for (uint32_t ri = 0; ri < h_nroots[pi]; ri++)
flip_bit(work, h_roots[(size_t)pi * CT + ri]);
int dup = 0;
for (int c = 0; c < nc; c++)
if (memcmp(seen + (size_t)c * data_len, work, data_len) == 0) {
dup = 1;
break;
}
if (!dup) {
memcpy(cands + (size_t)nc * data_len, work, data_len);
memcpy(seen + (size_t)nc * data_len, work, data_len);
nc++;
}
free(work);
break;
}
}
for (unsigned int pi = 0; pi < npass && nc < max_cands; pi++) {
if (is_susp[pi])
continue;
/* verify survivor pi (same as above, ascending order) */
if (h_nroots[pi] != h_pass_L[pi])
continue;
uint32_t K = (uint32_t)(nbits - 1 - h_pass[pi]);
for (int j = 1; j <= CT2; j++) {
uint32_t e = (uint32_t)(((uint64_t)j * K) % N);
syn[j - 1] = S[j - 1] ^ g_tab.h_exp[e];
}
for (uint32_t ri = 0; ri < h_nroots[pi]; ri++) {
uint32_t Kr = (uint32_t)(nbits - 1 - h_roots[(size_t)pi * CT + ri]);
for (int j = 1; j <= CT2; j++) {
uint32_t e = (uint32_t)(((uint64_t)j * Kr) % N);
syn[j - 1] ^= g_tab.h_exp[e];
}
}
int zero = 1;
for (int j = 0; j < CT2; j++)
if (syn[j]) {
zero = 0;
break;
}
if (!zero)
continue;
codewords++;
uint8_t *work = (uint8_t *)malloc(in_len);
if (!work) {
free(seen);
free(syn);
free(is_susp);
goto out;
}
memcpy(work, in, in_len);
flip_bit(work, h_pass[pi]);
for (uint32_t ri = 0; ri < h_nroots[pi]; ri++)
flip_bit(work, h_roots[(size_t)pi * CT + ri]);
int dup = 0;
for (int c = 0; c < nc; c++)
if (memcmp(seen + (size_t)c * data_len, work, data_len) == 0) {
dup = 1;
break;
}
if (!dup) {
memcpy(cands + (size_t)nc * data_len, work, data_len);
memcpy(seen + (size_t)nc * data_len, work, data_len);
nc++;
}
free(work);
}
free(seen);
free(syn);
free(is_susp);
}
*codewords_out = codewords;
rc = nc;
out:
cudaFree(d_S);
cudaFree(d_pass);
cudaFree(d_pass_lambda);
cudaFree(d_pass_L);
cudaFree(d_npass);
cudaFree(d_split_pass);
cudaFree(d_roots);
cudaFree(d_nroots);
free(h_pass);
free(h_pass_L);
free(h_roots);
free(h_nroots);
return rc;
}
-46
View File
@@ -1,46 +0,0 @@
/* chase_cuda.h - CUDA Chase-1 scan for deep repair (t=8, -e4).
*
* GPU mirror of bch_chase1_block (bch.c) for one block: one CUDA
* thread per trial position runs Berlekamp-Massey + the
* lambda-splits test; a second kernel runs the Chien search in
* parallel for the few survivors; the host verifies each by the
* syndrome-zero check (exactly equivalent to the CPU's
* zero-remainder check: syndrome zero iff remainder zero, since
* the syndrome's roots close under conjugation to the generator).
*
* Candidate order reproduces the CPU's: suspects first in order,
* then ascending positions skipping suspects. Counts (trials,
* split_pass, codewords) use the same definitions as
* bch_chase_stats_t, so results are directly comparable.
*/
#ifndef LZPLY_CHASE_CUDA_H
#define LZPLY_CHASE_CUDA_H
#include <stddef.h>
#include <stdint.h>
#include "bch.h"
#ifdef __cplusplus
extern "C" {
#endif
/* 1 if a CUDA device is present, 0 otherwise. */
int chase_cuda_available(void);
/* Chase-1 for one block on the GPU (t=8 only; returns -2 for other t
* or when CUDA is unavailable/fails). Same candidate contract as
* bch_chase1_block: returns the number of distinct candidate blocks
* in `cands` (each data_len bytes, 0..max_cands), or -1 on bad
* input. `suspects` may be NULL (with nsuspects 0). Stats are the
* same counts as bch_chase_stats_t. */
int chase_cuda_scan1(const uint8_t *in, size_t in_len, size_t data_len,
const bch_poly_t *p, uint8_t *cands, int max_cands,
const size_t *suspects, int nsuspects,
long *trials_out, long *split_pass_out,
long *codewords_out);
#ifdef __cplusplus
}
#endif
#endif /* LZPLY_CHASE_CUDA_H */
+3 -56
View File
@@ -23,16 +23,6 @@
#include "rs.h"
#include "sha256.h"
/* CUDA Chase-1 (chase_cuda.cu), linked only when nvcc is available
* at build time; weak so a CPU-only build links and runs unchanged
* (same pattern as bch_cuda in bch.c on main). */
extern int chase_cuda_available(void) __attribute__((weak));
extern int chase_cuda_scan1(const uint8_t *in, size_t in_len, size_t data_len,
const bch_poly_t *p, uint8_t *cands, int max_cands,
const size_t *suspects, int nsuspects,
long *trials_out, long *split_pass_out,
long *codewords_out) __attribute__((weak));
/* Decompress a blob and verify its SHA-256. Returns a malloc'd raw
* buffer (caller frees) or NULL on failure. Level 0 means stored
* uncompressed (the blob is the raw bytes). */
@@ -149,42 +139,6 @@ static void pool_free(block_pool_t *pool, size_t *pool_bytes)
pool->dlen = 0;
}
/* Chase-1 for one block: the CUDA scan when a device is present,
* the CPU scan otherwise. Same candidate contract as
* bch_chase1_block (suspects first, then ascending positions;
* candidates in scan order, so the L1 direct-try order is
* unchanged). *used_cuda is set to 1 when the GPU scan ran.
* The GPU scan has no deadline (it runs the full scan in ~0.35 s
* on a 524 KiB block); when the deadline is already past, the CPU
* scan runs instead and reports partial as usual. A -2 from the
* GPU scan (not t=8, or CUDA failed) also falls back to CPU. */
static int chase1_block(const uint8_t *in, size_t in_len, size_t data_len,
const bch_poly_t *p, uint8_t *cands, int max_cands,
const size_t *suspects, int nsuspects,
bch_chase_stats_t *stats, double deadline,
int *used_cuda)
{
*used_cuda = 0;
if (chase_cuda_available && chase_cuda_available() &&
(deadline < 0 || bch_now() < deadline)) {
long trials = 0, split_pass = 0, codewords = 0;
int ncc = chase_cuda_scan1(in, in_len, data_len, p, cands,
max_cands, suspects, nsuspects,
&trials, &split_pass, &codewords);
if (ncc >= 0) {
stats->trials = trials;
stats->split_pass = split_pass;
stats->codewords = codewords;
stats->candidates = ncc;
stats->partial = 0;
*used_cuda = 1;
return ncc;
}
}
return bch_chase1_block(in, in_len, data_len, p, cands, max_cands,
suspects, nsuspects, stats, deadline);
}
int deep_repair_entry(const uint8_t *stored, size_t stored_len, int level,
int is_bch, uint16_t poly_id, int rs_level,
const uint8_t want_sha[32], size_t blob_size,
@@ -418,8 +372,7 @@ int deep_repair_entry(const uint8_t *stored, size_t stored_len, int level,
free(bc);
}
added1 = pools[bi].n; /* pool size after pass-2 */
/* Chase-1 candidates (suspects first, then scan) --
* GPU when a device is present, else CPU. */
/* Chase-1 candidates (suspects first, then scan). */
{
size_t *susp = malloc(sizeof(size_t) *
BCH_CHASE_MAX_SUSPECTS);
@@ -436,16 +389,10 @@ int deep_repair_entry(const uint8_t *stored, size_t stored_len, int level,
bslen[bi], bdlen[bi],
poly, susp,
BCH_CHASE_MAX_SUSPECTS);
{
int used_cuda = 0;
ncc = chase1_block(bch_stored + s_off,
ncc = bch_chase1_block(bch_stored + s_off,
bslen[bi], bdlen[bi], poly,
cc, BCH_CHASE_MAX_CANDS,
susp, ns, &cs, deadline,
&used_cuda);
if (used_cuda)
stats->chase_cuda_used = 1;
}
susp, ns, &cs, deadline);
stats->trials[1] += cs.trials;
stats->split_pass[1] += cs.split_pass;
stats->codewords[1] += cs.codewords;
-1
View File
@@ -67,7 +67,6 @@ typedef struct {
long blocks_total; /* BCH blocks in the blob */
long blocks_failed; /* blocks failing standard decode */
int partial; /* a level stopped early on its budget */
int chase_cuda_used; /* L1 ran on the GPU (CUDA Chase-1 scan) */
char fail_stage[24]; /* "ok", "rs", "len", "crc", "sha",
"budget", "noecc", "nocand" */
} deep_stats_t;
+321
View File
@@ -0,0 +1,321 @@
# lzply baseline — experiments/baseline @ 8dbb8d03
Measured 2026-12-02 on hot_newyork (172.93.49.176, 8 cores, 30 GB RAM,
Ubuntu 26.04.1, gcc 15.2.0, liblz 1.16~rc1, libfuse3 3.18.2).
Base commit: `8dbb8d03` — "BCH: two-pass silent repair (hash-gated pass 2;
zero silent failures, loud failure otherwise)".
Branch: `experiments/baseline`. This file is the yardstick for the
parallel ECC / compression experiments: same corpus, same commands,
same harness (`bench/`).
## 1. Codebase map
Repo root `/opt/lzply-exp-base` (checked out from
`git@github.com:cnmcdee/lzply.git`, branch `experiments/baseline`).
~11,633 lines of C/Python, no legacy support: v4 (`LZPL`) is the only
format; v1/v2/v3 and old magics `LZRS`/`LZBC` are rejected outright.
| File | Lines | Role |
|---|---|---|
| `lzply.c` | 1926 | `lzply` CLI: `-c/-a/-d/-l/-t/-i/-tr`, date filters, selectors |
| `lzply_lib.c` / `lzply_lib.h` | 930 / 253 | shared core: v4 format, per-entry pipeline (lzip -> BCH), header I/O, archive scan, filters |
| `bch.c` / `bch.h` | 1007 / 109 | binary BCH codec + two-pass (pass-2 candidate) repair |
| `bch_polys.h` | 273 | 82 embedded generator polynomials (parents N = 2^m - 1, m = 7..22) |
| `gen_bch_polys.py` | 322 | regenerates `bch_polys.h` from rssearch data (checked in, not rebuilt by make) |
| `bch_test.c` | 415 | BCH unit tests (table remainder vs brute force, roundtrips, corruption, auto-pick, block splitting) |
| `sha256.c` / `sha256.h` | 124 / 26 | SHA-256 (per-entry integrity; load-bearing against BCH miscorrection) |
| `lzply_mount.c` | 1448 | FUSE filesystem (`lzply_mount`, `mount.lzply` helper) |
| `lzply_stat.c` | 293 | per-entry statistics (sizes, poly, t, parity bits, ECC overhead %) |
| `lzply_heal.c` | 618 | strip + re-apply BCH parity without touching the compressed blob |
| `lzply_check.c` | 564 | bit-error-rate measurement (`--json`, `--warn-ber`, `--fail-ber`) |
| `lzply_refresh.c` | 410 | in-place platter refresher (1-3 passes, SHA-256 verified) |
| `lzply_hyper.c` | 2264 | striped volume: 8 bit-plane data stripes + 1-3 XOR/GF parity, rebuilds up to 3 dead stripes (no compression) |
| `lzply_util.c` / `lzply_util.h` | 440 / 33 | shared helpers for stat/heal/check/refresh (mount resolution via /proc, human sizes) |
| `lzprobe.c` | 41 | tiny probe tool |
| `Makefile` | 137 | builds 7 binaries + `bch_test`; `make test` runs the full suite |
| `tests/run_tests.sh` | 1156 | 147 archive tests (see §3) |
| `tests/run_hyper_tests.sh` | 443 | 56 striped-volume tests |
| `tests/corrupt.c`, `tests/corrupt_bits.c` | 96 / 103 | whole-byte / single-bit corruption injectors used by the suite |
| `tests/make_testdata.sh` | 46 | generates `testdata/` (incl. a 50 MiB random file) on demand |
| `bench/bench.sh` | — | this baseline's ratio/speed/memory benchmark (see §5) |
| `bench/corrupt_matrix.py` | — | this baseline's corruption matrix (see §6) |
| `README.md`, `README-hyper.md`, `lzply_hyper-design.md` | — | user docs; format + CLI reference |
Build system: plain `make` (no configure/autotools). `make -j8` builds
`lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh
lzply_hyper` + `liblzply.a` (lzply_lib + bch + sha256). Deps:
`build-essential`, `liblz-dev` (lzip/LZMA), `libfuse3-dev` (mount only).
`CFLAGS = -O2 -Wall -Wextra`; the baseline build is warning-clean.
## 2. Format (v4) and pipeline
All integers little-endian. Global header (16 B): magic `"LZPL"`,
version u8 (=4), flags u8, entry_count u32, reserved u64. Each entry:
u16 path_len, u8 level, u8 rs_level, u8 flags, u8 reserved,
u64 orig_size, u64 stored_size, u64 blob_size, u8 sha256[32],
u32 mode, u64 mtime, u32 header_crc32 (covers the 74 bytes before it),
path[path_len], data[stored_size]. End marker: u16 path_len == 0.
Per-entry pipeline: `compress (lzip) -> BCH encode` on write;
`BCH-decode -> decompress` on read. One entry = one independent byte
stream. `blob_size` is the compressed length before ECC parity.
CLI (see `README.md` for the full reference):
- Compression: lzip levels `-1`..`-9`, default `-6`. The compressed
stream inside an entry is byte-identical to `lzip -N`.
- Store mode (level 0): when the compressed blob would be no smaller
than the original (already-compressed / random / empty), the entry is
stored uncompressed; BCH still applies. `-0` forces store for all.
- Error correction: `-e <0..7>` maps to BCH t: 0 -> none, 1 -> 1,
2 -> 2, 3 -> 4, 4 -> 8, 5 -> 16, 6 -> 32, 7 -> 32. Default `-e 4`
(t=8). `poly=NN` (hex `poly=003a` or decimal `poly=58`) pins one
polynomial and overrides `-e`. With no pin, the most efficient poly
for the blob length is auto-picked (smallest parent whose codeword
covers the blob). A blob longer than one block's capacity is split
into blocks of that poly's max payload (m=22, t=32: 524,199 B/block);
the decoder rebuilds boundaries from blob_size + poly.
- Integrity: every entry carries SHA-256 of its original data. A
bounded-distance BCH decoder can miscorrect damage beyond t (e.g.
t=1, 2-bit errors miscorrect ~50% at codec level); SHA-256 catches
it, so miscorrection is reported as corruption, never silent damage.
- Two-pass repair (this base commit): when pass-1 decode fails (or the
hash fails after a pass-1 success), pass 2 enumerates up to 16
candidate decodings (residual-BM + bounded flip-and-redecode) and the
caller hash-verifies each; first SHA-256 match wins, otherwise loud
failure. Zero silent failures by construction.
- Timestamps: mtime (seconds, UTC) + file mode stored per entry;
ownership not stored. `-datestart` / `-dateend` / `-year` filter on
mtime; `-i` reads headers only (never decompresses); `-tr` prints a
tree; `-a` appends (incremental when no path collides); selectors
match exact paths or directory prefixes.
- Exit codes: 0 ok, 1 usage, 2 I/O error, 3 corrupt/unrecoverable.
- Limitations (v4): whole files buffered in memory (50 MiB fine,
multi-GB needs a streaming rewrite); symlinks/special files skipped;
BCH corrects scattered bit flips, not whole lost bytes — a burst
wiping many consecutive bits in one block can exceed t even when the
byte count is small; the BCH decoder builds GF(2^m) log/exp tables
(up to 32 MiB transient for m=22) the first time it must correct an
error in a block (no-error path needs no tables).
## 3. Test suite — results at this base
`make test` = `bch_test` + `tests/run_tests.sh` + `tests/run_hyper_tests.sh`.
| Suite | Result (hot_newyork) |
|---|---|
| `bch_test` phase 1+2 (remainder x-check + roundtrip, all 82 polys) | 5220 checks, 0 fails |
| `bch_test` phase 3 (corruption) | 7253 checks, 0 fails |
| `tests/run_tests.sh` | **147 passed, 0 failed** |
| `tests/run_hyper_tests.sh` | **56 passed, 0 failed** |
Coverage: roundtrips at every level `-1`..`-9`; byte-identical
cross-check vs system `lzip -6` (at `-e 0`); roundtrips at BCH levels
0..7; BCH corruption with pinned polys (t recovered, t+1 fails
cleanly); combined `-9 -e 5` with 16 corrupted bits; v1/v3 archives
and old magics rejected; overwrite flags; empty dir/file, 1-byte file,
spaces in names, truncated/non-archive inputs; 50 MiB multi-block file;
`poly=` pinning (hex/decimal), unknown-poly rejection; append (21
tests) + selective extract; inspect/tree/date filters (27 tests);
`lzply_stat` (4), `lzply_heal` (8), `lzply_check` (8),
`lzply_refresh` (9), mount write-back (3), store mode (16).
Environment caveat (NOT a code failure): run from `/opt/lzply-exp-base`
the suite reports **144 passed, 3 failed** — the 3 mount write-back
tests (`mount with relative archive path: writes persist in the real
archive`, `store mode: mount repack stores an incompressible file`,
`store mode: mount-repacked stored file extracts byte-identical`).
Root cause, verified: AppArmor's `fusermount3` profile (enforce mode,
`/etc/apparmor.d/fusermount3`) allows `umount` only under
`@{HOME}/**`, `/mnt/**`, `/run/user/@{uid}/**`, `/media/**`,
`/tmp/**`, `/cvmfs/**` — NOT under `/opt/**`. `fusermount3 -u`
fails with EPERM (audit: `apparmor="DENIED" operation="umount" ...
profile="fusermount3"`), the mount stays up, the repack never runs,
and the test reads the pre-mount archive. The lzply code is correct:
the same tests pass when the tree is copied under `/tmp`
(147/0 above), a manual relative-path mount under `/tmp` repacks
correctly, and plain `umount` (unconfined) unmounts the `/opt` mounts
fine and triggers the repack. To run the suite green, run it from a
copy under `/tmp` (or any AppArmor-allowed path):
`cp -a /opt/lzply-exp-base /tmp/lzply-tmproot && cd /tmp/lzply-tmproot && make test`.
Stale mounts left by the failing `/opt` runs were cleaned with
`umount` (the other coordinator's `/opt/lzply-exp-ecc` mounts were
left untouched).
## 4. Corpus (reproduction)
Standard corpora, downloaded 2026-12-02 to `/opt/lzply-bench/corpus/`:
- `enwik8` — first 100,000,000 bytes of English Wikipedia
(https://mattmahoney.net/dc/enwik8.zip), sha256
`2b49720ec4d78c3c9fabaee6e4179a5e997302b3a70029f30f2d582218c024a8`
- Silesia corpus (https://sun.aei.polsl.pl/~sdeor/corpus/silesia.zip),
all 12 files:
| file | bytes | sha256 |
|---|---|---|
| dickens | 10,192,446 | `b24c37886142e11d0ee687db6ab06f936207aa7f2ea1fd1d9a36763c7a507e6a` |
| mozilla | 51,220,480 | `657fc3764b0c75ac9de9623125705831ebbfbe08fed248df73bc2dc66e2a963b` |
| mr | 9,970,564 | `68637ed52e3e4860174ed2dc0840ac77d5f1a60abbcb13770d5754e3774d53e6` |
| nci | 33,553,445 | `fc63a31770947b8c2062d3b19ca94c00485a232bb91b502021948fee983e1635` |
| ooffice | 6,152,192 | `e7ee013880d34dd5208283d0d3d91b07f442e067454276095ded14f322a656eb` |
| osdb | 10,085,684 | `60f027179302ca3ad87c58ac90b6be72ec23588aaa7a3b7fe8ecc0f11def3fa3` |
| reymont | 6,627,202 | `0eac0114a3dfe6e2ee1f345a0f79d653cb26c3bc9f0ed79238af4933422b7578` |
| samba | 21,606,400 | `93ba07bc44d8267789c1d911992f40b089ffa2140b4a160fac11ccae9a40e7b2` |
| sao | 7,251,944 | `c2d0ea2cc59d4c21b7fe43a71499342a00cbe530a1d5548770e91ecd6214adcc` |
| webster | 41,458,703 | `6a68f69b26daf09f9dd84f7470368553194a0b294fcfa80f1604efb11143a383` |
| x-ray | 8,474,240 | `7de9fce1405dc44ae5e6813ed21cd5751e761bd4265655a005d39b9685d1c9ad` |
| xml | 5,345,280 | `0e82e54e695c1938e4193448022543845b33020c8be6bf3bf3ead2224903e08c` |
Data files total 311,489,800 bytes. The corpus directory also holds the
two source zips (`enwik8.zip` 36,445,475 B, `silesia.zip` 68,182,744 B);
whole-directory runs archive all 15 files (416,566,799 B total).
Corruption-matrix input: `slice1m.bin` = first 1,048,576 bytes of
`enwik8`, sha256
`4fb5efa9f35df431737731bf3c8f38a467b69731940ff82a4ee0e218aae58834`,
archived as `slice1m.lzply` at `-6 -e 4` (blob 296.9 KiB, poly `0050`,
t=8, single BCH block; 176 parity bits, 0.007% ECC overhead).
Reproduce the corpus download:
```sh
mkdir -p /opt/lzply-bench/corpus && cd /opt/lzply-bench/corpus
curl -sL -o enwik8.zip https://mattmahoney.net/dc/enwik8.zip
curl -sL -o silesia.zip https://sun.aei.polsl.pl/~sdeor/corpus/silesia.zip
python3 -c "import zipfile; zipfile.ZipFile('enwik8.zip').extractall()"
python3 -c "import zipfile; zipfile.ZipFile('silesia.zip').extractall()"
sha256sum enwik8 dickens mozilla mr nci ooffice osdb reymont samba sao webster x-ray xml
```
## 5. Baseline numbers — ratio, speed, memory
Command: `bench/bench.sh <lzply> <corpus-dir> <work-dir>` (needs
GNU `time`, `/usr/bin/time -v`, for wall clock + max RSS). Each run:
one encode, one decode, `diff -r` round-trip check. Machine shared
with other agents' builds during measurement — encode wall times are
noisy (see caveat); decode is stable. All round-trips bit-identical.
### 5.1 enwik8, single file, 100,000,000 bytes, default -e 4 (t=8)
| level | archive bytes | ratio | enc wall | enc MB/s | enc max RSS | dec wall | dec MB/s | dec max RSS |
|---|---|---|---|---|---|---|---|---|
| -1 | 29,126,665 | 29.13% | 1:43.82 | 0.96 | 156,404 KB | 0:06.57 | 15.2 | 157,560 KB |
| -6 | 26,519,665 | 26.52% | 3:06.14 | 0.54 | 215,800 KB | 0:06.19 | 16.2 | 159,668 KB |
| -9 | 25,397,987 | 25.40% | 4:10.43 | 0.40 | 485,112 KB | 0:06.24 | 16.0 | 181,880 KB |
### 5.2 whole corpus directory, 416,566,799 bytes (15 files), -6
| -e (t) | archive bytes | ratio | enc wall | enc MB/s | enc max RSS | dec wall | dec MB/s | dec max RSS |
|---|---|---|---|---|---|---|---|---|
| 4 (t=8, default) | 181,121,579 | 43.48% | 8:54.98 | 0.78 | 242,384 KB | 0:22.28 | 18.7 | 233,832 KB |
| 0 (no ECC) | 181,113,835 | 43.48% | 8:33.81 | 0.81 | 242,444 KB | 0:17.31 | 24.1 | 177,976 KB |
| 7 (t=32) | 181,144,811 | 43.49% | 8:56.79 | 0.78 | 242,568 KB | 0:38.93 | 10.7 | 233,844 KB |
ECC overhead on this corpus: default t=8 costs 7,744 bytes over no-ECC
(0.0043%); t=32 costs 30,976 bytes (0.017%). BCH parity is negligible
next to LZMA output at these sizes — the overhead story is per-block
parity bits, not a percentage of the archive. Decode slows with t
(17.3s -> 22.3s -> 38.9s) because larger t means larger GF tables on
the correction path and more blocks to check.
### 5.3 mozilla (binary-ish), 51,220,480 bytes, -6 -e 4
| archive bytes | ratio | enc wall | enc MB/s | enc max RSS | dec wall | dec MB/s | dec max RSS |
|---|---|---|---|---|---|---|---|
| 13,580,691 | 26.51% | 0:49.45 | 1.04 | 155,768 KB | 0:02.89 | 17.7 | 86,776 KB |
### 5.4 Caveats
- Encode speed is dominated by single-threaded LZMA (`liblz`), not by
BCH: `-1` vs `-9` on enwik8 is 0.96 vs 0.40 MB/s for a 29.1% ->
25.4% ratio gain. Any compression-family experiment must beat
these ratio/speed points, not just the ratio.
- Wall times were measured while other agents were building on the
same 8-core server; expect encode times to vary run to run. Decode
times (I/O + LZMA decode, single-threaded) were stable across runs.
- Peak RSS is dominated by the whole-file buffering (input + blob +
stored copy in memory at once) plus, at `-9`, LZMA's dictionary
(485 MB for enwik8 -9 encode). Multi-GB files need the streaming
rewrite noted in §2.
## 6. Corruption matrix — correction power at default -e 4 (t=8)
Harness: `bench/corrupt_matrix.py <lzply> <archive> <trials> [seed]`.
Single-entry archive `slice1m.lzply` (see §4: 1 MiB text, blob
296.9 KiB, one BCH block, t=8). Each trial: copy the archive, corrupt
ONLY the stored-data region (headers untouched), run `lzply -t`, and
on success extract + SHA-256-verify the recovered file. 200 trials
per setting, seed 20261202 (Python `random.Random`, deterministic).
"recovered" = `-t` passed AND extracted bytes hash-identical;
"failed-loud" = `-t` (or extract) exited non-zero; "silent-bad" =
passed but content wrong (must be 0 — the SHA-256 gate).
### 6.1 Results (200 trials per setting)
Scattered bits (seed 20261202), single 304 KB block, t=8:
| scattered bits flipped | recovered | failed-loud | silent-bad |
|---|---|---|---|
| 1 | 200/200 | 0 | 0 |
| 2 | 200/200 | 0 | 0 |
| 4 | 200/200 | 0 | 0 |
| 8 (= t) | 200/200 | 0 | 0 |
| 9 (= t+1) | **0/200** | 200 | 0 |
| 16 | **0/200** | 200 | 0 |
| 32 | **0/200** | 200 | 0 |
Bursts — L consecutive bytes replaced with random bytes (up to 8L bit
errors); two independent seeds:
| burst length | recovered (seed 20261202) | recovered (seed 20261203) | failed-loud | silent-bad |
|---|---|---|---|---|
| 1 byte | 200/200 | 200/200 | 0 | 0 |
| 2 bytes | 135/200 | 117/200 | 65 / 83 | 0 |
| 4 bytes | 0/200 | 0/200 | 200 | 0 |
| 8 bytes | 0/200 | 0/200 | 200 | 0 |
| 16 bytes | 0/200 | 0/200 | 200 | 0 |
**Total silent-bad across all 2,800 trials: 0.** The SHA-256 gate
holds everywhere: damage beyond t is always a loud failure, never
wrong data.
### 6.2 Reading the numbers
- The cliff is exactly at t: everything at or below 8 scattered bit
errors recovers; everything above recovers nothing. Pass 1
(bounded-distance BCH) behaves exactly as theory says.
- **Pass 2 rescues nothing beyond t for random scattered errors at
this block size: 0/600 trials at n = 9, 16, 32.** Pass 2 IS wired
in (`entry_decode` in `lzply_lib.c` calls `bch_decode_candidates`,
up to 16 candidates, hash-gated) — the residual-BM +
flip-and-redecode candidates simply never land on the true codeword
for random t+1..t+4 patterns in a 304 KB (m=22) block. This is the
gap the deep-repair work (Chase flips, list decoding) exists to
close; any experiment claiming beyond-t recovery must beat 0/200
here, on this archive, with these seeds.
- The 2-byte burst split (117-135/200) is the binomial edge: two
random bytes differ in ~8 bits on average, so about half the trials
land at <= 8 bit errors (recovered) and half above (failed). A
1-byte burst is always <= 8 bit errors, hence 200/200.
- Pass 2 is expensive when it runs: trials at n <= 8 cost ~1 s each
(fresh `lzply -t` + `lzply -d` processes, GF(2^22) table build on
the correction path); trials beyond t cost ~4-5 s each (candidate
enumeration). A repair scheme's per-block time budget matters as
much as its recovery rate.
Reproduce: `python3 bench/corrupt_matrix.py /opt/lzply-exp-base/lzply
/opt/lzply-bench/slice1m.lzply 200 20261202` (bits + bursts, one
process) or with `MATRIX_ONLY=burst MATRIX_WORKDIR=/tmp/lzply-matrix-burst`
and seed 20261203 for the burst-only run. Logs:
`/opt/lzply-bench/matrix.log`, `/opt/lzply-bench/matrix-burst.log`.
## 7. What is NOT in this baseline
- hot_chicago build/test: blocked by the sshd outage (new sessions
hang at banner exchange; see report). The branch is pushed, so the
Chicago run is a clone + `make -j8` + `make test` + the same
`bench.sh` / `corrupt_matrix.py` once SSH recovers. Chicago needs
no package installs (lzip, liblz-dev, libfuse3-dev present).
- `lzply_hyper` (striped volume) numbers: the suite passes (56/0)
but no separate ratio/speed benchmark was run — it stores
uncompressed stripes, so its yardstick is rebuild time, not ratio.
+203
View File
@@ -0,0 +1,203 @@
# Integration: experiment winners on current main (LZPL v5)
Merged onto `experiments/integration` at `b27b345` (LZPL v5 + lz_rs +
deep repair + CRC16). The three experiment branches were all based on
`8dbb8d03`; this integration re-bases their winners onto current main
instead. The archive format is unchanged (still LZPL v5): the winners
arrive as standalone tools in `exp/` and `experiments/`, built and
smoke-tested by `tests/run_integration_tests.sh` (hooked into
`make test`). Wiring interleave/LDPC into `lzply -e` levels would be
a format change (LZPL v6) and is explicitly future work, not done here.
## Sources
| branch | tip | carried over |
|---|---|---|
| `experiments/baseline` | `5807281` | `bench/`, `docs/BASELINE.md` (the comparison baseline) |
| `experiments/ecc` | `a34cd7d` | `exp/` harness + interleave + LDPC (see below) |
| `experiments/comp` | `fbce346` | `experiments/` rANS core + dict + bchcheck (see below) |
## Winners (integrated)
### 1. Byte interleaving, depth 64, over small-block BCH (`exp/`)
* What: the encoded stream (BCH, 1 KiB blocks) is permuted before it
hits the channel — groups of D consecutive blocks written row-wise
into a D-row matrix, read out column-wise. A burst of L bytes then
hits any one block at most ceil(L/D) bytes instead of all L bytes
landing in one block and killing it. Zero extra parity: a pure
permutation, inverted on decode, so overhead is exactly the BCH
overhead and random-error performance is unchanged.
* Gotcha fixed on the branch: groups merge the short tail (a 4-block
tail group measured 0.94 on 64 B bursts before the fix).
* Measured (text.lz, 64 KiB windows, 200 trials/setting):
`intlv-d64-bch1k-t32` recovers 1.00 at burst 16/64/256 B and 1.00 at
4x64 B bursts, where uninterleaved `bch1k-t32` recovers 0.00 at every
burst size. Random-error performance unchanged by construction
(1.00 at BER 1e-3, same as `bch1k-t32`). Overhead 5.40%.
Even at 1.29% overhead, `intlv-d64-bch1k-t8` survives 64 B bursts
at 1.00.
* Speed: interleaving costs nothing measurable (3.39 MB/s enc,
1.73 MB/s dec — same as the BCH underneath).
* Use:
```
cd exp && ./mkcorpora.sh # build corpora/text.lz etc.
./bench --codec intlv-d64-bch1k-t32 --blob corpora/text.lz \
--size 65536 --trials 200 --burst 256,1 --out results/x.csv
```
### 2. Small-block BCH, 1 KiB blocks (`exp/`)
* What: the same BCH lzply ships, but forced to m=13 blocks
(971 data bytes/block) instead of one huge block per blob.
This is the "spend real redundancy" point.
* Measured (text.lz, 64 KiB, 200 trials): `bch1k-t32` recovers 1.00
at BER 1e-4 and 1e-3, 0.01 at 3e-3, at 5.40% overhead — where
as-shipped `bch-t32` (one 64 KiB block, 0.12% overhead) recovers
1.00 at 1e-5, 0.01 at 1e-4, 0.00 at 1e-3. Bursts still kill it
without interleaving (256 B burst: 0.00 at every t).
* Speed: `bch1k-t32` 2.97 MB/s enc, 1.55 MB/s dec;
`bch1k-t8` 9.98 / 5.87 MB/s at 1.29% overhead.
* Use:
```
./bench --codec bch1k-t32 --blob corpora/text.lz \
--size 65536 --trials 200 --ber 1e-3
```
### 3. Regular LDPC, rate 0.90 (`exp/`)
* What: regular LDPC, PEG construction, min-sum belief propagation.
n=8192 bits, column weight 3, m=768 checks, row weight 32,
k=7424 bits (928 B). Fixed seed, so the code is identical on every
run and every server. Systematic encoding by Gauss-Jordan reduction
of H to [I | P] (one-time, at codec creation, ~1.8 s init).
* Measured (text.lz, 64 KiB, 200 trials): `ldpc-r90` recovers 1.00
at BER 1e-3 and 0.97 at 3e-3, where `bch1k-t32` recovers 0.01 at
3e-3 — the iterative decoder's cliff sits a decade higher in BER.
Overhead 10.94%. Bursts kill it (16 B burst: 0.24); LDPC+interleave
is the follow-up. `ldpc-r95` is weak (0.32 at 1e-3, fails at
6 errors/block); irregular LDPC is the follow-up.
* Speed: 3.34 MB/s enc, 0.91 MB/s dec — ~4x slower decode than
`bch1k-t32`.
* Use:
```
./bench --codec ldpc-r90 --blob corpora/text.lz \
--size 65536 --trials 200 --ber 1e-3
./ldpc_diag r90 40 50 # single-block error-count sweep
```
### 4. Dictionary transform, code-only opt-in (`experiments/`)
* What: per-file word dictionary (top 4096 words by saving,
transmitted in the header), words -> 3-byte codes, then lzip -6.
Format: magic `DICT`, u32 orig_len, u16 ndict, entries (u8 len,
bytes); 0xFF escape introduces a 2-byte code.
* Measured (8 MiB corpora, lzip -6): code 9.19% vs plain lzip6 9.38%
(-2.1% better — long repeated identifiers survive as codes better
than as LZ matches). Everywhere else the dictionary costs more
than it saves: text 3.58 vs 3.56 (+0.5% worse), bin 33.30 vs 32.61,
mixed 17.65 vs 17.41, rand worse. Not a default; a code-only
optional preprocessing stage at most.
* End-to-end BCH check (`bchcheck`): dict+lzip code blob (770,519 B)
BCH t=8, 8 flips -> 8 corrected, full pipeline recovers
bit-identical; 32 flips -> decode FAIL (beyond t=8, honest failure).
* Use (dict takes file paths, not stdin):
```
./dict c code.c code.dict && lzip -6 code.dict
lzip -dc code.dict.lz > code.dict2 && ./dict d code.dict2 code.c.out
```
### Supporting infrastructure: rANS core (`experiments/rans.[ch]`)
* What: the shared entropy stage for the prototypes — static
per-file freqs, 12-bit probs. Enc 30-38 MB/s, dec 47-62 MB/s,
RSS ~20 MB. Kept as reusable infrastructure, not as a standalone
compressor: order-0 rANS alone scores text 64.40%, code 67.62%
(no LZ stage), so it is a reject as a compressor and a keep as a
core. Two real bugs fixed on the branch (renormalisation threshold;
emitted stream can exceed n bytes, scratch is 2n+64).
* Use: `./rans_tool c in out` / `./rans_tool d in out`.
## Rejects (measured, not carried over)
Only their numbers stay (in `exp/README.md`, `experiments/README.md`,
`experiments/results/*.csv`); the code was removed in the integration
cleanup commit.
| family | verdict | numbers |
|---|---|---|
| Polar SC (`polar-r90`) | dominated, rejected | 0.00 at BER 1e-3 at every design point; designing for p=1e-2 gives 0.00 at 1e-4; best (d4) 0.95 at 1e-4. Dec 0.58 MB/s, slowest of all. SCL list decoding is the follow-up that could rescue it. |
| UEP (unequal error protection) | conditional, not integrated | Whole-file recovery dominated by the weak tier (0.00 at 1e-3). The 1-4 KiB prefix survives (1.00 at 1e-3, 1.00 at 256 B burst) — but only useful if lzply gains a salvage mode; today the entry SHA gates all-or-nothing extraction. |
| LZ77 + rANS (`lzrans`) | rejected as a lzip replacement | lazy: text 6.26, code 13.52, bin 41.84, mixed 23.15; optimal parsing recovers only ~1-3% relative — the gap is LZMA's adaptive context entropy model, not parsing. |
| BWT + MTF + rANS | rejected | text 6.35 (beats bzip2's 9.25), code 12.31, bin 42.76; loses to lzip everywhere; encode 0.05 MB/s (~3 min/8 MB), decode 5-6 MB/s, RSS ~200 MB. |
| PPM order-2 + arithmetic | rejected | text 32.84, code 30.82, mixed 39.18; ~6 MB/s enc, ~4 MB/s dec. Nowhere near PPMd-class. |
| rANS order-0 standalone | rejected as a compressor | text 64.40, code 67.62, bin 77.14 — no LZ stage. Core kept (above). |
## Baselines the winners were measured against
* As-shipped BCH (`bch-t32`): one 64 KiB blob = one BCH block
(m=20, 80 parity bytes, 0.12% overhead, 32 correctable bits per
64 KiB). Cliff between BER 1e-5 and 1e-4 (1.00 -> 0.01).
* Pass 2 (hash-gated candidates) rescues nothing in practice:
0/875 in the pass-2 matrix, 0/50 at every k in the targeted sweep.
Its demonstrated value is the loud-failure guarantee: 0 silent
miscorrections in 7813 checks. See `docs/BASELINE.md`.
* lzip (the current lzply stage): text 3.44-3.56%, code 9.05-9.38%,
bin 32.53-32.61%, mixed 17.17-17.41% at -9..-6. No prototype family
beats lzip on ratio. See `experiments/README.md`.
## Verification on the integrated tree
* `make -j8` then `make test` runs the full suites (bch_test,
rs_test, crc16_test, run_rs_tests.sh, run_tests.sh,
run_deep_repair_tests.sh, run_hyper_tests.sh) plus
`tests/run_integration_tests.sh`: clean round-trips for all three
ECC codecs, intlv-d64 burst survival + uninterleaved control,
bch1k BER survival + as-shipped control, LDPC BER survival,
rANS round-trip, dict+lzip round-trip, bchcheck 8-flip recovery
and 32-flip expected failure, LZPL v5 archive round-trip.
* Cross-corpus check on the branches reproduced text.lz exactly on
bin.lz and rand.lz for every codec and setting.
## Build
```
make -j8 # main tools + lz_rs + deep repair
make exp # exp/bench + ldpc_diag + pass2_diag
make experiments # experiments/rans_tool + dict + bchcheck
make test # full suites + integration smoke tests
```
## Fresh numbers on the integrated tree (hot_newyork, 2026-12-02)
Re-measured after the merge with `bench-integration.sh` (best-of-3
timings, load ~1.2-1.6). Data set: mixed dir 25,521,882 bytes (repo
text + repo C sources + /bin/ls, /bin/cat, /usr/bin/lzip) + 1 MiB
/dev/urandom. The lzply core is untouched by the integration, so the
plain-lzply numbers below are the b27b345 numbers.
Plain lzply at b27b345:
- `lzply -c -6` mixed: 7,060,165 bytes, 22.904 s compress / 1.594 s extract
- `lzply -c -6 -e 0` mixed: 7,059,797 bytes (BCH adds 368 bytes here)
- `lzply -c -6` rand1m: 1,048,750 bytes (stored, level 0), 0.577 s / 0.060 s
exp bench --speed, mixed.lz blob (308,207 bytes), 64 KiB windows:
- bch-t32: enc 8.59 MB/s, dec 4.28 MB/s, overhead 0.12%
- bch1k-t32: enc 3.72 MB/s, dec 1.93 MB/s, overhead 5.40%
- intlv-d64-bch1k-t32: enc 3.77 MB/s, dec 1.72 MB/s, overhead 5.40%
- ldpc-r90: enc 4.08 MB/s, dec 1.07 MB/s, overhead 10.94%, init 1.87 s
Recovery on the mixed blob (fresh, reproduces the branch matrices):
- intlv-d64-bch1k-t32, 256 B burst: 1.000 (20 trials)
- bch1k-t32, BER 1e-3: 1.000 (20 trials)
- ldpc-r90, BER 1e-3: 1.000 (10 trials)
Dictionary transform on this corpus (repo C sources only, 786,430
bytes): plain lzip6 120,409 vs dict+lzip6 123,662 (+2.7% worse) --
the branch -2.1% win was on header-heavy code (8 MiB of /usr/include
headers + repo sources). On text (1,004,068 bytes): plain 187,798 vs
dict 191,045 (+1.7% worse). The code-only conditional stands, and it
is corpus-dependent: headers win, plain C sources do not.
rANS order-0 on text (1,004,068 bytes): 614,658 bytes (61.2%),
enc ~31 MB/s, dec ~42 MB/s.
+5 -56
View File
@@ -1,13 +1,11 @@
# Deep repair — past the BCH limit t
Deep repair recovers archive entries whose bit errors exceed
`lzply_deep_repair` recovers archive entries whose bit errors exceed
the BCH correction limit t, in escalating levels, reporting
per-level timing ("time of arrival": how long each level took and
at which level the repair landed). It is built into the main tool
(`lzply -r archive`, same levels and options as the standalone
`lzply_deep_repair` binary, which is still shipped). The CRC16
is the oracle: every beyond-t candidate is CRC-verified before
acceptance, then decompressed and SHA-256-checked.
at which level the repair landed). The CRC16 is the oracle: every
beyond-t candidate is CRC-verified before acceptance, then
decompressed and SHA-256-checked.
## The levels
@@ -39,43 +37,6 @@ acceptance, then decompressed and SHA-256-checked.
holds its true data in the pool but neither single-block
variation passes the CRC.
## The CUDA Chase-1 scan (L1 on the GPU)
On a CUDA build (nvcc present at build time -- `make` links
`chase_cuda.o` into `lzply` and `lzply_deep_repair` automatically;
without nvcc the build is CPU-only and nothing changes), the L1
Chase-1 scan runs on the GPU when a CUDA device is present. The
dispatch is automatic: there is no flag. The scan is the same
algorithm as the CPU one (one thread per trial position:
Berlekamp-Massey + the lambda-splits test, Chien search in
parallel for survivors, host syndrome-zero verification), and
produces the same candidates in the same order -- verified
bit-identical across the 5-pattern validation and a 24-pattern
sweep (10/10 CPU/CUDA hash agreements, zero mismatches).
Measured on hot_house (RTX 3080 Ti), one 524 KiB block (m=22,
t=8, -e4), 4,194,296 trials: **171.571 s CPU -> 0.335-0.379 s
CUDA (453-512x on the timed scan, ~190x end to end)**; the
extended sweep runs 453-562x. A beyond-t repair of a 524 KiB
block that took ~8 minutes at L1 now lands in under a second.
`-v` marks the L1 line `(CUDA)` when the GPU scan ran.
Fallback: the CPU scan runs whenever the GPU scan cannot -- no
CUDA device, a CPU-only build, a non-t=8 poly (the kernel is
t=8 only), a CUDA failure, or a deadline already past when the
scan would start. The symbols are referenced weakly, so a
CPU-only build links and runs unchanged.
Limits: the kernel is t=8 only; Chase-2 is not ported (L2 stays
on the CPU). The GPU scan has no deadline -- it runs the full
scan, then truncates at `BCH_CHASE_MAX_CANDS` (the CPU scan
stops early at the cap when the budget hits); the candidate set
still matches. On small blocks the ~0.115 s CUDA first-touch
cost dominates -- a 512-byte block repairs in ~0.11 s on the GPU
vs ~0.04 s on the CPU -- so the win is on large blocks.
Full write-up: https://www.lzply.com/cuda-chase-500x-deep-repair/
## Why the suspect set does not help Chase-2 (much)
With hard-decision input there is no channel reliability, so
@@ -137,16 +98,6 @@ lzply_deep_repair [-l max-level 0..3] [--time-budget seconds] [-v]
[-o outdir] [--entry name] archive
```
The same repair is built into the main tool:
```
lzply -r [--level 0..3] [--time-budget seconds] [-v]
[-o outdir] [--entry name] archive [outdir]
```
`-r` takes the same levels, budget, and output options
(`--level` in place of `-l`, which is the list mode in `lzply`).
Per-entry output:
```
@@ -217,9 +168,7 @@ wrong-but-valid candidates per trial and the CRC rejects all
`bch_test` 7,975 checks still pass). A full Chase-1 scan of a
524 KiB block (4,194,296 trials) takes **471.9 s** (measured,
probe5: RECOVERED at L1 in 471.918 s, trials 4,194,296,
split 126, codewords 126). On a CUDA build the same scan runs
on the GPU in ~0.35 s (see the CUDA section above); 471.9 s is
the CPU scan. The tool scans fully before trying
split 126, codewords 126). The tool scans fully before trying
candidates (the chase layer has no oracle), so the landing time
is the full-scan time, not the time to the lowest true error.
At the default 120 s budget a beyond-t repair of a 524 KiB
+6
View File
@@ -0,0 +1,6 @@
bench
ldpc_diag
pass2_diag
*.o
corpora/
results/
+26
View File
@@ -0,0 +1,26 @@
# exp/Makefile - build the ECC experiments harness (bench).
# Links the real lzply BCH + SHA-256 from the repo root.
CC ?= gcc
CFLAGS ?= -O2 -Wall -Wextra -march=native
CPPFLAGS ?= -I. -I..
SRCS = bench.c bch_wrap.c interleave.c ldpc.c \
../bch.c ../sha256.c
OBJS = $(SRCS:.c=.o)
bench: $(OBJS)
$(CC) $(CFLAGS) -o $@ $(OBJS) -lm
ldpc_diag: ldpc_diag.c ldpc.c
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ ldpc_diag.c ldpc.c -lm
pass2_diag: pass2_diag.c ../bch.c ../sha256.c
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ pass2_diag.c ../bch.c ../sha256.c -lm
%.o: %.c
$(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $@
clean:
rm -f bench ldpc_diag pass2_diag $(OBJS)
.PHONY: clean
+206
View File
@@ -0,0 +1,206 @@
# lzply ECC experiments (branch `experiments/ecc`)
> Integrated onto current main (`experiments/integration`, LZPL v5):
> the winners here are interleaving d64, small-block BCH 1 KiB, and
> LDPC r90. Polar and UEP were measured, rejected, and their code was
> NOT carried over — see `docs/INTEGRATION.md`.
Open-ended error-correction research on top of lzply's BCH baseline.
Each family implements `ecc_iface.h` (whole-blob encode/decode) and is
measured by `bench.c` on the same corpora, same corruption matrix, same
success criterion (exact recovery, memcmp + SHA-256).
## How to run
```
./bench --codec bch-t32 --blob corpora/text.lz --size 65536 \
--trials 200 --ber 1e-3 --nopass2 --out results/x.csv
./bench --codec ldpc-r90 --blob corpora/text.lz --burst 256,1 --trials 200
./bench --codec bch-t32 --blob corpora/text.lz --speed
./ldpc_diag r90 40 50 # single-block error-count sweep
./uep_diag uep-c1024-h32-l8 corpora/text.lz 65536 50 --ber 1e-3
```
Modes: `--ber X` (independent bit flips), `--burst LEN,COUNT`
(COUNT randomized-byte bursts of LEN bytes), `--clean`, `--speed`.
`--nopass2` skips the (slow) second-chance recovery hook so the matrix
stays fast; `run_pass2.sh` measures rescue rates separately.
`run_matrix.sh <corpus> <size> <trials> <out.csv> <codec...>` runs the
full matrix (5 BERs + 5 burst settings + clean), parallel over cores.
Corpora (`mkcorpora.sh`, generated, not committed): `text.lz` /
`bin.lz` / `rand.lz` — lzip -9 of 4 MiB text, binaries, seeded random
bytes (the compressed blob is what lzply protects); `*.raw` — the
stored-entry case. Default window is 64 KiB.
## Families
| codec | what it is |
|---|---|
| `bch-t{2,4,8,16,32}` | Baseline: BCH exactly as lzply ships it (auto-pick poly for the whole blob; pass 2 via `recover_verified`). |
| `bch1k-t{8,16,32}` | Same BCH, forced m=13 blocks (971 data bytes/block) — the "spend real redundancy" point. |
| `intlv-d{D}-bch1k-t{T}` | Byte interleaver (depth D) over bch1k-t{T}. Zero extra parity; bursts spread across blocks. Groups merge the short tail (see below). |
| `ldpc-r{90,95}` | Regular LDPC, PEG construction, min-sum belief propagation. |
| `polar-r{90,95}[-d{2,3,4}]` | Polar code, SC decoding. `-dN` is the design crossover 1e-N (default d2 = 1e-2). The design point matters enormously (see below). |
| `uep-c{C}-h{H}-l{L}` | Unequal error protection: first C bytes at BCH t=H, rest at t=L (small blocks). |
## Results (text.lz, 64 KiB windows, 200 trials/setting, hot_newyork)
Recovery rate = fraction of trials exactly recovered. Overhead is
measured (stored/data - 1). Pass-2 rescue rates are in
results/pass2-text.csv (separate, 25 trials/setting).
### Baseline: what lzply ships is nearly unprotected
| codec | ovh | BER 1e-5 | 1e-4 | 1e-3 | 3e-3 | 1e-2 | burst 256 B |
|---|---|---|---|---|---|---|---|
| bch-t2 | 0.01% | 0.11 | 0 | 0 | 0 | 0 | 0 |
| bch-t8 | 0.03% | 0.88 | 0 | 0 | 0 | 0 | 0 |
| bch-t16 | 0.06% | 1.00 | 0 | 0 | 0 | 0 | 0 |
| bch-t32 | 0.12% | 1.00 | 0.01 | 0 | 0 | 0 | 0 |
One 64 KiB blob is a single BCH block (m=20, 80 parity bytes), so
t=32 corrects 32 bit errors per 64 KiB. At BER 1e-4 the blob already
carries ~52 errors: the cliff is between 1e-5 and 1e-4.
Pass 2 (hash-gated candidates) rescues nothing in practice:
the repo's own bch_test reports t+1 recovered 0/100 and t+2
recovered 0/100; this harness's pass2 matrix (35 rows, 875 trials,
all BCH codecs) shows rescued=0 in every setting, and a targeted
sweep (pass2_diag, m=13 t=16, k=t+1..t+8) rescues 0/50 at every k. Its mechanism (residual-BM)
addresses pass-1 miscorrection, which essentially never happens
for random errors (pass 1 fails rather than miscorrecting), and
the flip-and-redecode fallback does not reach the true codeword.
Its demonstrated value is the loud-failure guarantee: 0 silent
miscorrections in 7813 checks. The matrix numbers above are
therefore the true lzply numbers with or without pass 2.
### Spending redundancy: small-block BCH
| codec | ovh | BER 1e-4 | 1e-3 | 3e-3 |
|---|---|---|---|---|
| bch1k-t8 | 1.29% | 1.00 | 0 | 0 |
| bch1k-t16 | 2.62% | 1.00 | 0.73 | 0 |
| bch1k-t32 | 5.40% | 1.00 | 1.00 | 0.01 |
Same code, 1 KiB blocks: t=32 buys survival to BER 1e-3 at 5.4%
overhead. Bursts still kill it (256 B burst: 0.00 at every t).
### Interleaving: zero-overhead burst protection (WINNER)
Byte interleave over bch1k-t32, 5.40% overhead (unchanged):
| codec | burst 16 B | 64 B | 256 B | 1024 B | 4x64 B |
|---|---|---|---|---|---|
| bch1k-t32 (no intlv) | 0 | 0 | 0 | 0 | 0 |
| intlv-d16-t32 | 1.00 | 1.00 | 0 | 0 | 0.10 |
| intlv-d32-t32 | 1.00 | 1.00 | 0 | 0 | 0.80 |
| intlv-d64-t32 | 1.00 | 1.00 | 1.00 | 0 | 1.00 |
Random-error performance is unchanged by construction (same BCH
underneath). Even at 1.29% overhead, intlv-d64-bch1k-t8 survives
64 B bursts at 1.00. Gotcha fixed en route: a short tail group
(4 blocks of 68) was the weak point and measured 0.94 on 64 B
bursts; groups now merge the tail.
### LDPC: the random-error winner (WINNER at ~11% overhead)
| codec | ovh | BER 1e-3 | 3e-3 | 1e-2 | burst 16 B |
|---|---|---|---|---|---|
| ldpc-r90 | 10.94% | 1.00 | 0.97 | 0 | 0.24 |
| ldpc-r95 | 6.25% | 0.32 | 0 | 0 | 0 |
At BER 3e-3, ldpc-r90 recovers 0.97 where bch1k-t32 recovers 0.01
— the iterative decoder's cliff sits a decade higher in BER. But
bursts kill it (a 16 B burst is ~64 errors in one 1 KiB block),
and r95 is weak: the regular (3,64) code starts failing at 6
errors/block (ldpc_diag). Irregular LDPC would be the follow-up;
LDPC+interleave would fix bursts.
### Polar SC: dominated, rejected (honest negative)
Designing for p=1e-2 gives 0.00 at BER 1e-4; designing for the
operating point (d3/d4) gives 0.90/0.95 at 1e-4 — but every variant
is 0.00 at BER 1e-3. SC at N=4096/R=0.9 is far weaker than
bch1k-t32 (1.00 at 1e-3, half the overhead) and ldpc-r90 (1.00 at
1e-3, same overhead). Two real bugs were fixed en route (SC partial
sums overwrote the leaf decisions; see polar.c). SCL list decoding
is the follow-up that could rescue polar; SC as measured is a reject.
### UEP: graceful degradation, conditional
Exact recovery is dominated by the weak tier (uep-c1024-h32-l8 at
1e-3: 0.00, same as uniform bch1k-t8). The prefix tells another
story (uep_diag, 50 trials):
| codec | BER 1e-3 whole | BER 1e-3 prefix | burst 256 B prefix |
|---|---|---|---|
| uep-c1024-h32-l8 | 0.00 | 1.00 | 1.00 |
| uep-c4096-h32-l8 | 0.00 | 1.00 | 0.94 |
The first 1-4 KiB (lzip header + stream start) survives when the
file is lost. Only useful if lzply gains a salvage mode; today the
entry SHA gates all-or-nothing extraction.
## Speed and memory (isolated, sequential, 64 KiB blob, clean)
`--speed` mode, 5 reps each. RSS is the bench process peak (harness
+ buffers ~6.5 MB); the codec delta is what matters.
| codec | enc MB/s | dec MB/s | RSS KB | ovh |
|---|---|---|---|---|
| bch-t32 | 6.46 | 3.44 | 6564 | 0.12% |
| bch1k-t8 | 9.98 | 5.87 | 6560 | 1.29% |
| bch1k-t16 | 5.39 | 3.14 | 6492 | 2.62% |
| bch1k-t32 | 2.97 | 1.55 | 6652 | 5.40% |
| intlv-d64-t32 | 3.39 | 1.73 | 6720 | 5.40% |
| intlv-d64-t8 | 11.11 | 5.80 | 6572 | 1.29% |
| ldpc-r90 | 3.34 | 0.91 | 7776 | 10.94% |
| ldpc-r95 | 5.18 | 1.16 | 7652 | 6.25% |
| polar-r90-d4 | 4.82 | 0.58 | 7252 | 11.72% |
| uep-c1024-h32-l8 | 9.96 | 4.80 | 6612 | 1.43% |
Interleaving costs nothing measurable (same speed and memory as
the BCH underneath; it is a permutation). LDPC pays a one-time
~1.8 s init (PEG + Gauss-Jordan) and decodes ~4x slower than
bch1k-t32; polar decodes slowest of all (0.58 MB/s). Failed BCH
decodes are far slower than clean ones (pass 2 dominates; matrix
rows for failed whole-blob blocks read 0.02-0.10 MB/s).
## Generalization
Cross-corpus check (bin.lz, rand.lz, 100 trials/setting, headline
codecs, BER 1e-4/1e-3 + 256 B burst + clean) reproduces text.lz
exactly for every codec and setting: bch1k-t32 1.00/1.00/0.00,
intlv-d64-t32 1.00/1.00/1.00, ldpc-r90 1.00/1.00/0.00,
polar-r90-d4 0.94/0.00/0.00, uep-c1024 1.00/0.00/0.00. Clean
round-trips are bit-identical everywhere (all clean rows 1.00).
## Test totals
- BCH matrix (text.lz): 143 rows x 200 trials = 28,600 trials
- LDPC matrix: 22 rows x 200 = 4,400
- Polar matrix: 33 rows x 200 = 6,600
- UEP matrix: 33 rows x 200 = 6,600
- Pass-2 matrix: 35 rows x 25 = 875 (rescued 0)
- Cross-corpus: 48 rows x 100 = 4,800
- Diagnostics: ldpc_diag single-block sweeps, uep_diag prefix
survival (50 trials/setting), pass2_diag targeted sweep
(t+1..t+8, 50 trials each)
- Total matrix trials: 51,875 (+ diagnostics)
- hot_chicago verification: BLOCKED — the old-VPS tunnel's SSH
leg to 104.225.223.162 failed 4 times over ~1.5 h (banner-exchange
timeout on the last attempt). Snapshot zips are staged on the
old VPS (/tmp/lzply-*.zip) for a retry when the tunnel recovers.
## Rules of this branch
- Never touch `main` or the other coordinator's branches/checkouts.
- No Reed-Solomon (the other job's territory).
- No legacy support; the format may change freely.
- Do not break the existing `-r` levels.
- Honest negatives count: a family that loses on every axis is killed
early and its numbers recorded.
- After every push: zip snapshot to /root/git-backups/lzply/ on both
servers (newest 7 kept); use /root/scripts/git-push-snapshot.sh
when present, else temp-clone + zip + copy manually.
+158
View File
@@ -0,0 +1,158 @@
/* bch_wrap.c - BCH baseline codecs for the experiments harness.
*
* Two operating points of the same code, so the harness can show the
* overhead/correction tradeoff honestly:
*
* bch-t<N> - exactly what lzply ships: bch_poly_for_data(blob, t)
* picks the smallest parent covering the WHOLE blob, so a
* 64 KiB blob is a single huge block (m=20, t=32 -> 80
* parity bytes, 0.12% overhead, 32 correctable bits per
* 64 KiB). Pass 2 (hash-gated candidates) is wired to
* recover_verified, matching entry_decode().
* bch1k-t<N> - same code, forced small blocks: pinned m=13 poly, so a
* block holds 971 data bytes (t=32 -> 5.4% overhead).
* This is the "what if we spent real redundancy" point.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ecc_iface.h"
#include "bch.h"
#include "bch_polys.h"
#include "sha256.h"
typedef struct {
int t;
const bch_poly_t *pinned; /* NULL = auto-pick (as-shipped) */
} bch_priv_t;
static const bch_poly_t *poly_by_mt(int m, int t)
{
for (int i = 0; i < BCH_NPOLYS; i++)
if (bch_polys[i].m == m && bch_polys[i].t == t)
return &bch_polys[i];
return NULL;
}
static size_t bch_encode_fn(ecc_codec_t *c, const uint8_t *data, size_t len,
uint8_t **out)
{
bch_priv_t *p = (bch_priv_t *)c->priv;
const bch_poly_t *poly = p->pinned;
if (!poly)
poly = bch_poly_for_data(len, p->t);
if (!poly)
return 0;
size_t slen = bch_encoded_len(len, poly);
uint8_t *buf = (uint8_t *)malloc(slen ? slen : 1);
if (!buf)
return 0;
if (bch_encode(data, len, poly, buf) != slen) {
free(buf);
return 0;
}
c->overhead = len ? (double)slen / (double)len - 1.0 : 0.0;
*out = buf;
return slen;
}
static int bch_decode_fn(ecc_codec_t *c, const uint8_t *stored, size_t slen,
size_t orig_len, uint8_t *out, long *corrected)
{
bch_priv_t *p = (bch_priv_t *)c->priv;
const bch_poly_t *poly = p->pinned;
if (!poly)
poly = bch_poly_for_data(orig_len, p->t);
if (!poly)
return -1;
if (slen != bch_encoded_len(orig_len, poly))
return -1;
int corr = 0;
int rc = bch_decode(stored, slen, orig_len, poly, out, &corr);
if (corrected)
*corrected = rc == 0 ? corr : -1;
return rc;
}
static int bch_recover_fn(ecc_codec_t *c, const uint8_t *stored, size_t slen,
size_t orig_len, const uint8_t want_sha[32],
uint8_t *out)
{
bch_priv_t *p = (bch_priv_t *)c->priv;
const bch_poly_t *poly = p->pinned;
if (!poly)
poly = bch_poly_for_data(orig_len, p->t);
if (!poly)
return -1;
if (slen != bch_encoded_len(orig_len, poly))
return -1;
uint8_t *cands = (uint8_t *)malloc((size_t)BCH_PASS2_MAX_CANDS * orig_len);
if (!cands)
return -1;
int nc = bch_decode_candidates(stored, slen, orig_len, poly, cands,
BCH_PASS2_MAX_CANDS);
int found = -1;
for (int i = 0; i < nc && found < 0; i++) {
uint8_t h[32];
lzply_sha256(cands + (size_t)i * orig_len, orig_len, h);
if (memcmp(h, want_sha, 32) == 0)
found = i;
}
if (found >= 0)
memcpy(out, cands + (size_t)found * orig_len, orig_len);
free(cands);
return found >= 0 ? 0 : -1;
}
static void bch_destroy(ecc_codec_t *c)
{
free(c->priv);
free((void *)c->name);
free(c);
}
static ecc_codec_t *bch_new(int t, const bch_poly_t *pinned, const char *name)
{
ecc_codec_t *c = (ecc_codec_t *)calloc(1, sizeof(*c));
bch_priv_t *p = (bch_priv_t *)calloc(1, sizeof(*p));
if (!c || !p) {
free(c);
free(p);
return NULL;
}
p->t = t;
p->pinned = pinned;
c->name = name;
c->desc = pinned ? "BCH, forced 1 KiB blocks" : "BCH as shipped in lzply";
c->block_data = pinned ? bch_max_data(pinned) : 0;
c->encode = bch_encode_fn;
c->decode = bch_decode_fn;
c->recover_verified = bch_recover_fn;
c->destroy = bch_destroy;
c->priv = p;
return c;
}
/* As-shipped: auto-pick poly for the whole blob. */
ecc_codec_t *bch_ship_new(int t)
{
char *name = (char *)malloc(32);
if (!name)
return NULL;
snprintf(name, 32, "bch-t%d", t);
return bch_new(t, NULL, name);
}
/* Forced small blocks: pinned m=13 poly (971 data bytes/block at any t). */
ecc_codec_t *bch_1k_new(int t)
{
const bch_poly_t *poly = poly_by_mt(13, t);
if (!poly)
return NULL;
char *name = (char *)malloc(32);
if (!name)
return NULL;
snprintf(name, 32, "bch1k-t%d", t);
return bch_new(t, poly, name);
}
+10
View File
@@ -0,0 +1,10 @@
/* bch_wrap.h - constructors for the BCH baseline codecs (bch_wrap.c). */
#ifndef EXP_BCH_WRAP_H
#define EXP_BCH_WRAP_H
#include "ecc_iface.h"
ecc_codec_t *bch_ship_new(int t);
ecc_codec_t *bch_1k_new(int t);
#endif /* EXP_BCH_WRAP_H */
+338
View File
@@ -0,0 +1,338 @@
/* bench.c - corruption-matrix harness for the lzply ECC experiments.
*
* One invocation = one codec x one corruption setting x N trials.
* Each trial: take a window of the corpus blob, encode it, corrupt the
* stored bytes (random bit flips at a BER, or randomized byte bursts),
* decode, and check exact recovery (memcmp + SHA-256). On decode
* failure, the codec's recover_verified hook (if any) gets one shot
* with the expected SHA -- that is how BCH pass 2 is credited.
*
* Usage:
* bench --codec NAME --blob FILE [--size N] [--trials N] [--seed S]
* (--ber X | --burst LEN,COUNT | --clean | --speed)
* [--out results.csv]
*
* CSV (appended to --out, or stdout if omitted):
* codec,corpus,blob_size,trials,mode,param,success,rescued,rate,
* enc_MBps,dec_MBps,peak_rss_kb,overhead_pct
*
* Exit 0 on a completed run (even if recovery is 0 -- that is data),
* 2 on usage/codec errors.
*/
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <inttypes.h>
#include <time.h>
#include <libgen.h>
#include <sys/resource.h>
#include "ecc_iface.h"
#include "sha256.h"
/* ---- codec factory (one constructor per family file) ---- */
ecc_codec_t *bch_ship_new(int t);
ecc_codec_t *bch_1k_new(int t);
ecc_codec_t *interleave_new(int depth, int t);
ecc_codec_t *ldpc_new(int rate_pct);
static ecc_codec_t *make_codec(const char *name)
{
int v;
if (sscanf(name, "bch-t%d", &v) == 1)
return bch_ship_new(v);
if (sscanf(name, "bch1k-t%d", &v) == 1)
return bch_1k_new(v);
int d, t;
if (sscanf(name, "intlv-d%d-bch1k-t%d", &d, &t) == 2)
return interleave_new(d, t);
if (sscanf(name, "ldpc-r%d", &v) == 1)
return ldpc_new(v);
return NULL;
}
/* ---- xorshift64* RNG ---- */
static uint64_t rs = 0x12345678abcdefULL;
static inline uint64_t xr(void)
{
rs ^= rs << 13;
rs ^= rs >> 7;
rs ^= rs << 17;
return rs;
}
static double now_s(void)
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return ts.tv_sec + ts.tv_nsec * 1e-9;
}
static uint8_t *read_file(const char *path, size_t *len_out)
{
FILE *f = fopen(path, "rb");
if (!f)
return NULL;
fseek(f, 0, SEEK_END);
long n = ftell(f);
fseek(f, 0, SEEK_SET);
if (n <= 0) {
fclose(f);
return NULL;
}
uint8_t *buf = (uint8_t *)malloc((size_t)n);
if (!buf) {
fclose(f);
return NULL;
}
if (fread(buf, 1, (size_t)n, f) != (size_t)n) {
free(buf);
fclose(f);
return NULL;
}
fclose(f);
*len_out = (size_t)n;
return buf;
}
static void usage(void)
{
fprintf(stderr,
"usage: bench --codec NAME --blob FILE [--size N] [--trials N]\n"
" [--seed S] (--ber X | --burst LEN,COUNT | --clean | --speed)\n"
" [--out results.csv]\n"
" codecs: bch-t{2,4,8,16,32} bch1k-t{8,16,32}\n"
" intlv-d{16,32,64}-bch1k-t{8,16,32} ldpc-r{90,95}\n");
}
int main(int argc, char **argv)
{
const char *codec_name = NULL, *blob_path = NULL, *out_path = NULL;
size_t win_size = 65536;
long trials = 200;
uint64_t seed = 0x12345678abcdefULL;
enum { M_BER, M_BURST, M_CLEAN, M_SPEED } mode = M_BER;
double ber = 1e-3;
long burst_len = 256, burst_count = 1;
int nopass2 = 0;
for (int i = 1; i < argc; i++) {
if (!strcmp(argv[i], "--codec") && i + 1 < argc)
codec_name = argv[++i];
else if (!strcmp(argv[i], "--blob") && i + 1 < argc)
blob_path = argv[++i];
else if (!strcmp(argv[i], "--out") && i + 1 < argc)
out_path = argv[++i];
else if (!strcmp(argv[i], "--size") && i + 1 < argc)
win_size = (size_t)strtoull(argv[++i], NULL, 0);
else if (!strcmp(argv[i], "--trials") && i + 1 < argc)
trials = strtol(argv[++i], NULL, 0);
else if (!strcmp(argv[i], "--seed") && i + 1 < argc)
seed = strtoull(argv[++i], NULL, 0);
else if (!strcmp(argv[i], "--ber") && i + 1 < argc) {
mode = M_BER;
ber = strtod(argv[++i], NULL);
} else if (!strcmp(argv[i], "--burst") && i + 1 < argc) {
mode = M_BURST;
char *a = argv[++i];
burst_len = strtol(a, NULL, 0);
char *comma = strchr(a, ',');
burst_count = comma ? strtol(comma + 1, NULL, 0) : 1;
} else if (!strcmp(argv[i], "--nopass2")) {
nopass2 = 1;
} else if (!strcmp(argv[i], "--clean")) {
mode = M_CLEAN;
} else if (!strcmp(argv[i], "--speed")) {
mode = M_SPEED;
} else {
usage();
return 2;
}
}
if (!codec_name || !blob_path) {
usage();
return 2;
}
size_t file_len = 0;
uint8_t *file = read_file(blob_path, &file_len);
if (!file || file_len <= win_size) {
fprintf(stderr, "bench: cannot read blob %s (need > %zu bytes)\n",
blob_path, win_size);
return 2;
}
rs = seed ^ 0x9e3779b97f4a7c15ULL;
double t0 = now_s();
ecc_codec_t *c = make_codec(codec_name);
double init_s = now_s() - t0;
if (!c) {
fprintf(stderr, "bench: unknown codec %s\n", codec_name);
return 2;
}
const char *corpus = strrchr(blob_path, '/');
corpus = corpus ? corpus + 1 : blob_path;
uint8_t *win = (uint8_t *)malloc(win_size);
uint8_t *stored = NULL, *rx = NULL, *out = NULL;
uint8_t want_sha[32];
if (!win) return 2;
out = (uint8_t *)malloc(win_size);
if (!out) return 2;
long success = 0, rescued = 0;
double enc_s = 0, dec_s = 0;
double overhead = 0;
int have_overhead = 0;
if (mode == M_SPEED) {
/* encode/decode the whole file in windows, 5 passes */
long passes = 5;
size_t nw = file_len / win_size;
double te0 = now_s();
for (long p = 0; p < passes; p++)
for (size_t w = 0; w < nw; w++) {
free(stored);
stored = NULL;
size_t sl = c->encode(c, file + w * win_size, win_size, &stored);
if (!sl) {
fprintf(stderr, "bench: encode failed in speed mode\n");
return 2;
}
if (!have_overhead) {
overhead = c->overhead;
have_overhead = 1;
}
}
double te1 = now_s();
double td0 = now_s();
for (long p = 0; p < passes; p++)
for (size_t w = 0; w < nw; w++) {
size_t sl = c->encode(c, file + w * win_size, win_size, &stored);
long corr = -1;
if (c->decode(c, stored, sl, win_size, out, &corr) != 0 ||
memcmp(out, file + w * win_size, win_size) != 0) {
fprintf(stderr, "bench: speed-mode roundtrip FAILED\n");
return 2;
}
}
double td1 = now_s();
double bytes = (double)passes * nw * win_size;
double enc_mb = bytes / (te1 - te0) / 1e6;
double dec_mb = bytes / (td1 - td0) / 1e6;
struct rusage ru;
getrusage(RUSAGE_SELF, &ru);
fprintf(stderr,
"SPEED %-28s corpus=%s win=%zu init=%.2fs enc=%.1f MB/s "
"dec=%.1f MB/s rss=%ld KiB overhead=%.2f%%\n",
codec_name, corpus, win_size, init_s, enc_mb, dec_mb,
ru.ru_maxrss, overhead * 100.0);
FILE *f = out_path ? fopen(out_path, "a") : stdout;
if (f) {
fprintf(f, "%s,%s,%zu,%ld,speed,init=%.2fs,0,0,1.000,"
"%.2f,%.2f,%ld,%.4f\n",
codec_name, corpus, win_size, passes, init_s, enc_mb,
dec_mb, ru.ru_maxrss, overhead * 100.0);
if (f != stdout)
fclose(f);
}
return 0;
}
/* corruption trials */
uint64_t ber_thr = (uint64_t)(ber * 18446744073709551616.0);
rx = (uint8_t *)malloc(1 << 20); /* grown below if needed */
for (long tr = 0; tr < trials; tr++) {
size_t off = (size_t)(xr() % (file_len - win_size + 1));
memcpy(win, file + off, win_size);
lzply_sha256(win, win_size, want_sha);
double te0 = now_s();
size_t slen = c->encode(c, win, win_size, &stored);
double te1 = now_s();
if (!slen) {
fprintf(stderr, "bench: encode failed trial %ld\n", tr);
return 2;
}
if (!have_overhead) {
overhead = c->overhead;
have_overhead = 1;
}
if (tr == 0) {
free(rx);
rx = (uint8_t *)malloc(slen);
if (!rx)
return 2;
}
memcpy(rx, stored, slen);
/* corrupt the stored bytes */
if (mode == M_BER) {
for (size_t i = 0; i < slen; i++) {
uint8_t m = 0;
for (int b = 0; b < 8; b++)
if (xr() < ber_thr)
m |= (uint8_t)(1u << b);
rx[i] ^= m;
}
} else if (mode == M_BURST) {
for (long b = 0; b < burst_count; b++) {
if ((size_t)burst_len >= slen)
continue;
size_t start = (size_t)(xr() % (slen - (size_t)burst_len + 1));
for (long k = 0; k < burst_len; k++)
rx[start + k] = (uint8_t)(xr() & 0xff);
}
}
double td0 = now_s();
long corr = -1;
int rc = c->decode(c, rx, slen, win_size, out, &corr);
int ok = (rc == 0 && memcmp(out, win, win_size) == 0);
if (!ok && !nopass2 && c->recover_verified) {
if (c->recover_verified(c, rx, slen, win_size, want_sha, out) == 0) {
ok = 1;
rescued++;
}
}
double td1 = now_s();
enc_s += te1 - te0;
dec_s += td1 - td0;
if (ok)
success++;
free(stored);
stored = NULL;
}
struct rusage ru;
getrusage(RUSAGE_SELF, &ru);
double rate = trials ? (double)success / (double)trials : 0;
double enc_mb = enc_s > 0 ? (double)trials * win_size / enc_s / 1e6 : 0;
double dec_mb = dec_s > 0 ? (double)trials * win_size / dec_s / 1e6 : 0;
char param[64];
if (mode == M_BER)
snprintf(param, sizeof param, "ber=%g", ber);
else if (mode == M_BURST)
snprintf(param, sizeof param, "burst=%ldx%ld", burst_len, burst_count);
else
snprintf(param, sizeof param, "clean");
const char *mname =
mode == M_BER ? "ber" : mode == M_BURST ? "burst" : "clean";
FILE *f = out_path ? fopen(out_path, "a") : stdout;
if (f) {
fprintf(f, "%s,%s,%zu,%ld,%s,%s,%ld,%ld,%.4f,%.2f,%.2f,%ld,%.4f\n",
codec_name, corpus, win_size, trials, mname, param, success,
rescued, rate, enc_mb, dec_mb, ru.ru_maxrss,
overhead * 100.0);
if (f != stdout)
fclose(f);
}
fprintf(stderr, "%-28s %-12s %-14s %4ld trials rate=%.3f rescued=%ld "
"enc=%.0fMB/s dec=%.0fMB/s ovh=%.2f%% rss=%ldKiB\n",
codec_name, corpus, param, trials, rate, rescued, enc_mb, dec_mb,
overhead * 100.0, ru.ru_maxrss);
return 0;
}
+40
View File
@@ -0,0 +1,40 @@
/* ecc_iface.h - generic error-correction codec interface for the lzply
* experiments harness (exp/). Every family under test implements this
* interface so bench.c measures them all the same way: encode a blob,
* corrupt the stored bytes, decode, and check exact recovery (SHA-256).
*
* A codec is a whole-blob transform: encode(data) -> stored bytes,
* decode(stored) -> data or failure. Block structure inside is the
* codec's business; the harness only sees blob in / blob out.
*/
#ifndef EXP_ECC_IFACE_H
#define EXP_ECC_IFACE_H
#include <stddef.h>
#include <stdint.h>
typedef struct ecc_codec ecc_codec_t;
struct ecc_codec {
const char *name; /* short id, e.g. "bch-t32" (used in CSV output) */
const char *desc; /* human-readable description */
size_t block_data; /* nominal data bytes per code block (0 = whole blob) */
/* encode data[0..len) -> malloc'd *out; return stored length, 0 on error.
Sets c->overhead = stored/len - 1. */
size_t (*encode)(ecc_codec_t *c, const uint8_t *data, size_t len,
uint8_t **out);
/* decode stored[0..slen) -> out[0..orig_len); 0 = exact recovery,
-1 = failure. *corrected = bits/symbols corrected if known, else -1. */
int (*decode)(ecc_codec_t *c, const uint8_t *stored, size_t slen,
size_t orig_len, uint8_t *out, long *corrected);
/* Optional second-chance recovery: given the expected SHA-256 of the
original data, try harder (e.g. BCH pass-2 candidates) and use the
first candidate that verifies. 0 = rescued, -1 = not. May be NULL. */
int (*recover_verified)(ecc_codec_t *c, const uint8_t *stored,
size_t slen, size_t orig_len,
const uint8_t want_sha[32], uint8_t *out);
double overhead; /* from the last encode() call */
void (*destroy)(ecc_codec_t *c);
void *priv;
};
#endif /* EXP_ECC_IFACE_H */
+253
View File
@@ -0,0 +1,253 @@
/* interleave.c - byte interleaver over small-block BCH.
*
* The encoded stream (bch1k-t{T}: blocks of ~1 KiB data, t parity bits
* each) is permuted before it hits the channel: the stream is cut into
* groups of D consecutive blocks, each group written row-wise into a
* D-row matrix (row j = block j) and read out column-wise. A burst of
* L consecutive bytes in the channel then hits any one block at most
* ceil(L/D) bytes -- about 4*L/D bit errors, since a randomized byte
* flips ~4 bits -- instead of all L bytes landing in one block and
* killing it outright. Zero extra parity: the interleaver is a pure
* permutation, inverted on decode, so overhead is exactly the BCH
* overhead and random-error performance is unchanged. The win is
* purely burst tolerance, roughly a factor D in burst length.
*
* Groups are self-delimiting: block boundaries are recomputed from
* orig_len, so the decoder knows every group's shape. The final group
* may be short and the final block short; the column traversal simply
* skips missing cells, which keeps the permutation exact with no
* padding and no length change.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ecc_iface.h"
#include "bch.h"
#include "bch_wrap.h"
typedef struct {
ecc_codec_t *inner; /* bch1k-t{T} */
int depth; /* blocks per interleave group */
int t;
} intlv_priv_t;
/* Permute the encoded stream (forward = interleave).
* blocks[] holds the stored length of each block; nblocks total.
* out must hold the same total length.
*
* Groups: blocks are cut into groups of `depth`, EXCEPT the final
* partial group is merged into the previous one instead of standing
* alone. A tiny tail group is the weak point: a burst landing in a
* 4-block tail hits each of its blocks with L/4 bytes instead of
* L/64, which is exactly why the first measurement showed 0.94
* instead of 1.00 on 64-byte bursts (the 68-block blob ends in a
* 4-block tail). Merging makes every group >= depth (the last may
* exceed it); when nblocks <= depth there is a single group. */
static void permute(const uint8_t *in, uint8_t *out, const size_t *blocks,
size_t nblocks, int depth, int forward)
{
size_t *start = (size_t *)malloc((nblocks + 1) * sizeof(size_t));
if (!start)
return;
start[0] = 0;
for (size_t i = 0; i < nblocks; i++)
start[i + 1] = start[i] + blocks[i];
/* group boundaries: groups of `depth`, last partial group merged
into the previous one */
size_t g0 = 0;
while (g0 < nblocks) {
size_t remain = nblocks - g0;
size_t g = remain < (size_t)depth ? remain : (size_t)depth;
/* If this would leave a short tail after this group, extend
this group to absorb the tail. (Invariant: a short tail
never survives an iteration, so no group is ever < depth
except when the whole blob is.) */
if (remain > (size_t)depth && remain - (size_t)depth < (size_t)depth)
g = remain;
size_t maxlen = 0;
for (size_t j = 0; j < g; j++)
if (blocks[g0 + j] > maxlen)
maxlen = blocks[g0 + j];
size_t goff = start[g0];
size_t pos = 0;
for (size_t c = 0; c < maxlen; c++) {
for (size_t j = 0; j < g; j++) {
if (c >= blocks[g0 + j])
continue;
size_t src = start[g0 + j] + c;
size_t dst = goff + pos;
if (forward)
out[dst] = in[src];
else
out[src] = in[dst];
pos++;
}
}
g0 += g;
}
free(start);
}
static size_t intlv_encode(ecc_codec_t *c, const uint8_t *data, size_t len,
uint8_t **out)
{
intlv_priv_t *p = (intlv_priv_t *)c->priv;
uint8_t *enc = NULL;
size_t slen = p->inner->encode(p->inner, data, len, &enc);
if (!slen)
return 0;
/* block layout of the inner encoding */
size_t bd = p->inner->block_data;
size_t nblocks = (len + bd - 1) / bd;
size_t *blocks = (size_t *)malloc(nblocks * sizeof(size_t));
if (!blocks) {
free(enc);
return 0;
}
/* stored length of block i: full blocks first, last may be short.
The inner codec is bch_encode with a pinned poly, so stored
length is a pure function of the block's data length. Recover
it by splitting slen: all full blocks share one length. */
size_t off = 0;
for (size_t i = 0; i < nblocks; i++) {
size_t dlen = len - i * bd < bd ? len - i * bd : bd;
/* stored bytes for dlen data bytes under the pinned poly:
ceil((8*dlen + r)/8); r = t*13 for m=13 */
size_t r = (size_t)p->t * 13;
blocks[i] = (8 * dlen + r + 7) / 8;
off += blocks[i];
}
if (off != slen) { /* should not happen; bail out cleanly */
free(blocks);
free(enc);
return 0;
}
uint8_t *buf = (uint8_t *)malloc(slen);
if (!buf) {
free(blocks);
free(enc);
return 0;
}
permute(enc, buf, blocks, nblocks, p->depth, 1);
free(blocks);
free(enc);
c->overhead = p->inner->overhead;
*out = buf;
return slen;
}
static int intlv_decode(ecc_codec_t *c, const uint8_t *stored, size_t slen,
size_t orig_len, uint8_t *out, long *corrected)
{
intlv_priv_t *p = (intlv_priv_t *)c->priv;
size_t bd = p->inner->block_data;
size_t nblocks = (orig_len + bd - 1) / bd;
size_t *blocks = (size_t *)malloc(nblocks * sizeof(size_t));
if (!blocks)
return -1;
size_t off = 0;
for (size_t i = 0; i < nblocks; i++) {
size_t dlen = orig_len - i * bd < bd ? orig_len - i * bd : bd;
size_t r = (size_t)p->t * 13;
blocks[i] = (8 * dlen + r + 7) / 8;
off += blocks[i];
}
if (off != slen) {
free(blocks);
return -1;
}
uint8_t *deint = (uint8_t *)malloc(slen);
if (!deint) {
free(blocks);
return -1;
}
permute(stored, deint, blocks, nblocks, p->depth, 0);
free(blocks);
int rc = p->inner->decode(p->inner, deint, slen, orig_len, out,
corrected);
free(deint);
return rc;
}
static int intlv_recover(ecc_codec_t *c, const uint8_t *stored, size_t slen,
size_t orig_len, const uint8_t want_sha[32],
uint8_t *out)
{
intlv_priv_t *p = (intlv_priv_t *)c->priv;
size_t bd = p->inner->block_data;
size_t nblocks = (orig_len + bd - 1) / bd;
size_t *blocks = (size_t *)malloc(nblocks * sizeof(size_t));
if (!blocks)
return -1;
size_t off = 0;
for (size_t i = 0; i < nblocks; i++) {
size_t dlen = orig_len - i * bd < bd ? orig_len - i * bd : bd;
size_t r = (size_t)p->t * 13;
blocks[i] = (8 * dlen + r + 7) / 8;
off += blocks[i];
}
if (off != slen) {
free(blocks);
return -1;
}
uint8_t *deint = (uint8_t *)malloc(slen);
if (!deint) {
free(blocks);
return -1;
}
permute(stored, deint, blocks, nblocks, p->depth, 0);
free(blocks);
int rc = p->inner->recover_verified
? p->inner->recover_verified(p->inner, deint, slen, orig_len,
want_sha, out)
: -1;
free(deint);
return rc;
}
static void intlv_destroy(ecc_codec_t *c)
{
intlv_priv_t *p = (intlv_priv_t *)c->priv;
if (p->inner)
p->inner->destroy(p->inner);
free(p);
free((void *)c->name);
free(c);
}
ecc_codec_t *interleave_new(int depth, int t)
{
ecc_codec_t *inner = bch_1k_new(t);
if (!inner)
return NULL;
ecc_codec_t *c = (ecc_codec_t *)calloc(1, sizeof(*c));
intlv_priv_t *p = (intlv_priv_t *)calloc(1, sizeof(*p));
if (!c || !p) {
free(c);
free(p);
inner->destroy(inner);
return NULL;
}
char *name = (char *)malloc(32);
if (!name) {
free(c);
free(p);
inner->destroy(inner);
return NULL;
}
snprintf(name, 32, "intlv-d%d-bch1k-t%d", depth, t);
p->inner = inner;
p->depth = depth;
p->t = t;
c->name = name;
c->desc = "byte interleaver over small-block BCH";
c->block_data = inner->block_data;
c->encode = intlv_encode;
c->decode = intlv_decode;
c->recover_verified = intlv_recover;
c->destroy = intlv_destroy;
c->priv = p;
return c;
}
+565
View File
@@ -0,0 +1,565 @@
/* ldpc.c - regular LDPC codec for the experiments harness.
*
* Two operating points, both n=8192 bits, column weight 3:
* ldpc-r90: m=768 checks, row weight 32, k=7424 bits (928 B),
* rate 0.90625, overhead 10.34%.
* ldpc-r95: m=384 checks, row weight 64, k=7808 bits (976 B),
* rate 0.953125, overhead 4.92%.
*
* Construction: random regular parity-check matrix (configuration
* model with 4-cycle rejection), fixed seed, so the code is identical
* on every run and every server. Systematic encoding by Gauss-Jordan
* reduction of H to [I | P] (one-time, at codec creation); decoding
* is normalized min-sum belief propagation (factor 0.8), max 50
* iterations, early stop when the syndrome is zero. Channel LLR uses
* a fixed nominal crossover p0 = 1e-3 (the decoder does not know the
* true BER; this is the honest setting for a storage channel).
*
* A blob is split into blocks of k data bytes; the last block is
* zero-padded to k bytes (padding is discarded on decode). Stored
* length per block is exactly n/8 = 1024 bytes.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "ecc_iface.h"
#define LDPC_N 8192
#define LDPC_WC 3
#define LDPC_MAX_ITER 50
#define LDPC_MS_NORM 0.8f
#define LDPC_P0 1e-3
typedef struct {
int m; /* checks */
int wr; /* row weight */
int k; /* data bits */
int kbytes; /* data bytes per block */
int nedges;
int *chk_var; /* m * wr: vars of each check */
int *var_chk; /* n * wc: checks of each var */
int *chk_edge; /* m * wr: edge id (var*wc+w) of each check entry */
int *pivot_col; /* m: pivot column of each RREF row */
uint64_t *enc_rows; /* m * kwords: RREF rows over data positions */
int kwords;
int *col_of_dp; /* k: column holding data position i */
float *msg_vc; /* var->check, nedges */
float *msg_cv; /* check->var, nedges */
float *llr_ch; /* n */
uint8_t *hard; /* n */
} ldpc_t;
static void free_ldpc(ldpc_t *L)
{
if (!L)
return;
free(L->chk_var);
free(L->var_chk);
free(L->chk_edge);
free(L->pivot_col);
free(L->enc_rows);
free(L->col_of_dp);
free(L->msg_vc);
free(L->msg_cv);
free(L->llr_ch);
free(L->hard);
free(L);
}
static uint64_t lrs = 0x243f6a8885a308d3ULL;
static inline uint64_t lxr(void)
{
lrs ^= lrs << 13;
lrs ^= lrs >> 7;
lrs ^= lrs << 17;
return lrs;
}
/* ---- construction: progressive edge growth (PEG) ----
* Edge by edge, each new edge of variable node v connects to the
* check node farthest from v in the graph built so far (unreached
* checks count as infinitely far), tie-broken by lowest check degree.
* PEG never deadlocks (there is always a farthest check) and
* maximizes girth by construction -- unlike greedy 4-cycle
* rejection, which stalls in the endgame when the remaining stub
* rows all close short cycles. Fallback: if every farthest check is
* already full (cannot happen with balanced degrees, but be safe),
* take the lowest-degree check overall. */
static int build_H(ldpc_t *L, uint64_t seed)
{
int m = L->m, n = LDPC_N, wc = LDPC_WC, wr = L->wr;
int *chk_deg = (int *)calloc((size_t)m, sizeof(int));
int *var_deg = (int *)calloc((size_t)n, sizeof(int));
int *dist = (int *)malloc((size_t)(n + m) * sizeof(int));
int *queue = (int *)malloc((size_t)(n + m) * sizeof(int));
if (!chk_deg || !var_deg || !dist || !queue) {
free(chk_deg);
free(var_deg);
free(dist);
free(queue);
return -1;
}
lrs = seed;
(void)lxr; /* seed only matters for tie-breaking below */
for (int v = 0; v < n; v++) {
for (int e = 0; e < wc; e++) {
/* BFS from v over the graph built so far. Node ids:
0..n-1 variables, n..n+m-1 checks. */
for (int i = 0; i < n + m; i++)
dist[i] = -1;
int qh = 0, qt = 0;
dist[v] = 0;
queue[qt++] = v;
int found_checks = 0;
while (qh < qt && found_checks < m) {
int u = queue[qh++];
int d = dist[u];
if (u < n) {
for (int w = 0; w < var_deg[u]; w++) {
int nid = n + L->var_chk[u * wc + w];
if (dist[nid] < 0) {
dist[nid] = d + 1;
queue[qt++] = nid;
found_checks++;
}
}
} else {
int ch = u - n;
for (int k = 0; k < chk_deg[ch]; k++) {
int vv = L->chk_var[ch * wr + k];
if (dist[vv] < 0) {
dist[vv] = d + 1;
queue[qt++] = vv;
}
}
}
}
/* farthest distance among reached checks (-1 = unreached) */
int bestd = -2, have_unreached = 0;
for (int ch = 0; ch < m; ch++) {
int d = dist[n + ch];
if (d < 0) {
have_unreached = 1;
} else if (d > bestd) {
bestd = d;
}
}
int best = -1, bestdeg = wr + 1;
for (int ch = 0; ch < m; ch++) {
int d = dist[n + ch];
int far = have_unreached ? (d < 0) : (d == bestd);
if (!far)
continue;
if (chk_deg[ch] < wr && chk_deg[ch] < bestdeg) {
bestdeg = chk_deg[ch];
best = ch;
}
}
if (best < 0) {
/* fallback: lowest-degree check anywhere */
for (int ch = 0; ch < m; ch++)
if (chk_deg[ch] < wr && chk_deg[ch] < bestdeg) {
bestdeg = chk_deg[ch];
best = ch;
}
}
if (best < 0) {
free(chk_deg);
free(var_deg);
free(dist);
free(queue);
return -1;
}
L->var_chk[v * wc + var_deg[v]++] = best;
L->chk_var[best * wr + chk_deg[best]++] = v;
}
}
free(chk_deg);
free(var_deg);
free(dist);
free(queue);
return 0;
}
/* ---- Gauss-Jordan: H -> RREF, record pivot columns + enc rows ---- */
static int gauss_jordan(ldpc_t *L)
{
int m = L->m, n = LDPC_N;
int words = (n + 63) / 64;
uint64_t *H = (uint64_t *)calloc((size_t)m * words, sizeof(uint64_t));
if (!H)
return -1;
for (int r = 0; r < m; r++)
for (int k = 0; k < L->wr; k++) {
int c = L->chk_var[r * L->wr + k];
H[(size_t)r * words + c / 64] |= 1ULL << (c % 64);
}
int prow = 0;
for (int col = 0; col < n && prow < m; col++) {
int sel = -1;
for (int r = prow; r < m; r++)
if ((H[(size_t)r * words + col / 64] >> (col % 64)) & 1ULL) {
sel = r;
break;
}
if (sel < 0)
continue;
if (sel != prow) {
for (int w = 0; w < words; w++) {
uint64_t t = H[(size_t)sel * words + w];
H[(size_t)sel * words + w] = H[(size_t)prow * words + w];
H[(size_t)prow * words + w] = t;
}
}
for (int r = 0; r < m; r++) {
if (r != prow &&
((H[(size_t)r * words + col / 64] >> (col % 64)) & 1ULL)) {
for (int w = 0; w < words; w++)
H[(size_t)r * words + w] ^=
H[(size_t)prow * words + w];
}
}
L->pivot_col[prow++] = col;
}
if (prow != m) {
free(H);
return -1; /* H not full rank */
}
int *is_pivot = (int *)calloc((size_t)n, sizeof(int));
if (!is_pivot) {
free(H);
return -1;
}
for (int i = 0; i < m; i++)
is_pivot[L->pivot_col[i]] = 1;
L->col_of_dp = (int *)malloc((size_t)L->k * sizeof(int));
if (!L->col_of_dp) {
free(H);
free(is_pivot);
return -1;
}
int dp = 0;
for (int c = 0; c < n; c++)
if (!is_pivot[c])
L->col_of_dp[dp++] = c;
if (dp != L->k) {
free(H);
free(is_pivot);
return -1;
}
L->kwords = (L->k + 63) / 64;
L->enc_rows = (uint64_t *)calloc((size_t)m * L->kwords,
sizeof(uint64_t));
if (!L->enc_rows) {
free(H);
free(is_pivot);
return -1;
}
int *data_pos = (int *)malloc((size_t)n * sizeof(int));
if (!data_pos) {
free(H);
free(is_pivot);
return -1;
}
dp = 0;
for (int c = 0; c < n; c++)
data_pos[c] = is_pivot[c] ? -1 : dp++;
for (int i = 0; i < m; i++) {
for (int c = 0; c < n; c++) {
if (is_pivot[c])
continue;
if ((H[(size_t)i * words + c / 64] >> (c % 64)) & 1ULL) {
int p = data_pos[c];
L->enc_rows[(size_t)i * L->kwords + p / 64] |=
1ULL << (p % 64);
}
}
}
free(data_pos);
free(H);
free(is_pivot);
return 0;
}
/* bit helpers: MSB-first within each byte */
static inline int get_bit(const uint8_t *buf, int i)
{
return (buf[i / 8] >> (7 - (i % 8))) & 1;
}
static inline void set_bit(uint8_t *buf, int i, int v)
{
if (v)
buf[i / 8] |= (uint8_t)(1u << (7 - (i % 8)));
else
buf[i / 8] &= (uint8_t) ~(1u << (7 - (i % 8)));
}
static size_t ldpc_encode(ecc_codec_t *c, const uint8_t *data, size_t len,
uint8_t **out)
{
ldpc_t *L = (ldpc_t *)c->priv;
size_t nblocks = (len + (size_t)L->kbytes - 1) / (size_t)L->kbytes;
size_t slen = nblocks * (LDPC_N / 8);
uint8_t *buf = (uint8_t *)calloc(slen ? slen : 1, 1);
if (!buf)
return 0;
uint8_t *dbytes = (uint8_t *)calloc((size_t)L->kbytes, 1);
uint64_t *dw = (uint64_t *)malloc((size_t)L->kwords * sizeof(uint64_t));
if (!dbytes || !dw) {
free(buf);
free(dbytes);
free(dw);
return 0;
}
for (size_t b = 0; b < nblocks; b++) {
size_t dlen = len - b * (size_t)L->kbytes < (size_t)L->kbytes
? len - b * (size_t)L->kbytes
: (size_t)L->kbytes;
memset(dbytes, 0, (size_t)L->kbytes);
memcpy(dbytes, data + b * (size_t)L->kbytes, dlen);
/* data as words, bit i of the block -> word i/64, bit i%64 */
memset(dw, 0, (size_t)L->kwords * sizeof(uint64_t));
for (int i = 0; i < L->k; i++)
if (get_bit(dbytes, i))
dw[i / 64] |= 1ULL << (i % 64);
uint8_t *cw = buf + b * (LDPC_N / 8);
for (int i = 0; i < L->k; i++)
set_bit(cw, L->col_of_dp[i], get_bit(dbytes, i));
for (int i = 0; i < L->m; i++) {
const uint64_t *row = L->enc_rows + (size_t)i * L->kwords;
int acc = 0;
for (int w = 0; w < L->kwords; w++)
acc ^= __builtin_parityll(row[w] & dw[w]);
set_bit(cw, L->pivot_col[i], acc);
}
}
free(dbytes);
free(dw);
c->overhead = len ? (double)slen / (double)len - 1.0 : 0.0;
*out = buf;
return slen;
}
static int ldpc_decode_block(ldpc_t *L, const uint8_t *cw_in,
uint8_t *data_out, long *corrected_out)
{
int n = LDPC_N, m = L->m, wc = LDPC_WC, wr = L->wr;
float L0 = (float)log((1.0 - LDPC_P0) / LDPC_P0);
for (int i = 0; i < n; i++) {
L->llr_ch[i] = get_bit(cw_in, i) ? -L0 : L0;
for (int w = 0; w < wc; w++)
L->msg_vc[i * wc + w] = L->llr_ch[i];
}
int converged = 0;
for (int it = 0; it < LDPC_MAX_ITER && !converged; it++) {
/* check update: two-minimum min-sum, via chk_edge ids */
for (int j = 0; j < m; j++) {
float min1 = 1e30f, min2 = 1e30f;
int argmin1 = -1, sign = 1;
for (int k = 0; k < wr; k++) {
int e = L->chk_edge[j * wr + k];
float x = L->msg_vc[e];
float a = fabsf(x);
if (a < min1) {
min2 = min1;
min1 = a;
argmin1 = k;
} else if (a < min2) {
min2 = a;
}
if (x < 0)
sign = -sign;
}
for (int k = 0; k < wr; k++) {
int e = L->chk_edge[j * wr + k];
float x = L->msg_vc[e];
int s = sign;
if (x < 0)
s = -s;
float mag = (k == argmin1 ? min2 : min1) * LDPC_MS_NORM;
L->msg_cv[e] = s > 0 ? mag : -mag;
}
}
/* hard decision + syndrome check */
converged = 1;
for (int i = 0; i < n; i++) {
float tot = L->llr_ch[i];
for (int w = 0; w < wc; w++)
tot += L->msg_cv[i * wc + w];
L->hard[i] = tot < 0 ? 1 : 0;
}
for (int j = 0; j < m; j++) {
int p = 0;
for (int k = 0; k < wr; k++)
p ^= L->hard[L->chk_var[j * wr + k]];
if (p) {
converged = 0;
break;
}
}
if (converged)
break;
/* var->check messages for the next iteration */
for (int i = 0; i < n; i++)
for (int w = 0; w < wc; w++) {
float tot = L->llr_ch[i];
for (int w2 = 0; w2 < wc; w2++)
if (w2 != w)
tot += L->msg_cv[i * wc + w2];
L->msg_vc[i * wc + w] = tot;
}
}
if (!converged)
return -1;
long corr = 0;
for (int i = 0; i < n; i++)
if (L->hard[i] != get_bit(cw_in, i))
corr++;
if (corrected_out)
*corrected_out = corr;
int *is_pivot = (int *)calloc((size_t)n, sizeof(int));
if (!is_pivot)
return -1;
for (int i = 0; i < m; i++)
is_pivot[L->pivot_col[i]] = 1;
int dp = 0;
memset(data_out, 0, (size_t)L->kbytes);
for (int col = 0; col < n; col++)
if (!is_pivot[col])
set_bit(data_out, dp++, L->hard[col]);
free(is_pivot);
return 0;
}
static int ldpc_decode(ecc_codec_t *c, const uint8_t *stored, size_t slen,
size_t orig_len, uint8_t *out, long *corrected)
{
ldpc_t *L = (ldpc_t *)c->priv;
size_t nblocks = (orig_len + (size_t)L->kbytes - 1) / (size_t)L->kbytes;
if (slen != nblocks * (LDPC_N / 8))
return -1;
long corr = 0;
for (size_t b = 0; b < nblocks; b++) {
uint8_t *db = (uint8_t *)malloc((size_t)L->kbytes);
if (!db)
return -1;
long bc = 0;
int rc = ldpc_decode_block(L, stored + b * (LDPC_N / 8), db, &bc);
if (rc != 0) {
free(db);
if (corrected)
*corrected = -1;
return -1;
}
corr += bc;
size_t dlen = orig_len - b * (size_t)L->kbytes < (size_t)L->kbytes
? orig_len - b * (size_t)L->kbytes
: (size_t)L->kbytes;
memcpy(out + b * (size_t)L->kbytes, db, dlen);
free(db);
}
if (corrected)
*corrected = corr;
return 0;
}
static void ldpc_destroy(ecc_codec_t *c)
{
ldpc_t *L = (ldpc_t *)c->priv;
free_ldpc(L);
free((void *)c->name);
free(c);
}
ecc_codec_t *ldpc_new(int rate_pct)
{
int m, wr;
const char *tag;
if (rate_pct == 90) {
m = 768;
wr = 32;
tag = "ldpc-r90";
} else if (rate_pct == 95) {
m = 384;
wr = 64;
tag = "ldpc-r95";
} else {
return NULL;
}
ldpc_t *L = (ldpc_t *)calloc(1, sizeof(*L));
if (!L)
return NULL;
L->m = m;
L->wr = wr;
L->k = LDPC_N - m;
L->kbytes = L->k / 8;
L->nedges = LDPC_N * LDPC_WC;
L->chk_var = (int *)malloc((size_t)m * wr * sizeof(int));
L->var_chk = (int *)malloc((size_t)LDPC_N * LDPC_WC * sizeof(int));
L->chk_edge = (int *)malloc((size_t)m * wr * sizeof(int));
L->pivot_col = (int *)malloc((size_t)m * sizeof(int));
L->msg_vc = (float *)malloc((size_t)L->nedges * sizeof(float));
L->msg_cv = (float *)malloc((size_t)L->nedges * sizeof(float));
L->llr_ch = (float *)malloc((size_t)LDPC_N * sizeof(float));
L->hard = (uint8_t *)malloc((size_t)LDPC_N);
if (!L->chk_var || !L->var_chk || !L->chk_edge || !L->pivot_col ||
!L->msg_vc || !L->msg_cv || !L->llr_ch || !L->hard) {
free_ldpc(L);
return NULL;
}
int ok = -1;
int attempt_used = -1;
for (int attempt = 0; attempt < 10 && ok != 0; attempt++) {
ok = build_H(L, 0x9e3779b97f4a7c15ULL +
(uint64_t)attempt * 0x100000001b3ULL);
attempt_used = attempt;
}
if (getenv("LDPC_DEBUG"))
fprintf(stderr, "ldpc: build_H ok=%d attempts=%d\n", ok,
attempt_used + 1);
if (ok != 0) {
free_ldpc(L);
return NULL;
}
int gj = gauss_jordan(L);
if (getenv("LDPC_DEBUG"))
fprintf(stderr, "ldpc: gauss_jordan=%d\n", gj);
if (gj != 0) {
free_ldpc(L);
return NULL;
}
/* edge ids for the decoder: chk_edge[j*wr+k] = var*wc+w */
for (int j = 0; j < m; j++)
for (int k = 0; k < wr; k++) {
int v = L->chk_var[j * wr + k];
int e = -1;
for (int w = 0; w < LDPC_WC; w++)
if (L->var_chk[v * LDPC_WC + w] == j)
e = v * LDPC_WC + w;
L->chk_edge[j * wr + k] = e;
}
ecc_codec_t *c = (ecc_codec_t *)calloc(1, sizeof(*c));
if (!c) {
free_ldpc(L);
return NULL;
}
char *name = (char *)malloc(16);
if (!name) {
free_ldpc(L);
free(c);
return NULL;
}
snprintf(name, 16, "%s", tag);
c->name = name;
c->desc = "regular LDPC, min-sum belief propagation";
c->block_data = (size_t)L->kbytes;
c->encode = ldpc_encode;
c->decode = ldpc_decode;
c->recover_verified = NULL;
c->destroy = ldpc_destroy;
c->priv = L;
return c;
}
+71
View File
@@ -0,0 +1,71 @@
/* ldpc_diag.c - diagnostic for the LDPC codec (NOT part of bench).
* Encodes one fixed block, flips exactly k bits (k = 0..KMAX), decodes,
* and reports the failure count per k. This separates "decoder bug"
* (fails even at k=1..3) from "code weakness" (fails only near the
* expected threshold). Usage: ldpc_diag <r90|r95> [kmax] [trials]
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include "ecc_iface.h"
ecc_codec_t *ldpc_new(int rate_pct);
static uint64_t rs = 0xabcdef1234567ULL;
static inline uint64_t xr(void)
{
rs ^= rs << 13;
rs ^= rs >> 7;
rs ^= rs << 17;
return rs;
}
int main(int argc, char **argv)
{
int rate = 90;
int kmax = 24, trials = 100;
if (argc > 1)
rate = atoi(argv[1] + 1); /* "r90" -> 90 */
if (argc > 2)
kmax = atoi(argv[2]);
if (argc > 3)
trials = atoi(argv[3]);
ecc_codec_t *c = ldpc_new(rate);
if (!c) {
fprintf(stderr, "ldpc_new failed\n");
return 2;
}
size_t dlen = c->block_data;
uint8_t *data = (uint8_t *)malloc(dlen);
uint8_t *out = (uint8_t *)malloc(dlen);
for (size_t i = 0; i < dlen; i++)
data[i] = (uint8_t)(xr() & 0xff);
uint8_t *stored = NULL;
size_t slen = c->encode(c, data, dlen, &stored);
if (!slen) {
fprintf(stderr, "encode failed\n");
return 2;
}
printf("rate=%d block_data=%zu stored=%zu overhead=%.2f%%\n", rate,
dlen, slen, c->overhead * 100.0);
uint8_t *rx = (uint8_t *)malloc(slen);
for (int k = 0; k <= kmax; k++) {
int fails = 0;
for (int t = 0; t < trials; t++) {
memcpy(rx, stored, slen);
/* flip k distinct random bits */
for (int f = 0; f < k; f++) {
size_t p = (size_t)(xr() % (slen * 8));
rx[p / 8] ^= (uint8_t)(1u << (7 - (p % 8)));
}
long corr = -1;
int rc = c->decode(c, rx, slen, dlen, out, &corr);
if (rc != 0 || memcmp(out, data, dlen) != 0)
fails++;
}
printf("k=%2d fails=%d/%d\n", k, fails, trials);
fflush(stdout);
}
return 0;
}
+27
View File
@@ -0,0 +1,27 @@
#!/bin/bash
# mkcorpora.sh - build the experiment corpora in exp/corpora/.
# text.raw / text.lz : English-ish text (docs + sources)
# bin.raw / bin.lz : ELF binaries
# rand.raw / rand.lz : seeded pseudo-random bytes (incompressible)
# lz files are lzip -9 of the raw files: that is what lzply actually
# protects (the compressed blob), plus the raw files for stored entries.
set -e
cd "$(dirname "$0")/corpora"
# text: repo docs/sources + system docs
{ find /opt/lzply-exp-ecc -name "*.md" -o -name "*.c" -o -name "*.h" | sort | xargs cat
find /usr/share/doc -type f -size -200k 2>/dev/null | head -200 | sort | xargs cat 2>/dev/null
find /usr/include -name "*.h" 2>/dev/null | head -300 | sort | xargs cat 2>/dev/null
} > text.raw
head -c 4194304 text.raw > text4m.raw && mv text4m.raw text.raw
# binaries: ELF files from /bin and /usr/bin
{ for f in /bin/* /usr/bin/*; do
[ -f "$f" ] && head -c1 "$f" | grep -q . && file "$f" 2>/dev/null | grep -q ELF && cat "$f"
done
} > bin.raw 2>/dev/null
head -c 4194304 bin.raw > bin4m.raw && mv bin4m.raw bin.raw
# random: seeded python (reproducible on both servers)
python3 -c "import random; random.seed(1234); open(\"rand.raw\",\"wb\").write(bytes(random.getrandbits(8) for _ in range(4194304)))"
for f in text bin rand; do
lzip -9 -f -c "$f.raw" > "$f.lz" 2>/dev/null || lzip -9 -c "$f.raw" > "$f.lz"
done
ls -la
+89
View File
@@ -0,0 +1,89 @@
/* pass2_diag.c - targeted test of BCH pass-2 (hash-gated candidates).
* Encodes one bch1k block, flips exactly k bits (k around t), and
* reports: pass-1 success, and pass-2 rescue (candidate verifies
* against the SHA-256 of the original). This separates "pass 2 is
* weak" from "the harness wiring is broken".
* Usage: pass2_diag <t> [kmax] [trials]
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include "bch.h"
#include "bch_polys.h"
#include "sha256.h"
static uint64_t rs = 0xabcdef1234567ULL;
static inline uint64_t xr(void)
{
rs ^= rs << 13;
rs ^= rs >> 7;
rs ^= rs << 17;
return rs;
}
static const bch_poly_t *poly_by_mt(int m, int t)
{
for (int i = 0; i < BCH_NPOLYS; i++)
if (bch_polys[i].m == m && bch_polys[i].t == t)
return &bch_polys[i];
return NULL;
}
int main(int argc, char **argv)
{
int t = argc > 1 ? atoi(argv[1]) : 16;
int kmax = argc > 2 ? atoi(argv[2]) : t + 8;
int trials = argc > 3 ? atoi(argv[3]) : 50;
const bch_poly_t *p = poly_by_mt(13, t);
if (!p) {
fprintf(stderr, "no poly m=13 t=%d\n", t);
return 2;
}
size_t dlen = bch_max_data(p);
size_t slen = bch_block_stored_len(dlen, p);
uint8_t *data = (uint8_t *)malloc(dlen);
uint8_t *stored = (uint8_t *)malloc(slen);
uint8_t *rx = (uint8_t *)malloc(slen);
uint8_t *out = (uint8_t *)malloc(dlen);
uint8_t *cands = (uint8_t *)malloc((size_t)BCH_PASS2_MAX_CANDS * dlen);
for (size_t i = 0; i < dlen; i++)
data[i] = (uint8_t)(xr() & 0xff);
if (bch_encode_block(data, dlen, p, stored) != 0) {
fprintf(stderr, "encode failed\n");
return 2;
}
uint8_t want[32];
lzply_sha256(data, dlen, want);
printf("t=%d block_data=%zu stored=%zu\n", t, dlen, slen);
for (int k = t - 2; k <= kmax; k++) {
int p1 = 0, rescued = 0;
for (int tr = 0; tr < trials; tr++) {
memcpy(rx, stored, slen);
for (int f = 0; f < k; f++) {
size_t pos = (size_t)(xr() % (slen * 8));
rx[pos / 8] ^= (uint8_t)(1u << (7 - (pos % 8)));
}
int corr = -1;
if (bch_decode_block(rx, slen, dlen, p, out, &corr) == 0 &&
memcmp(out, data, dlen) == 0) {
p1++;
continue;
}
int nc = bch_decode_block_candidates(rx, slen, dlen, p, cands,
BCH_PASS2_MAX_CANDS);
for (int i = 0; i < nc; i++) {
uint8_t h[32];
lzply_sha256(cands + (size_t)i * dlen, dlen, h);
if (memcmp(h, want, 32) == 0) {
rescued++;
break;
}
}
}
printf("k=%2d pass1=%d/%d rescued=%d/%d\n", k, p1, trials, rescued,
trials);
fflush(stdout);
}
return 0;
}
+21
View File
@@ -0,0 +1,21 @@
#!/bin/bash
# run_matrix.sh - full corruption matrix for a list of codecs.
# Usage: run_matrix.sh <corpus> <blobsize> <trials> <outfile> <codec...>
# Each codec x setting is its own bench invocation; xargs -P spreads
# them over all cores. Pass 2 is OFF for the matrix (too slow at scale);
# rescue rates are measured separately by run_pass2.sh.
set -u
CORPUS="$1"; SIZE="$2"; TRIALS="$3"; OUT="$4"; shift 4
mkdir -p "$(dirname "$OUT")"
{
for CODEC in "$@"; do
for BER in 1e-5 1e-4 1e-3 3e-3 1e-2; do
echo "./bench --codec $CODEC --blob $CORPUS --size $SIZE --trials $TRIALS --ber $BER --nopass2 --out $OUT"
done
for B in "16,1" "64,1" "256,1" "1024,1" "64,4"; do
echo "./bench --codec $CODEC --blob $CORPUS --size $SIZE --trials $TRIALS --burst $B --nopass2 --out $OUT"
done
echo "./bench --codec $CODEC --blob $CORPUS --size $SIZE --trials $TRIALS --clean --out $OUT"
done
} | xargs -P "$(nproc)" -I CMD sh -c 'CMD 2>>results/matrix.log'
echo "matrix done: $OUT"
+18
View File
@@ -0,0 +1,18 @@
#!/bin/bash
# run_pass2.sh - BCH pass-2 rescue rates, small trial count (pass 2 is
# slow; 25 trials per setting is enough to see rescues).
# Usage: run_pass2.sh <corpus> <blobsize> <trials> <outfile> <codec...>
set -u
CORPUS="$1"; SIZE="$2"; TRIALS="$3"; OUT="$4"; shift 4
mkdir -p "$(dirname "$OUT")"
{
for CODEC in "$@"; do
for BER in 1e-4 1e-3 3e-3; do
echo "./bench --codec $CODEC --blob $CORPUS --size $SIZE --trials $TRIALS --ber $BER --out $OUT"
done
for B in "64,1" "256,1"; do
echo "./bench --codec $CODEC --blob $CORPUS --size $SIZE --trials $TRIALS --burst $B --out $OUT"
done
done
} | xargs -P "$(nproc)" -I CMD sh -c 'CMD 2>>results/pass2.log'
echo "pass2 done: $OUT"
+32
View File
@@ -0,0 +1,32 @@
# experiments/Makefile - prototypes for the lzply compression research.
# Built with max cores via -j; each tool is standalone: `tool c in out`,
# `tool d in out`. Shared rANS core in rans.o.
CC = gcc
CFLAGS = -O3 -Wall -Wextra -march=native
LDLIBS = -llz -lm
TOOLS = rans_tool dict bchcheck
all: $(TOOLS)
rans.o: rans.c rans.h
$(CC) $(CFLAGS) -c -o $@ rans.c
rans_tool: rans_tool.o rans.o
$(CC) $(CFLAGS) -o $@ rans_tool.o rans.o
dict.o: dict.c
$(CC) $(CFLAGS) -c -o $@ dict.c
dict: dict.o
$(CC) $(CFLAGS) -o $@ dict.o
bchcheck.o: bchcheck.c ../bch.h
$(CC) $(CFLAGS) -I.. -c -o $@ bchcheck.c
bchcheck: bchcheck.o ../bch.o ../bch_polys.h
$(CC) $(CFLAGS) -o $@ bchcheck.o ../bch.o
clean:
rm -f $(TOOLS) *.o
.PHONY: all clean
+140
View File
@@ -0,0 +1,140 @@
# lzply compression experiments (branch experiments/comp)
> Integrated onto current main (`experiments/integration`, LZPL v5):
> the winners here are the dictionary transform (code-only) and the
> rANS core as infrastructure. lzrans, BWT, and PPM were measured,
> rejected, and their code was NOT carried over — see
> `docs/INTEGRATION.md`.
Prototypes for open-ended compression research. Each tool is standalone:
`tool c|o in out`, `tool d in out`. Shared rANS core in rans.[ch].
`bench.py <name> <enc> <dec> [corpora...]` times (best of 3), sizes,
and sha256-verifies round-trips; `bench1.py` is the single-run variant
(for slow tools); CSVs land in results/.
## Corpora (built by mkcorpora.py, deterministic per machine)
- text: 8 MiB UTF-8 docs from /usr/share/doc + common-licenses
- code: 8 MiB C headers (/usr/include) + this repo's sources
- bin: 8 MiB ELF binaries from /bin + /usr/bin
- mixed: 8 MiB round-robin 64 KiB chunks of text+code+bin
- rand: 4 MiB /dev/urandom (seed 1234), incompressible control
Corpora are NOT committed (regenerate with mkcorpora.py).
All ratios below are compressed/orig %; speeds are MB/s (orig bytes).
## Baseline: lzip (the current lzply stage; same liblz, same levels)
| tool | text | code | bin | mixed | rand | enc MB/s | dec MB/s |
|---|---|---|---|---|---|---|---|
| lzip -1 | 6.22 | 15.13 | 37.83 | 21.58 | 101.36 | 1.4-9.1 | 8.9-71.8 |
| lzip -6 | 3.56 | 9.38 | 32.61 | 17.41 | 101.36 | 0.9-2.3 | 7.9-71.4 |
| lzip -9 | 3.44 | 9.05 | 32.53 | 17.17 | 101.36 | 0.8-1.4 | 9.0-70.3 |
References: xz -6 ~= lzip -6 (text 3.51, code 9.20, bin 32.59,
mixed 17.30); zstd -19 text 3.63, code 9.48, bin 34.81, mixed 18.31;
gzip -9 text 23.48, code 16.40, bin 44.14, mixed 30.06;
bzip2 -9 text 9.25, code 12.55, bin 40.22, mixed 23.53,
dec only 5-9 MB/s.
## ANS: rANS order-0 (rans_tool) — REJECT as standalone, KEEP core
Static per-file freqs, 12-bit probs. Enc 30-38 MB/s, dec 47-62 MB/s,
RSS ~20 MB, but no LZ stage: text 64.40, code 67.62, bin 77.14,
mixed 78.11, rand 100.46. The core is the entropy stage for the BWT
and LZ prototypes below. (Two real bugs found and fixed in the core:
renormalisation threshold must be (L>>12)*f<<8 or the decoder
over-reads; the emitted stream can exceed n bytes, scratch is 2n+64.)
## LZ77 + rANS (lzrans) — REJECT as a lzip replacement
Hash-chain finder, 1 MiB window, lazy (`c`) and optimal-parse (`o`)
modes, deflate-style length codes, log2 distance codes, litlen/dist
rANS streams + raw extra bits.
| mode | text | code | bin | mixed | rand | enc | dec | RSS |
|---|---|---|---|---|---|---|---|---|
| lazy | 6.26 | 13.52 | 41.84 | 23.15 | 100.48 | 0.5-4.4 | 26-73 | 44 MB |
| optimal | 6.19 | 13.05 | — | — | — | 0.4-1.0 | 64-73 | 173 MB |
Optimal parsing recovers only ~1-3% relative, so the gap is not
parsing: it is LZMA's adaptive context entropy model plus deeper
match search and a larger dictionary. A static-table rANS cannot
close a ~75% relative gap on text.
## BWT + MTF + run tokens + rANS (bwt) — REJECT as a lzip replacement
Suffix array by cyclic doubling (see the linear-vs-rotation trap
below), MTF, runs >=4 tokenised as (value, 256, k), 257-symbol rANS.
| corpus | ratio | enc | dec |
|---|---|---|---|
| text | 6.35 | 177 s (0.05 MB/s) | 5.3 MB/s |
| code | 12.31 | 173 s | 6.3 MB/s |
| bin | 42.76 | 137 s | 5.9 MB/s |
| mixed | (bench running) | | |
| rand | (bench running) | | |
RSS ~200 MB. Beats bzip2 on text (6.35 vs 9.25), ~ties on code
(12.31 vs 12.55), loses on bin (42.76 vs 40.22); loses to lzip
everywhere by a wide margin. Encode is ~3 min/8 MB (doubling SA is
memory-latency-bound over 160 MB of rank arrays); decode is 5-6 MB/s
(LF-walk random access).
GOTCHA (real bug, fixed): a linear suffix sort is NOT rotation
order — "a" < "a bandana" linearly, but cyclically
"a bandanabanan" < "abanana bandan". A sentinel does not fix it
("a$" < "a bandana$" truncates the comparison). The SA must use
cyclic doubling (rank[(i+k) % n]).
## PPM order-2 + arithmetic coding (ppm) — REJECT
Order-2/1/0 contexts, escape mass = distinct-symbol count,
Witten-Neal-Cleary 32-bit arithmetic coder, counts updated in all
levels after every symbol. RSS ~80 MB.
| corpus | ratio | enc MB/s | dec MB/s |
|---|---|---|---|
| text | 32.84 | 6.3 | 3.9 |
| code | 30.82 | 6.3 | 4.1 |
| mixed | 39.18 | 4.8 | 3.2 |
Far behind lzip and slow: the bit-level coder plus 256-wide level
scans cost ~6 MB/s encode, ~4 MB/s decode. A simple order-2 PPM
with heavy escape mass is nowhere near PPMd-class.
## Dictionary transform + lzip (dict) — CONDITIONAL, code only
Per-file word dictionary (top 4096 words by saving, transmitted in
the header), words -> 3-byte codes, then lzip -6. RSS ~32 MB.
| corpus | dict+lzip6 | plain lzip6 | delta |
|---|---|---|---|
| text | 3.58 | 3.56 | +0.5% worse |
| code | 9.19 | 9.38 | -2.1% BETTER |
| bin | 33.30 | 32.61 | +2.1% worse |
| mixed | 17.65 | 17.41 | +1.4% worse |
| rand | 101.73 | 101.36 | worse |
Only code wins (+2.1%): long repeated identifiers survive as codes
better than as LZ matches. Everywhere else the dictionary costs
more than it saves (lzip already captures word repeats). Not a
default; a code-only optional preprocessing stage at most.
(Gotcha fixed during the build: words are sorted by count, so the
saving filter must `continue`, not `break`, or a short frequent
word like "the" discards the whole dictionary.)
## BCH end-to-end (bchcheck) — winners survive error correction
Blob -> BCH(t=8, lzply -e 4 level) -> flip N bits -> decode ->
decompress -> sha256 check.
- dict+lzip code blob (770,519 B): poly 0050, stored 770,563
(+44 B parity, 0.006%). 8 flips -> 8 corrected, full pipeline
recovers bit-identical. 32 flips -> decode FAIL (exceeds t=8 per
block; honest failure mode).
- plain lzip6 code blob (787,213 B): 8 flips -> 8 corrected,
recovered + decoded bit-identical.
## Verdicts (bottom line)
- No family beats lzip on ratio. lzip/LZMA's adaptive entropy
model + deep match search + large dictionary is very hard to beat
with a from-scratch prototype in this scope.
- KEEP: the rANS core (fast, correct, reusable as an entropy stage).
- CONDITIONAL: dict transform, code-only (+2.1% on code).
- REJECT: lzrans (lazy + optimal), BWT, PPM order-2, rANS order-0
standalone. Honest negatives, numbers above.
- Test totals: 334 timed bench invocations, all sha256-verified OK
(plus ~25 manual small-input round-trips and 3 BCH runs: 2 pass,
1 expected fail at 32 flips).
## Notes / environment
- hot_newyork (172.93.49.176), 8 cores, 30 GB RAM; server load was
10-17 during the runs (shared with other agents), so absolute
MB/s figures are load-dependent; ratios are exact.
- hot_chicago verification pending: its SSH stopped accepting new
sessions Dec 2 (sshd can't fork under load); a retry agent is
probing every 15 min. No Chicago numbers yet.
- The other lz_rs/deep-repair coordinator works in /opt/lzply/src
and /root/lzrs-verify/lzply; untouched by this work. No
Reed-Solomon was (re-)implemented here.
+88
View File
@@ -0,0 +1,88 @@
/* bchcheck.c - BCH end-to-end corruption test for experiment blobs.
* Takes a compressed blob, BCH-encodes it (t=8 by default, the lzply
* -e 4 level; largest t=8 poly if the blob exceeds one m=22 block),
* flips N random bits (seeded), decodes, and writes the recovered
* blob. Exit 0 if the recovered blob is byte-identical to the input,
* 1 if decode failed or the blob differs, 2 on usage/IO error.
* Usage: bchcheck blob nflips seed out [t]
* The caller then decompresses `out` with the prototype and checks
* the sha256 round-trip, proving the compressed stream survives BCH.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include "bch.h"
static uint8_t *slurp(const char *path, size_t *n) {
FILE *f = fopen(path, "rb");
if (!f) { perror(path); exit(2); }
fseek(f, 0, SEEK_END);
long sz = ftell(f);
fseek(f, 0, SEEK_SET);
uint8_t *b = malloc(sz ? (size_t)sz : 1);
if (!b) exit(2);
if (sz && fread(b, 1, (size_t)sz, f) != (size_t)sz) exit(2);
fclose(f);
*n = (size_t)sz;
return b;
}
/* Largest-capacity poly with the requested t (m=22 wins). */
static const bch_poly_t *largest_t_poly(int t) {
const bch_poly_t *best = NULL;
size_t bestcap = 0;
for (uint16_t id = 0x0001; id <= 0x0052; id++) {
const bch_poly_t *p = bch_poly_by_id(id);
if (!p || p->t != t) continue;
size_t cap = bch_max_data(p);
if (cap > bestcap) { bestcap = cap; best = p; }
}
return best;
}
int main(int argc, char **argv) {
if (argc < 5 || argc > 6) {
fprintf(stderr, "usage: %s blob nflips seed out [t]\n", argv[0]);
return 2;
}
int t = argc == 6 ? atoi(argv[5]) : 8;
long nflips = atol(argv[2]);
unsigned seed = (unsigned)atoi(argv[3]);
size_t n;
uint8_t *blob = slurp(argv[1], &n);
const bch_poly_t *poly = bch_poly_for_data(n, t);
if (!poly) poly = largest_t_poly(t);
if (!poly) { fprintf(stderr, "bchcheck: no poly for t=%d\n", t); return 2; }
size_t slen = bch_encoded_len(n, poly);
uint8_t *stored = malloc(slen ? slen : 1);
uint8_t *rec = malloc(n ? n : 1);
if (!stored || !rec) return 2;
if (bch_encode(blob, n, poly, stored) != slen) {
fprintf(stderr, "bchcheck: encode failed\n");
return 2;
}
/* xorshift64 PRNG for flip positions (seeded, deterministic) */
uint64_t xs = (uint64_t)seed * 0x9E3779B97F4A7C15ULL + 0x123456789ULL;
for (long k = 0; k < nflips; k++) {
xs ^= xs << 13; xs ^= xs >> 7; xs ^= xs << 17;
size_t bit = (size_t)(xs % (uint64_t)(slen * 8));
stored[bit / 8] ^= (uint8_t)(0x80u >> (bit % 8));
}
int corrected = 0;
int rc = bch_decode(stored, slen, n, poly, rec, &corrected);
fprintf(stderr, "bchcheck: poly=%04x blob=%zu stored=%zu overhead=%.1f%% "
"flips=%ld corrected=%d decode=%s\n",
poly->id, n, slen, 100.0 * (double)(slen - n) / (double)n,
nflips, corrected, rc == 0 ? "OK" : "FAIL");
if (rc != 0) return 1;
FILE *f = fopen(argv[4], "wb");
if (!f) { perror(argv[4]); return 2; }
if (n && fwrite(rec, 1, n, f) != n) return 2;
fclose(f);
if (memcmp(blob, rec, n) != 0) {
fprintf(stderr, "bchcheck: recovered blob DIFFERS\n");
return 1;
}
return 0;
}
+84
View File
@@ -0,0 +1,84 @@
#!/usr/bin/env python3
"""bench.py <name> <enc-template> <dec-template> [corpus...]
Templates use {in} {out} {dec}; run via /bin/sh. Times encode/decode
(wall, best of 3 for encode, best of 3 for decode), records ratio,
MB/s, sha256 round-trip. Appends CSV rows to results/<name>.csv and
prints a table. Encode failure on a corpus records 'FAIL'.
"""
import subprocess, sys, os, time, hashlib, csv
EXP = os.path.dirname(os.path.abspath(__file__))
CORP = os.path.join(EXP, "corpora")
RES = os.path.join(EXP, "results")
TMP = "/tmp/expbench"
os.makedirs(TMP, exist_ok=True)
os.makedirs(RES, exist_ok=True)
def sha(p):
h = hashlib.sha256()
with open(p, "rb") as fh:
for c in iter(lambda: fh.read(1 << 20), b""):
h.update(c)
return h.hexdigest()
def run(cmd, timeout=600):
t0 = time.perf_counter()
r = subprocess.run(cmd, shell=True, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, timeout=timeout)
return r.returncode, time.perf_counter() - t0
def bench_one(name, enc, dec, corpus):
src = os.path.join(CORP, corpus)
n = os.path.getsize(src)
want = sha(src)
out = os.path.join(TMP, name + ".out")
decf = os.path.join(TMP, name + ".dec")
for f in (out, decf):
if os.path.exists(f):
os.unlink(f)
best_enc = None
for _ in range(3):
rc, dt = run(enc.format(**{"in": src, "out": out, "dec": decf}))
if rc != 0:
return (corpus, n, None, None, None, "ENCFAIL")
best_enc = dt if best_enc is None else min(best_enc, dt)
csize = os.path.getsize(out)
best_dec = None
for _ in range(3):
if os.path.exists(decf):
os.unlink(decf)
rc, dt = run(dec.format(**{"in": src, "out": out, "dec": decf}))
if rc != 0:
return (corpus, n, csize, None, None, "DECFAIL")
best_dec = dt if best_dec is None else min(best_dec, dt)
ok = sha(decf) == want
return (corpus, n, csize, best_enc, best_dec, "OK" if ok else "MISMATCH")
def main():
name, enc, dec = sys.argv[1], sys.argv[2], sys.argv[3]
corpora = sys.argv[4:] or ["text", "code", "bin", "mixed", "rand"]
csvp = os.path.join(RES, name + ".csv")
new = not os.path.exists(csvp)
print(f"== {name}: enc=[{enc}] dec=[{dec}]")
print(f"{'corpus':8s} {'orig':>9s} {'comp':>9s} {'ratio%':>7s} {'encMB/s':>8s} {'decMB/s':>8s} status")
with open(csvp, "a", newline="") as fh:
w = csv.writer(fh)
if new:
w.writerow(["tool", "corpus", "orig", "comp", "ratio_pct",
"enc_s", "dec_s", "enc_MBs", "dec_MBs", "status"])
for c in corpora:
corpus, n, cs, es, ds, st = bench_one(name, enc, dec, c)
if cs is None:
print(f"{c:8s} {n:9d} {'-':>9s} {'-':>7s} {'-':>8s} {'-':>8s} {st}")
w.writerow([name, c, n, "", "", "", "", "", "", st])
continue
ratio = 100.0 * cs / n
emb = n / 1e6 / es if es else 0
dmb = n / 1e6 / ds if ds else 0
print(f"{c:8s} {n:9d} {cs:9d} {ratio:7.2f} {emb:8.1f} {dmb:8.1f} {st}")
w.writerow([name, c, n, cs, f"{ratio:.2f}", f"{es:.3f}", f"{ds:.3f}",
f"{emb:.1f}", f"{dmb:.1f}", st])
print("csv: " + csvp)
if __name__ == "__main__":
main()
+71
View File
@@ -0,0 +1,71 @@
#!/usr/bin/env python3
"""bench1.py: single-run variant of bench.py (for slow tools like bwt).
Usage: bench1.py <name> <enc-template> <dec-template> [corpus...]
Appends to results/<name>.csv and prints one line per corpus."""
import subprocess, sys, os, time, hashlib, csv
EXP = os.path.dirname(os.path.abspath(__file__))
CORP = os.path.join(EXP, "corpora")
RES = os.path.join(EXP, "results")
TMP = "/tmp/expbench"
os.makedirs(TMP, exist_ok=True)
os.makedirs(RES, exist_ok=True)
def sha(p):
h = hashlib.sha256()
with open(p, "rb") as fh:
for c in iter(lambda: fh.read(1 << 20), b""):
h.update(c)
return h.hexdigest()
def run(cmd, timeout=3600):
t0 = time.perf_counter()
r = subprocess.run(cmd, shell=True, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, timeout=timeout)
return r.returncode, time.perf_counter() - t0
def main():
name, enc, dec = sys.argv[1], sys.argv[2], sys.argv[3]
corpora = sys.argv[4:] or ["text", "code", "bin", "mixed", "rand"]
csvp = os.path.join(RES, name + ".csv")
new = not os.path.exists(csvp)
print(f"== {name} (single run)", flush=True)
with open(csvp, "a", newline="") as fh:
w = csv.writer(fh)
if new:
w.writerow(["tool", "corpus", "orig", "comp", "ratio_pct",
"enc_s", "dec_s", "enc_MBs", "dec_MBs", "status"])
for c in corpora:
src = os.path.join(CORP, c)
n = os.path.getsize(src)
want = sha(src)
out = os.path.join(TMP, name + ".out")
decf = os.path.join(TMP, name + ".dec")
for f in (out, decf):
if os.path.exists(f):
os.unlink(f)
rc, es = run(enc.format(**{"in": src, "out": out, "dec": decf}))
if rc != 0:
print(f"{c}: ENCFAIL", flush=True)
w.writerow([name, c, n, "", "", "", "", "", "", "ENCFAIL"])
continue
cs = os.path.getsize(out)
if os.path.exists(decf):
os.unlink(decf)
rc, ds = run(dec.format(**{"in": src, "out": out, "dec": decf}))
if rc != 0:
print(f"{c}: DECFAIL", flush=True)
w.writerow([name, c, n, cs, "", "", "", "", "", "DECFAIL"])
continue
ok = sha(decf) == want
st = "OK" if ok else "MISMATCH"
ratio = 100.0 * cs / n
print(f"{c:8s} {n:9d} {cs:9d} {ratio:6.2f}% enc {es:7.1f}s "
f"({n/1e6/es:5.1f} MB/s) dec {ds:6.1f}s ({n/1e6/ds:5.1f} MB/s) {st}",
flush=True)
w.writerow([name, c, n, cs, f"{ratio:.2f}", f"{es:.3f}", f"{ds:.3f}",
f"{n/1e6/es:.1f}", f"{n/1e6/ds:.1f}", st])
print("csv: " + csvp, flush=True)
if __name__ == "__main__":
main()
+260
View File
@@ -0,0 +1,260 @@
/* dict.c - word-dictionary transform (preprocessing stage for lzip).
* Builds a per-file dictionary of the most frequent words (alnum runs
* of length >= 3), replaces them with 2-byte codes, then the caller
* pipes the output through lzip. The dictionary is transmitted in
* the header, so the cost is honest.
* Format: magic "DICT", u32 orig_len, u16 ndict, then ndict entries
* (u8 len, bytes), then the transformed stream: 0xFF escape byte
* introduces a 2-byte code (little-endian); a literal 0xFF in the
* data is escaped as 0xFF 0xFF 0xFF (escape + code 0xFFFF = literal
* 0xFF); other bytes pass through. Words are maximal [A-Za-z0-9_]
* runs; only words in the dictionary are replaced.
* Usage: dict c in out | dict d in out
* (then: lzip -6 transformed; decode: lzip -d | dict d)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#define ESC 0xFF
#define MAX_DICT 4096
#define MIN_WORD 3
static uint8_t *slurp(const char *path, size_t *n) {
FILE *f = fopen(path, "rb");
if (!f) { perror(path); exit(2); }
fseek(f, 0, SEEK_END);
long sz = ftell(f);
fseek(f, 0, SEEK_SET);
uint8_t *b = malloc(sz ? (size_t)sz : 1);
if (!b) exit(2);
if (sz && fread(b, 1, (size_t)sz, f) != (size_t)sz) exit(2);
fclose(f);
*n = (size_t)sz;
return b;
}
static void spit(const char *path, const uint8_t *b, size_t n) {
FILE *f = fopen(path, "wb");
if (!f) { perror(path); exit(2); }
if (n && fwrite(b, 1, n, f) != n) exit(2);
fclose(f);
}
static int is_word(int c) {
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||
(c >= '0' && c <= '9') || c == '_';
}
/* word table entry */
typedef struct { char *w; uint32_t count; } went_t;
static int cmp_count(const void *a, const void *b) {
uint32_t ca = ((const went_t *)a)->count, cb = ((const went_t *)b)->count;
return ca < cb ? 1 : ca > cb ? -1 : 0;
}
static uint32_t hash_str(const char *s, size_t n) {
uint32_t h = 2166136261u;
for (size_t i = 0; i < n; i++) { h ^= (uint8_t)s[i]; h *= 16777619u; }
return h;
}
static int encode(const char *inpath, const char *outpath) {
size_t n;
uint8_t *in = slurp(inpath, &n);
/* count words in a hash table (open addressing) */
size_t hcap = 1 << 20;
went_t *ht = calloc(hcap, sizeof *ht);
if (!ht) return 2;
size_t i = 0;
while (i < n) {
if (!is_word(in[i])) { i++; continue; }
size_t j = i;
while (j < n && is_word(in[j])) j++;
size_t len = j - i;
if (len >= MIN_WORD) {
uint32_t h = hash_str((char *)in + i, len) & (hcap - 1);
while (ht[h].w) {
if (strlen(ht[h].w) == len &&
memcmp(ht[h].w, in + i, len) == 0) break;
h = (h + 1) & (hcap - 1);
}
if (!ht[h].w) {
ht[h].w = malloc(len + 1);
memcpy(ht[h].w, in + i, len);
ht[h].w[len] = 0;
}
ht[h].count++;
}
i = j;
}
/* collect, sort by count, keep the top MAX_DICT by SAVING:
* saving = count * (len - 3) - (len + 1) [dict cost]; keep > 0 */
went_t *all = malloc(hcap * sizeof *all);
size_t na = 0;
for (size_t k = 0; k < hcap; k++)
if (ht[k].w) all[na++] = ht[k];
qsort(all, na, sizeof *all, cmp_count);
went_t *dict = malloc(MAX_DICT * sizeof *dict);
size_t nd = 0;
for (size_t k = 0; k < na && nd < MAX_DICT; k++) {
size_t len = strlen(all[k].w);
/* code costs 3 bytes (ESC + 2), word costs len; saving per
* occurrence = len - 3; dict entry costs len + 1 bytes */
int64_t saving = (int64_t)all[k].count * ((int64_t)len - 3) -
(int64_t)(len + 1);
if (saving <= 0) continue; /* sorted by count, not saving */
dict[nd++] = all[k];
}
/* rebuild a lookup hash for the kept dictionary: code = index */
size_t lcap = 1 << 16;
int32_t *look = malloc(lcap * sizeof *look);
if (!look) return 2;
for (size_t k = 0; k < lcap; k++) look[k] = -1;
for (size_t k = 0; k < nd; k++) {
size_t len = strlen(dict[k].w);
uint32_t h = hash_str(dict[k].w, len) & (lcap - 1);
while (look[h] >= 0) h = (h + 1) & (lcap - 1);
look[h] = (int32_t)k;
}
/* transform */
size_t cap = n + 1024;
uint8_t *out = malloc(cap);
if (!out) return 2;
size_t o = 0;
/* make room for the dictionary header */
{
size_t hdr = 10;
for (size_t k = 0; k < nd; k++) hdr += 1 + strlen(dict[k].w);
if (cap < hdr + 16) {
cap = hdr + 16;
out = realloc(out, cap);
if (!out) return 2;
}
}
/* header: magic, orig_len, ndict, entries */
memcpy(out, "DICT", 4); o += 4;
out[o++] = (uint8_t)(n & 0xff);
out[o++] = (uint8_t)((n >> 8) & 0xff);
out[o++] = (uint8_t)((n >> 16) & 0xff);
out[o++] = (uint8_t)((n >> 24) & 0xff);
out[o++] = (uint8_t)(nd & 0xff);
out[o++] = (uint8_t)((nd >> 8) & 0xff);
for (size_t k = 0; k < nd; k++) {
size_t len = strlen(dict[k].w);
out[o++] = (uint8_t)len;
memcpy(out + o, dict[k].w, len);
o += len;
}
/* growable body: recompute with room (header already written) */
i = 0;
while (i < n) {
/* ensure room for the worst case (1 byte -> 3 bytes) + slack */
if (o + 8 > cap) {
cap *= 2;
out = realloc(out, cap);
if (!out) return 2;
}
if (is_word(in[i])) {
size_t j = i;
while (j < n && is_word(in[j])) j++;
size_t len = j - i;
int code = -1;
if (len >= MIN_WORD) {
uint32_t h = hash_str((char *)in + i, len) & (lcap - 1);
while (look[h] >= 0) {
int32_t k = look[h];
if (strlen(dict[k].w) == len &&
memcmp(dict[k].w, in + i, len) == 0) { code = k; break; }
h = (h + 1) & (lcap - 1);
}
}
if (code >= 0) {
out[o++] = ESC;
out[o++] = (uint8_t)(code & 0xff);
out[o++] = (uint8_t)((code >> 8) & 0xff);
} else {
memcpy(out + o, in + i, len);
o += len;
}
i = j;
} else {
uint8_t c = in[i++];
if (c == ESC) {
out[o++] = ESC;
out[o++] = 0xFF;
out[o++] = 0xFF;
} else {
out[o++] = c;
}
}
}
spit(outpath, out, o);
fprintf(stderr, "dict: %zu words kept (of %zu distinct)\n", nd, na);
return 0;
}
static int decode(const char *inpath, const char *outpath) {
size_t n;
uint8_t *in = slurp(inpath, &n);
if (n < 10 || memcmp(in, "DICT", 4) != 0) {
fprintf(stderr, "dict: bad magic/header\n");
return 3;
}
uint32_t orig = (uint32_t)in[4] | ((uint32_t)in[5] << 8) |
((uint32_t)in[6] << 16) | ((uint32_t)in[7] << 24);
uint32_t nd = (uint32_t)in[8] | ((uint32_t)in[9] << 8);
size_t p = 10;
char **dict = malloc((nd ? nd : 1) * sizeof *dict);
if (!dict) return 2;
for (uint32_t k = 0; k < nd; k++) {
if (p >= n) { fprintf(stderr, "dict: truncated dict\n"); return 3; }
size_t len = in[p++];
if (p + len > n) { fprintf(stderr, "dict: truncated dict\n"); return 3; }
dict[k] = malloc(len + 1);
memcpy(dict[k], in + p, len);
dict[k][len] = 0;
p += len;
}
uint8_t *out = malloc(orig ? orig : 1);
if (!out) return 2;
size_t o = 0;
while (p < n) {
uint8_t c = in[p++];
if (c == ESC) {
if (p + 1 >= n) { fprintf(stderr, "dict: truncated code\n"); return 3; }
uint32_t code = (uint32_t)in[p] | ((uint32_t)in[p + 1] << 8);
p += 2;
if (code == 0xFFFF) {
if (o >= orig) return 3;
out[o++] = ESC;
} else {
if (code >= nd) { fprintf(stderr, "dict: bad code\n"); return 3; }
size_t len = strlen(dict[code]);
if (o + len > orig) return 3;
memcpy(out + o, dict[code], len);
o += len;
}
} else {
if (o >= orig) return 3;
out[o++] = c;
}
}
if (o != orig) {
fprintf(stderr, "dict: short output %zu != %u\n", o, orig);
return 3;
}
spit(outpath, out, o);
return 0;
}
int main(int argc, char **argv) {
if (argc != 4 || (argv[1][0] != 'c' && argv[1][0] != 'd')) {
fprintf(stderr, "usage: %s c|d in out\n", argv[0]);
return 1;
}
return argv[1][0] == 'c' ? encode(argv[2], argv[3])
: decode(argv[2], argv[3]);
}
+77
View File
@@ -0,0 +1,77 @@
#!/usr/bin/env python3
"""Build deterministic benchmark corpora on the server. Sizes capped.
text: /usr/share/doc text files + common-licenses (English prose/docs)
code: /usr/include headers + this repo sources (C/Markdown)
bin: ELF binaries from /bin, /usr/bin (executables)
mixed: round-robin 64KiB chunks of text+code+bin
rand: /dev/urandom control (incompressible)
"""
import os, glob, hashlib, random
OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "corpora")
CAP = 8 * 1024 * 1024
def collect(patterns, cap, text_only=False):
buf = bytearray()
files = []
for p in patterns:
files += sorted(glob.glob(p, recursive=True))
for f in files:
try:
if not os.path.isfile(f):
continue
with open(f, "rb") as fh:
d = fh.read()
except OSError:
continue
if text_only:
try:
d.decode("utf-8")
except UnicodeDecodeError:
continue
buf += d
if len(buf) >= cap:
break
return bytes(buf[:cap])
def write(name, data):
p = os.path.join(OUT, name)
with open(p, "wb") as fh:
fh.write(data)
print(name + ": " + str(len(data)) + " bytes sha256=" + hashlib.sha256(data).hexdigest()[:16])
text = collect(["/usr/share/doc/**/*", "/usr/share/common-licenses/*"], CAP, text_only=True)
write("text", text)
code = collect(["/usr/include/**/*.h", "/opt/lzply-exp-comp/*.c",
"/opt/lzply-exp-comp/*.h", "/opt/lzply-exp-comp/*.md"], CAP)
write("code", code)
bins = []
for d in ("/bin", "/usr/bin"):
for f in sorted(glob.glob(d + "/*")):
try:
with open(f, "rb") as fh:
h = fh.read(4)
if h[:4] == b"\x7fELF":
bins.append(f)
except OSError:
pass
buf = bytearray()
for f in bins:
with open(f, "rb") as fh:
buf += fh.read()
if len(buf) >= CAP:
break
bindata = bytes(buf[:CAP])
write("bin", bindata)
parts = [text, code, bindata]
m = bytearray()
i = 0
while len(m) < CAP:
for part in parts:
off = (i * 65536) % max(1, len(part) - 65536)
m += part[off:off + 65536]
if len(m) >= CAP:
break
i += 1
write("mixed", bytes(m[:CAP]))
rnd = random.Random(1234).randbytes(4 * 1024 * 1024)
write("rand", rnd)
+221
View File
@@ -0,0 +1,221 @@
/* rans.c - rANS entropy coder (see rans.h). Standard rANS:
* encode backwards, x in [2^23, 2^32); decode forwards from the
* 4-byte final state stored at the end of the stream. */
#include "rans.h"
#include <stdlib.h>
#include <string.h>
void rans_freq(const uint8_t *in, size_t n, uint16_t *freq) {
uint32_t cnt[256] = {0};
for (size_t i = 0; i < n; i++) cnt[in[i]]++;
uint32_t total = 0;
for (int s = 0; s < 256; s++) {
/* scale counts to PROB_SCALE, present symbols keep >= 1 */
uint32_t f = n ? (uint32_t)(((uint64_t)cnt[s] * RANS_PROB_SCALE) / n) : 0;
if (cnt[s] && f == 0) f = 1;
freq[s] = (uint16_t)f;
total += f;
}
/* Fix the sum to exactly PROB_SCALE by adjusting the largest. */
int mx = 0;
for (int s = 1; s < 256; s++) if (freq[s] > freq[mx]) mx = s;
if (total < RANS_PROB_SCALE) freq[mx] += (uint16_t)(RANS_PROB_SCALE - total);
else if (total > RANS_PROB_SCALE) {
uint32_t over = total - RANS_PROB_SCALE;
/* take from the largest symbol, never below 1 if present */
uint32_t give = freq[mx] - (cnt[mx] ? 1u : 0u);
if (give > over) give = over;
freq[mx] -= (uint16_t)give;
/* if still over (pathological), trim the next largest */
for (int s = 0; s < 256 && total - give > RANS_PROB_SCALE; s++) {
if (s == mx || !cnt[s]) continue;
uint32_t g = freq[s] - 1;
uint32_t need = total - give - RANS_PROB_SCALE;
if (g > need) g = need;
freq[s] -= (uint16_t)g; give += g;
}
}
}
size_t rans_encode_raw(const uint8_t *in, size_t n, const uint16_t *freq,
uint8_t *out) {
uint32_t cum[256];
uint32_t c = 0;
for (int s = 0; s < 256; s++) { cum[s] = c; c += freq[s]; }
uint32_t x = RANS_L;
/* Encode backwards; emit bytes into a temp tail, then reverse.
* Simpler: write backwards from the end of a scratch area. We
* write into out[0..] backwards via a local reverse pass: emit
* into out in reverse order by filling from the end. Caller
* guarantees out holds n + 64 bytes, so use the tail. */
uint8_t *p = out + 2 * n + 64; /* one past the end of scratch */
/* reserve 4 bytes at the very start of the emitted stream for the
* final state; emit stream bytes before them. Work backwards: */
uint8_t *w = p;
for (size_t i = n; i-- > 0;) {
uint8_t s = in[i];
uint32_t f = freq[s];
/* xmax = (L>>12)*f<<8: keeps post-update state in [L, 2^31) so the
* decoder renormalisation consumes exactly the bytes emitted here. */
uint32_t xmax = ((RANS_L >> RANS_PROB_BITS) * f) << 8;
while (x >= xmax) { *--w = (uint8_t)(x & 0xff); x >>= 8; }
x = (((x / f) << RANS_PROB_BITS) | ((x % f) + cum[s]));
}
/* w..p holds the emitted bytes in order; final state x follows. */
size_t nbytes = (size_t)(p - w);
memmove(out + 4, w, nbytes);
out[0] = (uint8_t)(x & 0xff);
out[1] = (uint8_t)((x >> 8) & 0xff);
out[2] = (uint8_t)((x >> 16) & 0xff);
out[3] = (uint8_t)((x >> 24) & 0xff);
return nbytes + 4;
}
int rans_decode_raw(const uint8_t *in, size_t in_len, const uint16_t *freq,
uint8_t *out, size_t out_len) {
if (in_len < 4) return -1;
uint16_t cum[256];
uint8_t dsym[RANS_PROB_SCALE];
uint32_t c = 0;
for (int s = 0; s < 256; s++) {
cum[s] = (uint16_t)c;
for (uint32_t k = 0; k < freq[s]; k++) dsym[c + k] = (uint8_t)s;
c += freq[s];
}
if (c != RANS_PROB_SCALE) return -1;
uint32_t x = (uint32_t)in[0] | ((uint32_t)in[1] << 8) |
((uint32_t)in[2] << 16) | ((uint32_t)in[3] << 24);
size_t p = 4;
for (size_t i = 0; i < out_len; i++) {
uint32_t slot = x & (RANS_PROB_SCALE - 1);
uint8_t s = dsym[slot];
out[i] = s;
uint32_t f = freq[s];
x = f * (x >> RANS_PROB_BITS) + (slot - cum[s]);
while (x < RANS_L) {
if (p >= in_len) return -1;
x = (x << 8) | in[p++];
}
}
return 0;
}
int rans_encode(const uint8_t *in, size_t n, uint8_t **out, size_t *out_len) {
uint16_t freq[256];
rans_freq(in, n, freq);
uint8_t *buf = malloc(520 + 2 * n + 64);
if (!buf) return -1;
memcpy(buf, "RANS", 4);
buf[4] = (uint8_t)(n & 0xff);
buf[5] = (uint8_t)((n >> 8) & 0xff);
buf[6] = (uint8_t)((n >> 16) & 0xff);
buf[7] = (uint8_t)((n >> 24) & 0xff);
for (int s = 0; s < 256; s++) {
buf[8 + 2 * s] = (uint8_t)(freq[s] & 0xff);
buf[8 + 2 * s + 1] = (uint8_t)((freq[s] >> 8) & 0xff);
}
size_t m = rans_encode_raw(in, n, freq, buf + 520);
*out = buf;
*out_len = 520 + m;
return 0;
}
int rans_decode(const uint8_t *in, size_t n, uint8_t **out, size_t *out_len) {
if (n < 520 || memcmp(in, "RANS", 4) != 0) return -1;
uint32_t orig = (uint32_t)in[4] | ((uint32_t)in[5] << 8) |
((uint32_t)in[6] << 16) | ((uint32_t)in[7] << 24);
uint16_t freq[256];
for (int s = 0; s < 256; s++)
freq[s] = (uint16_t)(in[8 + 2 * s] | (in[8 + 2 * s + 1] << 8));
uint8_t *buf = malloc(orig ? orig : 1);
if (!buf) return -1;
if (rans_decode_raw(in + 520, n - 520, freq, buf, orig) != 0) {
free(buf);
return -1;
}
*out = buf;
*out_len = orig;
return 0;
}
/* ---- general-alphabet layer (uint16_t symbols) ---- */
void rans_freq_n(const uint16_t *in, size_t n, int nsym, uint16_t *freq) {
uint32_t cnt[1024] = {0};
for (size_t i = 0; i < n; i++) cnt[in[i]]++;
uint32_t total = 0;
for (int s = 0; s < nsym; s++) {
uint32_t f = n ? (uint32_t)(((uint64_t)cnt[s] * RANS_PROB_SCALE) / n) : 0;
if (cnt[s] && f == 0) f = 1;
freq[s] = (uint16_t)f;
total += f;
}
int mx = 0;
for (int s = 1; s < nsym; s++) if (freq[s] > freq[mx]) mx = s;
if (total < RANS_PROB_SCALE) freq[mx] += (uint16_t)(RANS_PROB_SCALE - total);
else if (total > RANS_PROB_SCALE) {
uint32_t over = total - RANS_PROB_SCALE;
uint32_t give = freq[mx] - (cnt[mx] ? 1u : 0u);
if (give > over) give = over;
freq[mx] -= (uint16_t)give;
for (int s = 0; s < nsym && total - give > RANS_PROB_SCALE; s++) {
if (s == mx || !cnt[s]) continue;
uint32_t g = freq[s] - 1;
uint32_t need = total - give - RANS_PROB_SCALE;
if (g > need) g = need;
freq[s] -= (uint16_t)g; give += g;
}
}
}
size_t rans_encode_raw_n(const uint16_t *in, size_t n, const uint16_t *freq,
int nsym, uint8_t *out) {
uint32_t cum[1024];
uint32_t c = 0;
for (int s = 0; s < nsym; s++) { cum[s] = c; c += freq[s]; }
uint32_t x = RANS_L;
uint8_t *p = out + 2 * n + 64;
uint8_t *w = p;
for (size_t i = n; i-- > 0;) {
uint16_t s = in[i];
uint32_t f = freq[s];
uint32_t xmax = ((RANS_L >> RANS_PROB_BITS) * f) << 8;
while (x >= xmax) { *--w = (uint8_t)(x & 0xff); x >>= 8; }
x = (((x / f) << RANS_PROB_BITS) | ((x % f) + cum[s]));
}
size_t nbytes = (size_t)(p - w);
memmove(out + 4, w, nbytes);
out[0] = (uint8_t)(x & 0xff);
out[1] = (uint8_t)((x >> 8) & 0xff);
out[2] = (uint8_t)((x >> 16) & 0xff);
out[3] = (uint8_t)((x >> 24) & 0xff);
return nbytes + 4;
}
int rans_decode_raw_n(const uint8_t *in, size_t in_len, const uint16_t *freq,
int nsym, uint16_t *out, size_t out_len) {
if (in_len < 4) return -1;
uint16_t cum[1024];
uint16_t dsym[RANS_PROB_SCALE];
uint32_t c = 0;
for (int s = 0; s < nsym; s++) {
cum[s] = (uint16_t)c;
for (uint32_t k = 0; k < freq[s]; k++) dsym[c + k] = (uint16_t)s;
c += freq[s];
}
if (c != RANS_PROB_SCALE) return -1;
uint32_t x = (uint32_t)in[0] | ((uint32_t)in[1] << 8) |
((uint32_t)in[2] << 16) | ((uint32_t)in[3] << 24);
size_t p = 4;
for (size_t i = 0; i < out_len; i++) {
uint32_t slot = x & (RANS_PROB_SCALE - 1);
uint16_t s = dsym[slot];
out[i] = s;
uint32_t f = freq[s];
x = f * (x >> RANS_PROB_BITS) + (slot - cum[s]);
while (x < RANS_L) {
if (p >= in_len) return -1;
x = (x << 8) | in[p++];
}
}
return 0;
}
+44
View File
@@ -0,0 +1,44 @@
/* rans.h - rANS entropy coder shared by the lzply experiments.
* 12-bit probabilities (scale 4096), 23-bit renormalisation window.
* Two layers:
* - stream layer: rans_freq / rans_encode_raw / rans_decode_raw work
* on a raw byte stream with a caller-supplied freq table (for
* multi-stream coders, e.g. LZ token streams).
* - file layer: rans_encode / rans_decode wrap one stream with a
* header (magic "RANS", u32 orig_len, 256 x u16 freq table).
*/
#ifndef EXP_RANS_H
#define EXP_RANS_H
#include <stddef.h>
#include <stdint.h>
#define RANS_PROB_BITS 12
#define RANS_PROB_SCALE (1u << RANS_PROB_BITS)
#define RANS_L (1u << 23)
/* Count + normalise frequencies of `in` to sum RANS_PROB_SCALE.
* Symbols present get >= 1. */
void rans_freq(const uint8_t *in, size_t n, uint16_t *freq /*[256]*/);
/* Encode `in` with `freq`; `out` must hold 2*n + 64 bytes. Returns
* bytes written. */
size_t rans_encode_raw(const uint8_t *in, size_t n, const uint16_t *freq,
uint8_t *out);
/* Decode `in_len` bytes into `out` (out_len bytes). Returns 0 ok, -1 bad. */
int rans_decode_raw(const uint8_t *in, size_t in_len, const uint16_t *freq,
uint8_t *out, size_t out_len);
/* Whole-file wrap: mallocs *out. Returns 0 ok, -1 bad. */
int rans_encode(const uint8_t *in, size_t n, uint8_t **out, size_t *out_len);
int rans_decode(const uint8_t *in, size_t n, uint8_t **out, size_t *out_len);
#endif
/* General-alphabet layer (uint16_t symbols, nsym <= 1024): for token
* streams such as literal/length (286 symbols) and distance (21). */
void rans_freq_n(const uint16_t *in, size_t n, int nsym, uint16_t *freq);
size_t rans_encode_raw_n(const uint16_t *in, size_t n, const uint16_t *freq,
int nsym, uint8_t *out /* 2*n+64 */);
int rans_decode_raw_n(const uint8_t *in, size_t in_len, const uint16_t *freq,
int nsym, uint16_t *out, size_t out_len);
+46
View File
@@ -0,0 +1,46 @@
/* rans_tool.c - standalone rANS order-0 compressor: `rans_tool c in out`,
* `rans_tool d in out`. Used for the ANS-family measurements. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "rans.h"
static uint8_t *slurp(const char *path, size_t *n) {
FILE *f = fopen(path, "rb");
if (!f) { perror(path); exit(2); }
fseek(f, 0, SEEK_END);
long sz = ftell(f);
fseek(f, 0, SEEK_SET);
uint8_t *b = malloc(sz ? (size_t)sz : 1);
if (!b) exit(2);
if (sz && fread(b, 1, (size_t)sz, f) != (size_t)sz) exit(2);
fclose(f);
*n = (size_t)sz;
return b;
}
static void spit(const char *path, const uint8_t *b, size_t n) {
FILE *f = fopen(path, "wb");
if (!f) { perror(path); exit(2); }
if (n && fwrite(b, 1, n, f) != n) exit(2);
fclose(f);
}
int main(int argc, char **argv) {
if (argc != 4 || (argv[1][0] != 'c' && argv[1][0] != 'd')) {
fprintf(stderr, "usage: %s c|d in out\n", argv[0]);
return 1;
}
size_t n;
uint8_t *in = slurp(argv[2], &n);
uint8_t *out = NULL;
size_t on = 0;
int rc = argv[1][0] == 'c' ? rans_encode(in, n, &out, &on)
: rans_decode(in, n, &out, &on);
if (rc != 0) {
fprintf(stderr, "%s: %s failed (bad input?)\n", argv[0], argv[1]);
return 3;
}
spit(argv[3], out, on);
return 0;
}
File renamed without changes.
+6
View File
@@ -0,0 +1,6 @@
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
bzip2,text,8388608,776306,9.25,2.969,1.346,2.8,6.2,OK
bzip2,code,8388608,1053123,12.55,2.754,0.937,3.0,8.9,OK
bzip2,bin,8388608,3373815,40.22,1.866,1.575,4.5,5.3,OK
bzip2,mixed,8388608,1974225,23.53,2.081,0.875,4.0,9.6,OK
bzip2,rand,4194304,4213434,100.46,1.336,0.958,3.1,4.4,OK
1 tool corpus orig comp ratio_pct enc_s dec_s enc_MBs dec_MBs status
2 bzip2 text 8388608 776306 9.25 2.969 1.346 2.8 6.2 OK
3 bzip2 code 8388608 1053123 12.55 2.754 0.937 3.0 8.9 OK
4 bzip2 bin 8388608 3373815 40.22 1.866 1.575 4.5 5.3 OK
5 bzip2 mixed 8388608 1974225 23.53 2.081 0.875 4.0 9.6 OK
6 bzip2 rand 4194304 4213434 100.46 1.336 0.958 3.1 4.4 OK
+6
View File
@@ -0,0 +1,6 @@
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
dict-lzip6,text,8388608,299963,3.58,2.541,0.166,3.3,50.4,OK
dict-lzip6,code,8388608,770519,9.19,4.144,0.218,2.0,38.5,OK
dict-lzip6,bin,8388608,2793130,33.30,9.522,0.467,0.9,18.0,OK
dict-lzip6,mixed,8388608,1480819,17.65,5.358,0.317,1.6,26.5,OK
dict-lzip6,rand,4194304,4266698,101.73,2.794,0.475,1.5,8.8,OK
1 tool corpus orig comp ratio_pct enc_s dec_s enc_MBs dec_MBs status
2 dict-lzip6 text 8388608 299963 3.58 2.541 0.166 3.3 50.4 OK
3 dict-lzip6 code 8388608 770519 9.19 4.144 0.218 2.0 38.5 OK
4 dict-lzip6 bin 8388608 2793130 33.30 9.522 0.467 0.9 18.0 OK
5 dict-lzip6 mixed 8388608 1480819 17.65 5.358 0.317 1.6 26.5 OK
6 dict-lzip6 rand 4194304 4266698 101.73 2.794 0.475 1.5 8.8 OK
+6
View File
@@ -0,0 +1,6 @@
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
gzip9,text,8388608,1969901,23.48,0.830,0.117,10.1,71.6,OK
gzip9,code,8388608,1376091,16.40,0.980,0.066,8.6,127.7,OK
gzip9,bin,8388608,3702420,44.14,2.700,0.115,3.1,72.6,OK
gzip9,mixed,8388608,2521765,30.06,1.180,0.117,7.1,71.5,OK
gzip9,rand,4194304,4194967,100.02,0.428,0.059,9.8,71.3,OK
1 tool corpus orig comp ratio_pct enc_s dec_s enc_MBs dec_MBs status
2 gzip9 text 8388608 1969901 23.48 0.830 0.117 10.1 71.6 OK
3 gzip9 code 8388608 1376091 16.40 0.980 0.066 8.6 127.7 OK
4 gzip9 bin 8388608 3702420 44.14 2.700 0.115 3.1 72.6 OK
5 gzip9 mixed 8388608 2521765 30.06 1.180 0.117 7.1 71.5 OK
6 gzip9 rand 4194304 4194967 100.02 0.428 0.059 9.8 71.3 OK
+6
View File
@@ -0,0 +1,6 @@
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
lzip1,text,8388608,521474,6.22,0.923,0.117,9.1,71.8,OK
lzip1,code,8388608,1268850,15.13,1.127,0.216,7.4,38.8,OK
lzip1,bin,8388608,3173235,37.83,3.144,0.468,2.7,17.9,OK
lzip1,mixed,8388608,1809972,21.58,1.789,0.271,4.7,31.0,OK
lzip1,rand,4194304,4251394,101.36,3.104,0.474,1.4,8.9,OK
1 tool corpus orig comp ratio_pct enc_s dec_s enc_MBs dec_MBs status
2 lzip1 text 8388608 521474 6.22 0.923 0.117 9.1 71.8 OK
3 lzip1 code 8388608 1268850 15.13 1.127 0.216 7.4 38.8 OK
4 lzip1 bin 8388608 3173235 37.83 3.144 0.468 2.7 17.9 OK
5 lzip1 mixed 8388608 1809972 21.58 1.789 0.271 4.7 31.0 OK
6 lzip1 rand 4194304 4251394 101.36 3.104 0.474 1.4 8.9 OK
+6
View File
@@ -0,0 +1,6 @@
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
lzip6,text,8388608,298558,3.56,3.655,0.117,2.3,71.4,OK
lzip6,code,8388608,787213,9.38,5.138,0.168,1.6,50.0,OK
lzip6,bin,8388608,2735269,32.61,9.676,0.416,0.9,20.2,OK
lzip6,mixed,8388608,1460156,17.41,5.519,0.267,1.5,31.4,OK
lzip6,rand,4194304,4251435,101.36,3.173,0.531,1.3,7.9,OK
1 tool corpus orig comp ratio_pct enc_s dec_s enc_MBs dec_MBs status
2 lzip6 text 8388608 298558 3.56 3.655 0.117 2.3 71.4 OK
3 lzip6 code 8388608 787213 9.38 5.138 0.168 1.6 50.0 OK
4 lzip6 bin 8388608 2735269 32.61 9.676 0.416 0.9 20.2 OK
5 lzip6 mixed 8388608 1460156 17.41 5.519 0.267 1.5 31.4 OK
6 lzip6 rand 4194304 4251435 101.36 3.173 0.531 1.3 7.9 OK
+6
View File
@@ -0,0 +1,6 @@
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
lzip9,text,8388608,288746,3.44,6.658,0.119,1.3,70.3,OK
lzip9,code,8388608,758969,9.05,9.062,0.168,0.9,50.0,OK
lzip9,bin,8388608,2729180,32.53,10.747,0.479,0.8,17.5,OK
lzip9,mixed,8388608,1440405,17.17,8.603,0.272,1.0,30.8,OK
lzip9,rand,4194304,4251435,101.36,3.071,0.467,1.4,9.0,OK
1 tool corpus orig comp ratio_pct enc_s dec_s enc_MBs dec_MBs status
2 lzip9 text 8388608 288746 3.44 6.658 0.119 1.3 70.3 OK
3 lzip9 code 8388608 758969 9.05 9.062 0.168 0.9 50.0 OK
4 lzip9 bin 8388608 2729180 32.53 10.747 0.479 0.8 17.5 OK
5 lzip9 mixed 8388608 1440405 17.17 8.603 0.272 1.0 30.8 OK
6 lzip9 rand 4194304 4251435 101.36 3.071 0.467 1.4 9.0 OK
+6
View File
@@ -0,0 +1,6 @@
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
lzrans-lazy,text,8388608,525357,6.26,1.888,0.119,4.4,70.6,OK
lzrans-lazy,code,8388608,1134159,13.52,3.264,0.116,2.6,72.5,OK
lzrans-lazy,bin,8388608,3510054,41.84,9.644,0.320,0.9,26.2,OK
lzrans-lazy,mixed,8388608,1942374,23.15,3.963,0.165,2.1,50.7,OK
lzrans-lazy,rand,4194304,4214292,100.48,9.295,0.115,0.5,36.3,OK
1 tool corpus orig comp ratio_pct enc_s dec_s enc_MBs dec_MBs status
2 lzrans-lazy text 8388608 525357 6.26 1.888 0.119 4.4 70.6 OK
3 lzrans-lazy code 8388608 1134159 13.52 3.264 0.116 2.6 72.5 OK
4 lzrans-lazy bin 8388608 3510054 41.84 9.644 0.320 0.9 26.2 OK
5 lzrans-lazy mixed 8388608 1942374 23.15 3.963 0.165 2.1 50.7 OK
6 lzrans-lazy rand 4194304 4214292 100.48 9.295 0.115 0.5 36.3 OK
+3
View File
@@ -0,0 +1,3 @@
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
lzrans-opt,text,8388608,519352,6.19,18.714,0.132,0.4,63.5,OK
lzrans-opt,code,8388608,1094779,13.05,8.628,0.115,1.0,72.9,OK
1 tool corpus orig comp ratio_pct enc_s dec_s enc_MBs dec_MBs status
2 lzrans-opt text 8388608 519352 6.19 18.714 0.132 0.4 63.5 OK
3 lzrans-opt code 8388608 1094779 13.05 8.628 0.115 1.0 72.9 OK
+4
View File
@@ -0,0 +1,4 @@
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
ppm,text,8388608,2754814,32.84,1.327,2.176,6.3,3.9,OK
ppm,code,8388608,2585570,30.82,1.324,2.040,6.3,4.1,OK
ppm,mixed,8388608,3286801,39.18,1.732,2.635,4.8,3.2,OK
1 tool corpus orig comp ratio_pct enc_s dec_s enc_MBs dec_MBs status
2 ppm text 8388608 2754814 32.84 1.327 2.176 6.3 3.9 OK
3 ppm code 8388608 2585570 30.82 1.324 2.040 6.3 4.1 OK
4 ppm mixed 8388608 3286801 39.18 1.732 2.635 4.8 3.2 OK
+6
View File
@@ -0,0 +1,6 @@
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
rans0,text,8388608,5401895,64.40,0.221,0.170,38.0,49.3,OK
rans0,code,8388608,5672388,67.62,0.277,0.171,30.3,49.1,OK
rans0,bin,8388608,6470778,77.14,0.217,0.179,38.6,46.9,OK
rans0,mixed,8388608,6552704,78.11,0.218,0.174,38.4,48.1,OK
rans0,rand,4194304,4213441,100.46,0.115,0.068,36.4,61.6,OK
1 tool corpus orig comp ratio_pct enc_s dec_s enc_MBs dec_MBs status
2 rans0 text 8388608 5401895 64.40 0.221 0.170 38.0 49.3 OK
3 rans0 code 8388608 5672388 67.62 0.277 0.171 30.3 49.1 OK
4 rans0 bin 8388608 6470778 77.14 0.217 0.179 38.6 46.9 OK
5 rans0 mixed 8388608 6552704 78.11 0.218 0.174 38.4 48.1 OK
6 rans0 rand 4194304 4213441 100.46 0.115 0.068 36.4 61.6 OK
+6
View File
@@ -0,0 +1,6 @@
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
xz6,text,8388608,294056,3.51,4.257,0.076,2.0,110.1,OK
xz6,code,8388608,771984,9.20,7.147,0.200,1.2,42.0,OK
xz6,bin,8388608,2733616,32.59,12.330,0.367,0.7,22.8,OK
xz6,mixed,8388608,1450908,17.30,7.553,0.271,1.1,31.0,OK
xz6,rand,4194304,4194584,100.01,3.323,0.085,1.3,49.1,OK
1 tool corpus orig comp ratio_pct enc_s dec_s enc_MBs dec_MBs status
2 xz6 text 8388608 294056 3.51 4.257 0.076 2.0 110.1 OK
3 xz6 code 8388608 771984 9.20 7.147 0.200 1.2 42.0 OK
4 xz6 bin 8388608 2733616 32.59 12.330 0.367 0.7 22.8 OK
5 xz6 mixed 8388608 1450908 17.30 7.553 0.271 1.1 31.0 OK
6 xz6 rand 4194304 4194584 100.01 3.323 0.085 1.3 49.1 OK
+6
View File
@@ -0,0 +1,6 @@
tool,corpus,orig,comp,ratio_pct,enc_s,dec_s,enc_MBs,dec_MBs,status
zstd19,text,8388608,304391,3.63,3.549,0.055,2.4,151.8,OK
zstd19,code,8388608,795239,9.48,11.348,0.071,0.7,117.7,OK
zstd19,bin,8388608,2919792,34.81,14.260,0.169,0.6,49.5,OK
zstd19,mixed,8388608,1535960,18.31,8.021,0.066,1.0,126.9,OK
zstd19,rand,4194304,4194413,100.00,3.020,0.037,1.4,112.0,OK
1 tool corpus orig comp ratio_pct enc_s dec_s enc_MBs dec_MBs status
2 zstd19 text 8388608 304391 3.63 3.549 0.055 2.4 151.8 OK
3 zstd19 code 8388608 795239 9.48 11.348 0.071 0.7 117.7 OK
4 zstd19 bin 8388608 2919792 34.81 14.260 0.169 0.6 49.5 OK
5 zstd19 mixed 8388608 1535960 18.31 8.021 0.066 1.0 126.9 OK
6 zstd19 rand 4194304 4194413 100.00 3.020 0.037 1.4 112.0 OK
+3 -95
View File
@@ -105,9 +105,7 @@
#include <unistd.h>
#include "bch.h"
#include "deep_repair.h"
#include "lzply_lib.h"
#include "repair_cmd.h"
@@ -1573,7 +1571,7 @@ static int cmd_tree(const char *archive, const char **selectors,
static void usage(FILE *out)
{
fprintf(out,
"Usage: %s -c|-d|-l|-t|-a|-i|-tr|-r [options] <input> [output] [selectors...]\n"
"Usage: %s -c|-d|-l|-t|-a|-i|-tr [options] <input> [output] [selectors...]\n"
"\n"
" -c compress a file or directory into one .lzply archive\n"
" -a append files/dirs to an archive (creates it if\n"
@@ -1596,15 +1594,6 @@ static void usage(FILE *out)
" -tr print an archive as a tree, like the Linux\n"
" `tree` command, with a directory/file count.\n"
" Selectors filter it.\n"
" -r repair an archive: recover entries whose bit\n"
" errors exceed the BCH limit t, in escalating\n"
" levels L0-L3 (standard decode, Chase-1,\n"
" Chase-2, cross-block). Recovered files go to\n"
" [output] dir (default ./repaired). --level N\n"
" caps the level (default 3), --time-budget S\n"
" the seconds per entry (default 120). On a\n"
" CUDA build the L1 Chase-1 scan runs on the\n"
" GPU when a device is present, else CPU.\n"
" -datestart <date> only entries with mtime on or after this date\n"
" -dateend <date> only entries with mtime on or before this date\n"
" Dates are YYYY-MM-DD (whole day, inclusive) or\n"
@@ -1659,18 +1648,16 @@ static void usage(FILE *out)
" %s -i backup.lzply -datestart 2024-01-01 -dateend 2024-06-30\n"
" inspect only Jan-Jun 2024 entries\n"
" %s -tr backup.lzply photos/ -year 2025 tree of 2025 photos only\n"
" %s -r backup.lzply repair into ./repaired\n"
" %s -r -o fixed/ backup.lzply repair into fixed/\n"
"\n"
"Exit codes: 0 ok, 1 usage, 2 I/O error, 3 corrupt/unrecoverable.\n",
lzply_progname, lzply_progname, lzply_progname, lzply_progname, lzply_progname, lzply_progname,
lzply_progname, lzply_progname, lzply_progname, lzply_progname, lzply_progname, lzply_progname,
lzply_progname, lzply_progname, lzply_progname, lzply_progname,
lzply_progname, lzply_progname, lzply_progname);
lzply_progname);
}
enum { MODE_NONE, MODE_COMPRESS, MODE_DECOMPRESS, MODE_LIST, MODE_TEST,
MODE_APPEND, MODE_INSPECT, MODE_TREE, MODE_REPAIR };
MODE_APPEND, MODE_INSPECT, MODE_TREE };
/* Parse a poly=NN value: hex if it has a 0x prefix or any a-f/A-F
* letter, else decimal. Returns the poly, or NULL if it is not a
@@ -1709,11 +1696,6 @@ int main(int argc, char **argv)
int ecc_level = 4; /* default -e 4 -> BCH t=8 */
const bch_poly_t *pinned_poly = NULL;
int ow_mode = OW_ASK;
const char *repair_outdir = "./repaired";
int repair_verbose = 0;
int repair_max_level = DEEP_MAX_LEVEL;
double repair_budget = DEEP_DEFAULT_BUDGET_SEC;
const char *repair_only_entry = NULL;
date_filter_t dfilter;
const char **args = NULL; /* positional arguments after the options */
int nargs = 0;
@@ -1762,64 +1744,6 @@ int main(int argc, char **argv)
mode = MODE_INSPECT;
} else if (strcmp(a, "-tr") == 0 || strcmp(a, "--tree") == 0) {
mode = MODE_TREE;
} else if (strcmp(a, "-r") == 0 || strcmp(a, "--repair") == 0) {
mode = MODE_REPAIR;
} else if (strcmp(a, "-o") == 0 || strcmp(a, "--output") == 0) {
if (i + 1 >= argc) {
fprintf(stderr, "%s: -o needs a directory\n",
lzply_progname);
return EXIT_USAGE;
}
repair_outdir = argv[++i];
} else if (strcmp(a, "-v") == 0 || strcmp(a, "--verbose") == 0) {
repair_verbose = 1;
} else if (strcmp(a, "--level") == 0) {
if (i + 1 >= argc) {
fprintf(stderr, "%s: --level needs 0..3\n",
lzply_progname);
return EXIT_USAGE;
}
repair_max_level = atoi(argv[++i]);
if (repair_max_level < 0 || repair_max_level > DEEP_MAX_LEVEL) {
fprintf(stderr, "%s: --level must be 0..3\n",
lzply_progname);
return EXIT_USAGE;
}
} else if (strncmp(a, "--level=", 8) == 0) {
repair_max_level = atoi(a + 8);
if (repair_max_level < 0 || repair_max_level > DEEP_MAX_LEVEL) {
fprintf(stderr, "%s: --level must be 0..3\n",
lzply_progname);
return EXIT_USAGE;
}
} else if (strcmp(a, "--time-budget") == 0) {
if (i + 1 >= argc) {
fprintf(stderr, "%s: --time-budget needs seconds\n",
lzply_progname);
return EXIT_USAGE;
}
repair_budget = atof(argv[++i]);
if (repair_budget <= 0) {
fprintf(stderr, "%s: --time-budget must be > 0\n",
lzply_progname);
return EXIT_USAGE;
}
} else if (strncmp(a, "--time-budget=", 14) == 0) {
repair_budget = atof(a + 14);
if (repair_budget <= 0) {
fprintf(stderr, "%s: --time-budget must be > 0\n",
lzply_progname);
return EXIT_USAGE;
}
} else if (strcmp(a, "--entry") == 0) {
if (i + 1 >= argc) {
fprintf(stderr, "%s: --entry needs a stored path\n",
lzply_progname);
return EXIT_USAGE;
}
repair_only_entry = argv[++i];
} else if (strncmp(a, "--entry=", 8) == 0) {
repair_only_entry = a + 8;
} else if (strcmp(a, "-datestart") == 0 ||
strcmp(a, "--datestart") == 0) {
if (i + 1 >= argc) {
@@ -2007,22 +1931,6 @@ int main(int argc, char **argv)
nargs >= 2 ? nargs - 1 : 0,
&dfilter);
break;
case MODE_REPAIR:
/* archive, optional outdir. */
if (nargs < 1 || nargs > 2) {
fprintf(stderr,
"%s: -r needs an archive and an optional output directory\n",
lzply_progname);
usage(stderr);
rc = EXIT_USAGE;
break;
}
if (nargs == 2)
repair_outdir = args[1];
rc = repair_archive(lzply_progname, args[0], repair_outdir,
repair_max_level, repair_budget,
repair_only_entry, repair_verbose);
break;
default:
rc = EXIT_USAGE;
break;
+312 -6
View File
@@ -18,23 +18,27 @@
* and how many bits were corrected. -v adds the per-level trial
* counts (BM trials, splitting-filter passes, valid codewords).
*
* The archive-walking driver lives in repair_cmd.c (shared with
* the lzply -r mode); this file is only the option parsing.
*
* Exit codes: 0 all entries recovered, 1 usage, 2 I/O error,
* 3 any entry unrecoverable (matching lzply's EXIT_CORRUPT).
*/
#define _FILE_OFFSET_BITS 64
#define _DEFAULT_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "bch.h"
#include "deep_repair.h"
#include "lzply_lib.h"
#include "repair_cmd.h"
#include "lzrs_lib.h"
static const char *prog = "lzply_deep_repair";
@@ -53,6 +57,56 @@ static void usage(void)
prog, DEEP_DEFAULT_BUDGET_SEC);
}
/* mkdir -p (mode 0755 for created parents). Returns 0 on success. */
static int mkdir_p(const char *path, mode_t mode)
{
char *tmp = xstrdup(path);
size_t n = strlen(tmp);
size_t i;
if (n == 0) {
free(tmp);
return 0;
}
while (n > 1 && tmp[n - 1] == '/')
tmp[--n] = '\0';
for (i = 1; i <= n; i++) {
if (tmp[i] == '/' || tmp[i] == '\0') {
char save = tmp[i];
struct stat st;
tmp[i] = '\0';
if (stat(tmp, &st) != 0) {
if (mkdir(tmp, mode) != 0 && errno != EEXIST) {
free(tmp);
return -1;
}
} else if (!S_ISDIR(st.st_mode)) {
free(tmp);
return -1;
}
tmp[i] = save;
}
}
free(tmp);
return 0;
}
static int write_out_file(const char *path, const uint8_t *data, size_t len,
uint32_t mode)
{
FILE *f = fopen(path, "wb");
if (!f)
return -1;
if (len > 0 && fwrite(data, 1, len, f) != len) {
fclose(f);
return -1;
}
if (fclose(f) != 0)
return -1;
if (mode)
chmod(path, (mode_t)(mode & 07777));
return 0;
}
int main(int argc, char **argv)
{
int max_level = DEEP_MAX_LEVEL;
@@ -61,6 +115,9 @@ int main(int argc, char **argv)
const char *outdir = "./repaired";
const char *only_entry = NULL;
const char *archive = NULL;
int is_lzrs = 0;
FILE *f = NULL;
uint8_t magic[4];
int opt;
static struct option long_opts[] = {
{ "time-budget", required_argument, NULL, 1000 },
@@ -110,6 +167,255 @@ int main(int argc, char **argv)
}
archive = argv[optind];
return repair_archive(prog, archive, outdir, max_level, budget,
only_entry, verbose);
f = fopen(archive, "rb");
if (!f) {
fprintf(stderr, "%s: cannot open %s: %s\n", prog, archive,
strerror(errno));
return EXIT_IO;
}
if (fread(magic, 1, 4, f) != 4) {
fprintf(stderr, "%s: %s is too short to be an archive\n",
prog, archive);
fclose(f);
return EXIT_CORRUPT;
}
if (memcmp(magic, "LZRS", 4) == 0)
is_lzrs = 1;
else if (memcmp(magic, "LZPL", 4) != 0) {
fprintf(stderr, "%s: %s is not an LZPL or LZRS archive\n",
prog, archive);
fclose(f);
return EXIT_CORRUPT;
}
/* Validate the archive up front (version, headers, end marker),
* so a structurally broken archive fails before any repair is
* attempted. The scan also gives the clear v4 message for old
* LZPL archives. */
{
int version = 0;
uint32_t count = 0;
off_t size = 0, end_off = 0;
scan_list_t entries;
int s;
rewind(f);
if (is_lzrs)
s = lzrs_scan_archive(archive, &version, &count, &size,
&entries, &end_off);
else
s = scan_archive(archive, &version, &count, &size,
&entries, &end_off);
if (s != 0) {
fclose(f);
return EXIT_CORRUPT;
}
scan_list_free(&entries);
rewind(f);
}
if (mkdir_p(outdir, 0755) != 0) {
fprintf(stderr, "%s: cannot create output directory %s: %s\n",
prog, outdir, strerror(errno));
fclose(f);
return EXIT_IO;
}
/* Skip the 16-byte global header; then walk the entries. */
if (fseeko(f, 16, SEEK_SET) != 0) {
fprintf(stderr, "%s: cannot seek in %s\n", prog, archive);
fclose(f);
return EXIT_IO;
}
{
int worst = 0;
long n_ok = 0, n_fail = 0, n_dir = 0;
long landed[4] = { 0, 0, 0, 0 };
double t_start = bch_now();
for (;;) {
char *path = NULL;
int level = 0, is_bch = 0, rs_level = 0, is_dir = 0;
uint16_t poly_id = 0, want_crc16 = 0;
uint64_t stored_size = 0, blob_size = 0, orig_size = 0;
uint32_t mode = 0;
uint8_t sha[32];
uint8_t *stored = NULL;
int r;
if (is_lzrs) {
lzrs_ehdr_t h;
r = lzrs_read_entry_header(f, &h);
if (r == 1)
break;
if (r < 0) {
fprintf(stderr, "%s: truncated or corrupt entry header\n",
prog);
worst = EXIT_CORRUPT;
break;
}
path = h.path;
level = h.level;
is_bch = (h.flags & FLAG_BCH) != 0;
rs_level = h.rs_level;
is_dir = (h.flags & FLAG_ISDIR) != 0;
poly_id = h.bch_poly_id;
want_crc16 = h.crc16;
stored_size = h.stored_size;
blob_size = h.blob_size;
orig_size = h.orig_size;
mode = h.mode;
memcpy(sha, h.sha, 32);
} else {
ehdr_t h;
r = read_entry_header(f, &h);
if (r == 1)
break;
if (r < 0) {
fprintf(stderr, "%s: truncated or corrupt entry header\n",
prog);
worst = EXIT_CORRUPT;
break;
}
path = h.path;
level = h.level;
is_bch = (h.flags & FLAG_BCH) != 0;
rs_level = 0;
is_dir = (h.flags & FLAG_ISDIR) != 0;
poly_id = (uint16_t)(h.rs_level |
((uint16_t)h.reserved << 8));
want_crc16 = h.crc16;
stored_size = h.stored_size;
blob_size = h.blob_size;
orig_size = h.orig_size;
mode = h.mode;
memcpy(sha, h.sha, 32);
}
stored = xmalloc(stored_size ? (size_t)stored_size : 1);
if (stored_size > 0 &&
fread(stored, 1, (size_t)stored_size, f) !=
(size_t)stored_size) {
fprintf(stderr, "%s: truncated data for %s\n", prog, path);
free(stored);
free(path);
worst = EXIT_CORRUPT;
break;
}
if (only_entry && strcmp(path, only_entry) != 0) {
free(stored);
free(path);
continue;
}
if (is_dir) {
char *dp = xmalloc(strlen(outdir) + strlen(path) + 2);
sprintf(dp, "%s/%s", outdir, path);
if (mkdir_p(dp, mode ? (mode_t)(mode & 07777) : 0755) != 0)
fprintf(stderr, "%s: cannot create directory %s: %s\n",
prog, dp, strerror(errno));
free(dp);
free(stored);
free(path);
n_dir++;
continue;
}
{
uint8_t *raw = NULL;
size_t raw_len = 0;
deep_stats_t st;
int drc = deep_repair_entry(stored, (size_t)stored_size,
level, is_bch, poly_id,
rs_level, sha,
(size_t)blob_size, want_crc16,
max_level, budget,
&raw, &raw_len, &st);
free(stored);
if (drc != 0) {
printf("%s: FAILED (stage %s) after %.3fs, "
"cands %ld crc-rejects %ld sha-rejects %ld\n",
path, st.fail_stage, st.t_total,
st.cands_tried, st.crc_rejects, st.sha_rejects);
if (verbose) {
int lv;
for (lv = 0; lv <= DEEP_MAX_LEVEL; lv++)
printf(" L%d: %.3fs trials %ld split %ld "
"codewords %ld\n", lv, st.t_level[lv],
st.trials[lv], st.split_pass[lv],
st.codewords[lv]);
printf(" blocks %ld/%ld failed%s\n",
st.blocks_failed, st.blocks_total,
st.partial ? " (partial: budget hit)" : "");
}
n_fail++;
if (EXIT_CORRUPT > worst)
worst = EXIT_CORRUPT;
free(path);
continue;
}
if (raw_len != orig_size) {
fprintf(stderr, "%s: %s: size mismatch after repair "
"(got %zu, expected %llu)\n", prog, path,
raw_len, (unsigned long long)orig_size);
free(raw);
free(path);
n_fail++;
if (EXIT_CORRUPT > worst)
worst = EXIT_CORRUPT;
continue;
}
{
char *dp = xmalloc(strlen(outdir) + strlen(path) + 2);
char *pd;
sprintf(dp, "%s/%s", outdir, path);
pd = parent_dir(dp);
if (mkdir_p(pd, 0755) != 0)
fprintf(stderr, "%s: cannot create %s: %s\n",
prog, pd, strerror(errno));
free(pd);
if (write_out_file(dp, raw, raw_len, mode) != 0) {
fprintf(stderr, "%s: cannot write %s: %s\n",
prog, dp, strerror(errno));
if (EXIT_IO > worst)
worst = EXIT_IO;
free(dp);
free(raw);
free(path);
continue;
}
free(dp);
}
{
char rssuf[48];
rssuf[0] = '\0';
if (st.rs_corrected > 0)
snprintf(rssuf, sizeof rssuf,
" (RS corrected %d symbols)",
st.rs_corrected);
printf("%s: RECOVERED at L%d in %.3fs "
"(L0 %.3fs, L1 %.3fs, L2 %.3fs, L3 %.3fs) "
"cands %ld crc-rejects %ld sha-rejects %ld "
"bch-corrected %d%s\n",
path, st.level_landed, st.t_total,
st.t_level[0], st.t_level[1], st.t_level[2],
st.t_level[3], st.cands_tried, st.crc_rejects,
st.sha_rejects, st.bch_corrected, rssuf);
}
if (verbose) {
int lv;
for (lv = 0; lv <= DEEP_MAX_LEVEL; lv++)
printf(" L%d: %.3fs trials %ld split %ld "
"codewords %ld\n", lv, st.t_level[lv],
st.trials[lv], st.split_pass[lv],
st.codewords[lv]);
printf(" blocks %ld/%ld failed%s\n",
st.blocks_failed, st.blocks_total,
st.partial ? " (partial: budget hit)" : "");
}
landed[st.level_landed]++;
n_ok++;
free(raw);
free(path);
}
}
printf("deep repair: %ld recovered (L0 %ld, L1 %ld, L2 %ld, "
"L3 %ld), %ld failed, %ld directories, %.3fs total\n",
n_ok, landed[0], landed[1], landed[2], landed[3],
n_fail, n_dir, bch_now() - t_start);
fclose(f);
return worst;
}
}
-43
View File
@@ -1,43 +0,0 @@
randfec: randfec.c
gcc -O2 -std=c11 -Wall -Wextra -march=native -o randfec randfec.c -lm
selftest: randfec
./randfec selftest
baseline: randfec
./randfec baseline
clean:
rm -f randfec
.PHONY: selftest baseline clean
# Phase 2: decoder-centric Monte Carlo + GPU d_min search
p2: p2.c ../bch.c ../bch.h ../bch_polys.h
gcc -O2 -std=c11 -Wall -Wextra -march=native -D_POSIX_C_SOURCE=200809L -o p2 p2.c ../bch.c -lm
cuda_dmin: cuda_dmin.cu
/usr/local/cuda/bin/nvcc -O3 -std=c++17 -arch=sm_86 -o cuda_dmin cuda_dmin.cu
p3: p3.c ../bch.c ../bch.h ../bch_polys.h fit_params.h
gcc -O2 -std=c11 -Wall -Wextra -march=native -D_POSIX_C_SOURCE=200809L -o p3 p3.c ../bch.c -lm
# Phase 2, Milestone 2.2: RaptorQ outer layer (foxsen real decode)
p4: p4.cc
g++ -O2 -std=c++11 -Wall -Wextra -march=native -I/root/raptorq/foxsen -o p4 p4.cc /root/raptorq/foxsen/Encoder.cpp /root/raptorq/foxsen/Decoder.cpp /root/raptorq/foxsen/Generators.cpp /root/raptorq/foxsen/Helper.cpp /root/raptorq/foxsen/StdAfx.cpp /root/raptorq/foxsen/Symbol.cpp
rq_bench: p4-bench.cc
g++ -O2 -std=c++11 -Wall -Wextra -march=native -I/root/raptorq/foxsen -o rq_bench p4-bench.cc /root/raptorq/foxsen/Encoder.cpp /root/raptorq/foxsen/Decoder.cpp /root/raptorq/foxsen/Generators.cpp /root/raptorq/foxsen/Helper.cpp /root/raptorq/foxsen/StdAfx.cpp /root/raptorq/foxsen/Symbol.cpp
lrq_bench: p4-lrqbench.cc
g++ -O2 -std=c++11 -Wall -Wextra -march=native -DEIGEN_MPL2_ONLY -I/usr/include/eigen3 -I/root/raptorq/libRaptorQ/src -o lrq_bench p4-lrqbench.cc /root/raptorq/libRaptorQ/build/lib/libRaptorQ.1.a /root/raptorq/libRaptorQ/build/librq_lz4_static.a -lpthread
rs_erase_test: rs_erase_test.c
gcc -O2 -std=c11 -Wall -Wextra -march=native -o rs_erase_test rs_erase_test.c
# Phase 2, Milestone 2.3: short-LDPC assessment (two builds, one source)
ldpc_test: ldpc_test.c ../bch.c ../bch.h ../bch_polys.h
gcc -O2 -std=c11 -Wall -Wextra -march=native -D_POSIX_C_SOURCE=200809L -o ldpc_test ldpc_test.c ../bch.c -lm
ldpc_test64: ldpc_test.c ../bch.c ../bch.h ../bch_polys.h
gcc -O2 -std=c11 -Wall -Wextra -march=native -D_POSIX_C_SOURCE=200809L -DLDPC_N=64 -DLDPC_R=16 -DLDPC_K=48 -DLDPC_DV=3 -DLDPC_DC=12 -o ldpc_test64 ldpc_test.c ../bch.c -lm
-138
View File
@@ -1,138 +0,0 @@
# Phase 2 — decoder-centric FEC comparison + GPU search
Branch `experiments/randfec` (from Phase 1 `828208c`). Research only:
nothing here touches lzply core. Programs: `p2.c` (CPU Monte Carlo:
GRAND / GRAND-MO / RLC / eBCH vs real BCH+BM), `cuda_dmin.cu`
(GPU d_min certification + mass sweep). Logs: `results/p2-matrix-*.log`,
`results/cuda-*.log`. Survivor lists: `results/cuda-sweep-*.txt`
(first 1000 lines in git; full lists on hot_house at
`/root/lzply-sweep-full/`, regenerable from the logged seed + command).
Fallback rule (user, Dec 2, 2026): if hot_house is unreachable for more
than 1 hour, relocate to hot_dallas from the latest pushed branch state
(CUDA pauses there, CPU work continues) and keep pushing.
## Method (p2.c)
Same (message, error) trial stream for every scheme in a group-model
cell, 10,000 trials per cell (blob: 5,000). Damage: iid scattered bit
flips (p=0.01, 0.03) and a Gilbert 2-state burst channel (mean burst
L=8/32, BER=0.01/0.03, plus a mix model with background p0=0.002).
GRAND = hard-decision, weight-ordered noise guesses (ML within a
1M-guess budget, weight <= 4). GRAND-MO = guesses ordered by Markov
burst-model likelihood (Viterbi-scored; bursts <= 12 + weight <= 4).
BM baseline is the REAL lzply decoder (`../bch.c`, `bch_decode_block`).
Repair rate = fraction of trials returning exactly the transmitted
codeword; miscorrections counted separately.
Groups: g1 (24,16,8) BCH m8t1 vs CRC 0x1f9 vs RLC; g2 (32,16,16) BCH
m8t2 vs CRC 0x109b1 vs RLC vs eBCH (g*(x+1), r=17); g3 (30,16,14) BCH
m7t2; g4 (64,48,16) BCH m8t2 vs CRC 0x14669 vs RLC; g5 (24,12,12) CRC
0x1343 vs RLC; blob (384 data bits, 384 parity bits): one BCH block
D=48 t=32 m=12 vs 24x CRC(32,16,16)+GRAND-MO vs 24x RLC+GRAND-MO vs
24x BCH+BM, damage drawn over the whole 768-bit stream.
## Milestone 1 results — the decoder was the limit, not the code
1. **BCH+GRAND beats BCH+BM everywhere, by +1.6 to +13.5 points.**
Same poly, same (n,k,r), only the decoder changes. Examples (repair
rate, 10k trials): g1 scat p=0.03: BM 82.96% -> GRAND 92.11%.
g2 scat p=0.03: 93.07% -> 99.38%. g3 scat p=0.03: 93.88% ->
98.63%. g4 scat p=0.03: 69.50% -> 83.01%. This answers shortlist
#3's control question: at short blocks the BCH *decoder* was the
limit. (Caveat: GRAND's guess budget explodes with n; see #7.)
2. **The BCH-poly swap buys nothing under an ML decoder.** CRC+GRAND
vs BCH+GRAND at the same (n,k,r): within +/-0.35 points at n<=32
(g2 scat p=0.03: CRC 99.47% vs BCH 99.38%; burst L8 BER 0.03: CRC
97.48% vs BCH 91.78% is GRAND-MO, not GRAND). At (64,48,16) scat
p=0.03 the searched CRC is WORSE: 79.96% vs BCH 83.01% (-3.05
points, ~7 sigma). Phase 1's d_min edge (7 vs 6) does not survive
the repair-rate test: d_min is a weak predictor; the weight
spectrum decides. Task (a) is therefore a negative result: do not
swap the poly on distance grounds.
3. **GRAND-MO is the burst winner, and a liability on iid errors.**
Burst models: g1 L8 BER 0.03: BM 89.94% -> GRAND-MO 95.62%.
g2 L8 BER 0.03: 89.78% -> 97.48%. g4 L8 BER 0.03: 81.23% ->
93.92% (+12.7). g4 L8 BER 0.01: 93.30% -> 98.30%. But on iid
errors GRAND-MO LOSES to plain GRAND by up to 13 points (g4 scat
p=0.03: 70.00% vs 83.01%; g1 scat p=0.03: 81.49% vs 92.11%) --
burst-first ordering miscorrects scattered errors. A practical
decoder needs channel-matched ordering / model selection.
4. **RLCs do not beat searched CRCs.** Under GRAND-MO on bursts RLC
ties CRC within +/-0.1 points everywhere (g2 L8 BER 0.03: RLC
97.43% vs CRC 97.48%). On iid errors RLC is clearly worse (g5
scat p=0.03: RLC 87.50% vs CRC+GRAND 98.71%; g2 scat p=0.03: RLC
95.20% vs CRC+GRAND 99.47%) -- its low-weight codewords
miscorrect. Shortlist #2 is a negative result at these sizes.
5. **eBCH (+1 parity bit) buys nothing measurable.** g2 scat p=0.01:
99.99% vs 99.99%; p=0.03: 99.34% vs 99.38% (BCH+GRAND). Burst
L8 BER 0.01: 97.35% vs 97.23%. The extra parity bit is spent on
the overall-parity check, which ML decoding barely uses.
6. **Blob: one big BCH block beats 24 short blocks at equal parity,
on all 6 models.** 384 data bits + 384 parity bits. Scat p=0.03:
big-BCH+BM 96.78% vs CRC-blocks+GRAND-MO 46.26% vs RLC-blocks
30.92% vs BCH-blocks+BM 17.00%. Burst L8 BER 0.01: 96.38% vs
83.92% vs 83.92% vs 48.04%. Burst L32 BER 0.01: 91.74% vs 85.14%.
Mix: 94.36% vs 84.62%. Short blocks fragment the parity budget
(all 24 must survive: 0.97^24 ~= 0.48) and a burst landing inside
one 32-bit block overwhelms it, while the big block pools t=32
across the whole blob. The deployed big-block structure is right;
a short-block architecture is a dead end at equal overhead.
(Note: GRAND-MO still rescues the short blocks relative to
short-block BM: 56.56% vs 9.36% at burst L8 BER 0.03.)
7. **GRAND is infeasible at deployed sizes.** Matching BM's t=32 at
n=32768 (D=4096, t=8: m=16, r=128) would need enumerating
weight<=8 patterns, C(32768,8) ~ 1e33 guesses. GRAND/GRAND-MO
are viable only at n <= ~128. Any GRAND adoption in lzply would
need a short-block format change, which #6 rules out on
repair-rate grounds at equal overhead.
## Milestone 1 results — CUDA mass search
`cuda_dmin.cu`: one block per candidate; weight<=t syndromes into a
per-block epoch-tagged hash table (no clearing between candidates).
GPU vs CPU cross-check: 0 mismatches at (64,16), (128,24), (96,32).
Measured speedups, same (n,r,t), GPU vs sort-based CPU reference:
(64,16,t=2) 160x (1.48M vs 9.2k cands/s); (64,32,t=3) 166x (61k vs
367/s); (96,24,t=2) 30x (116k vs 3.8k/s); (96,32,t=3) 96x (8.5k vs
88/s); (128,24,t=2) 39x (78k vs 2.0k/s). 7M+ valid candidates swept.
Sweeps, 10^6 random cyclic candidates each (pass = d_min certified):
| n | r | t | pass rate | d_min |
|---|---|---|-----------|-------|
| 64 | 16 | 2 | 40.28% | >=5 |
| 64 | 32 | 3 | 99.72% | >=7 |
| 96 | 24 | 2 | 97.96% | >=5 |
| 96 | 32 | 3 | 97.64% | >=7 |
| 128 | 24 | 2 | 95.32% | >=5 |
| 128 | 16 | 2 | 0.97% | >=5 |
| 128 | 32 | 3 | 90.20% | >=7 |
| 128 | 16 | 3 | 0 / 10^6 | >=7 none |
Exact d_min probes (first 20 survivors, CPU t=3/t=4 certification):
(128,112,16) t=2 survivors: 0/20 pass t=3 -- all d_min exactly 5,
no d_min-6 code at (128,112,16) in the sample; BCH m8t2's d_min 5
is not beaten at the same parity at n=128. (96,64,32) and
(128,96,32) t=3 survivors: 0/20 pass t=4 -- all d_min exactly 7.
Good codes are common at r=24/32 and n<=128; the ceiling in the
samples is d_min 7 at r=32, d_min 5 at (128,112,16).
Bugs caught: (1) 64-bit shift overflow in single-bit syndrome
computation for n>64 (`(1ULL<<j)<<r` with j+r>=64) silently
duplicated syndromes and failed every candidate -- invalidated the
first round of n>64 sweeps; fixed with an x^m mod g linear
recurrency, regression-checked (same seeds reproduce the valid n=64
rates: 40.28%, 99.72%). (2) Blob buffer overflow in p2.c
(`enc[80]` for an 88-byte BCH block) corrupted the model name in
the log and made scheme-A blob numbers unreliable; fixed (D=48,
buffers 128) and reran. (3) OOM: 6 concurrent sweeps x 2.15 GB
pool > 12 GB -- run at most 5 concurrently.
## Not started
- RaptorQ outer layer (file-level experiment, shortlist #4 alt).
- Short LDPC protograph (conditional on a manufactured reliability
signal; none built yet).
- GRAND-MO with a burst model fitted to real lzply damage (current
models are assumed Gilbert parameters, not fitted).
- No article: per instructions, the user reviews before any publish.
-259
View File
@@ -1,259 +0,0 @@
# Phase 2, Milestone 2.1 — GRAND-MO with model selection, fitted to real damage
Branch `experiments/randfec` (from Milestone 1 `6ea6cf9`). Research only:
nothing here touches lzply core. Programs: `randfec/m2/damage.c`
(calibrated corruption of real archives), `randfec/m2/fit.py` (Gilbert
fit by moment matching) + `randfec/m2/gilsim.c` (validation simulator),
`randfec/p3.c` (Monte Carlo: GRAND-MO with fitted / mixture / two-pass
ordering + syndrome-evidence test). Logs: `randfec/m2/fit2c.log`,
`randfec/results/p3-matrix-{g1,g2,g4,g5}.log`, `randfec/results/p3-syndev2.log`.
Fitted params: `randfec/fit_params.h` (generated by `randfec/m2/mk_p3.py`
from `randfec/m2/fits2/*.json`). p3 selftest: ALL PASS; M1 replication
exact (g2 burst-L8-BER0.03: BM 89.78, CRC-GRAND-MO 97.48, RLC 97.43).
Fallback rule (user, Dec 2, 2026): if hot_house is unreachable for more
than 1 hour, relocate to hot_dallas from the latest pushed branch state
(CUDA pauses there, CPU work continues) and keep pushing.
## Experiment A — burst model fitted to REAL lzply damage
Real archives (`lzply -c -e 4`, default t=8) built from the repo test
corpus: `mixed-e4.lzply` (1,065,235 B: text, source, 1 MiB random,
1 MiB zeros, small files) and `big-e4.lzply` (52,431,127 B, 50 MiB
random). Damage modes mirror the project's own test corrupters
(`tests/corrupt_bits.c` = scattered bit flips, `tests/corrupt_run.c` =
contiguous byte run XOR 0xff) with calibrated rates. The XOR of
original vs corrupted archive is exactly the channel error pattern on
the stored BCH codeword bits. BERs below are MEASURED (orig vs out
comparison), not requested.
| scenario | damage | measured BER | bits flipped |
|---|---|---|---|
| iid001 | iid bit flips p=0.001 | 0.0010055 | 8,569 |
| iid01 | iid bit flips p=0.01 | 0.0100156 | 85,352 |
| run1ff | 1-byte runs, 800/MB, XOR ff | 0.0007632 | 6,504 (813 runs) |
| run4ff | 4-byte runs, 200/MB, XOR ff | 0.0007623 | 6,496 (203 runs) |
| run8ff | 8-byte runs, 100/MB, XOR ff | 0.0007660 | 6,528 (102 runs) |
| run4rand | 4-byte runs, 200/MB, XOR rand | 0.0003717 | 3,168 (203 runs) |
| mix | bg iid 0.0005 + 4-byte runs 200/MB ff | 0.0012521 | 10,670 (203 runs) |
| run512ff | 512-byte runs, 2/MB, XOR ff | 0.0009613 | 8,192 (2 runs) |
| big-mix | mix on the 50 MB archive | 0.0012610 | 528,921 (10,000 runs) |
| big-run4ff | run4ff on the 50 MB archive | 0.0007625 | 319,840 (10,000 runs) |
Fit: Gilbert 2-state model (a=P(G->B), b=P(B->G), p0=flip prob in G,
q1=flip prob in B) by matching 7 moments (BER, lag-1/2/4 P(11) joints,
mean 1-run, mean 0-run) computed exactly from the 4-state (state,bit)
chain, random-restart coordinate descent + basin hopping. Validation:
simulate the fitted model with `gilsim` (20M bits) and compare the
window-weight histograms, which were NOT in the fit loss.
Headline fits (50 MB archive, 10,000 runs each):
| model | a | b | p0 | q1 | mean burst | mean gap | loss |
|---|---|---|---|---|---|---|---|
| FIT-RUN (big-run4ff) | 2.16e-05 | 0.02846 | 2.3e-06 | 0.999998 | 35.1 bits | 46,389 bits | 1.7e-04 |
| FIT-MIX (big-mix) | 2.68e-05 | 0.03393 | 0.000485 | 0.983476 | 29.5 bits | 37,260 bits | 2.6e-06 |
Truth check: run4ff is 4-byte runs = 32-bit bursts, q1=1; fitted mean
burst 35.1 bits (+10% — the geometric tail compensates the hard
cutoff of fixed-length runs), q1=0.999998. Mix truth is background
0.0005 + 4-byte runs; fitted p0=0.000485 (recovers the background
almost exactly) and q1=0.983. Validation (sim vs real, 20M bits):
big-run4ff win32 P(>2)/P(>4) = 0.0013/0.0012 vs real 0.0013/0.0013;
win64 0.0020/0.0018 vs 0.0021/0.0021. big-mix win32 0.0015/0.0013 vs
0.0013/0.0013; win64 0.0023/0.0021 vs 0.0021/0.0021. Both validate
within ~15% on statistics the fit never saw.
Caveats (all measured, not assumed):
- Fixed-length damage is not Gilbert: the geometric model cannot match
the hard cutoff (runs of exactly 8 bits give observed lag8 ~= 0;
any geometric model with mean burst 8 gives lag8 ~= 0.34*BER), so
lag8/64/256 are reported but NOT fitted. Residual loss concentrates
there (run1ff loss 0.018, mostly lag4: model 0.000421 vs obs 0.000382).
- Small-sample fits can match moments yet fail validation: the 1 MB
mixed-mix fit (203 runs) matches all 7 moments (loss 1.1e-06) but
its simulated win32 P(>2)=0.0033 vs real 0.0014 (2.4x high). The
50 MB fit does not have this problem. Use the big fits (as p3 does).
- Partial-density bursts are not identifiable: run4rand (random-byte
runs, true q1=0.5) fits q1=0.787 with matching moments (loss
1.4e-05) but simulated win32 P(>2)=0.0005 vs real 0.0013 (2.6x low).
Burst length and in-burst density trade off; window histograms
discriminate. Not used downstream (headline fits have q1 ~= 1).
- run512ff is unidentifiable from this data: 2 events in 8.5M bits.
Fitted mean burst 10,628 bits vs true 4,096; the (a,b) pair is one
of many that fit. Window stats still validate (0.0009 vs 0.0010),
because block decoding only cares whether a window falls inside a
run, not the run's total length. Excluded from downstream use.
- iid damage is unidentifiable in Gilbert form (many (a,b,p0,q1) give
the same moments); the fits reproduce iid statistics exactly but
the parameters are degenerate. Not used downstream (M1 scat models
are used for iid testing instead).
## Experiment B — model-selection matrix (p3.c)
10,000 trials/cell, same (message, error) stream per scheme in a
cell (sigma ~0.07-0.5 pts per cell; paired differences tighter).
Groups g1 (24,16,8), g2 (32,16,16), g4 (64,48,16), g5 (24,12,12).
Models: M1's six (scat p=0.01/0.03, burst L8/L32 BER 0.01/0.03,
mix-L16-BER0.01) + four fitted-shape channels (FITRUN / FITMIX at
BER 0.01/0.03, shape from the big fits, frequency rescaled).
Schemes (all CRC unless noted): bm (real BCH+BM baseline), grand
(iid ML, W=4), grandmo (GRAND-MO with the ORACLE per-channel model,
M1's scheme), grandmo-fix8 (one fixed L8 prior), grandmo-fit (fitted
RUN prior, native), grandmo-fitscaled (fitted RUN shape at the test
BER), grandmo-fitmix (fitted MIX prior, native), grandmix (single
list ordered by mixture LL: 0.5*burst(fitscaled) + 0.5*iid(p=0.01)),
grand2pass (GRAND + GRAND-MO(fitscaled) scanned separately, candidates
arbitrated by mixture LL). Regrets below are vs the best specialist
(max of CRC-grand / CRC-grandmo-oracle) WITHIN the CRC family; BCH
vs CRC code differences (g4 scat-p0.03: BCH-grand 83.01 vs CRC-grand
79.96; g1: 92.11 vs 91.31) are a separate, already-reported M1 effect.
### g2 (32,16,16) — repair rate %
| model | bm | grand | grandmo | gmo-fit | gmo-fitmix | grandmix | grand2pass | mix-regret |
|---|---|---|---|---|---|---|---|---|
| scat-p0.01 | 99.53 | 99.99 | 99.77 | 99.95 | 99.92 | 99.98 | 99.98 | 0.01 |
| scat-p0.03 | 93.07 | 99.47 | 96.95 | 98.70 | 98.72 | 99.44 | 99.44 | 0.03 |
| burst-L8-BER0.01 | 96.51 | 97.29 | 99.30 | 99.30 | 99.30 | 99.06 | 99.10 | 0.24 |
| burst-L32-BER0.01 | 98.13 | 98.25 | 98.79 | 98.79 | 98.79 | 98.71 | 98.71 | 0.08 |
| burst-L8-BER0.03 | 89.78 | 91.91 | 97.48 | 97.46 | 97.45 | 97.04 | 97.04 | 0.44 |
| mix-L16-BER0.01 | 98.03 | 98.28 | 99.12 | 99.12 | 99.12 | 99.04 | 99.04 | 0.08 |
| burst-FITRUN-BER0.01 | 98.21 | 98.30 | 98.79 | 98.79 | 98.79 | 98.79 | 98.79 | 0.00 |
| burst-FITRUN-BER0.03 | 94.84 | 95.10 | 96.82 | 96.82 | 96.82 | 96.82 | 96.82 | 0.00 |
| burst-FITMIX-BER0.01 | 98.07 | 98.19 | 98.85 | 98.85 | 98.85 | 98.80 | 98.80 | 0.05 |
| burst-FITMIX-BER0.03 | 94.62 | 94.88 | 96.73 | 96.73 | 96.73 | 96.71 | 96.71 | 0.02 |
### g4 (64,48,16) — repair rate % (hardest group)
| model | bm | grand | grandmo | gmo-fit | gmo-fitmix | grandmix | grand2pass | mix-regret |
|---|---|---|---|---|---|---|---|---|
| scat-p0.01 | 97.23 | 98.60 | 96.43 | 98.04 | 98.11 | 98.61 | 98.58 | -0.01 |
| scat-p0.03 | 69.50 | 79.96 | 70.00 | 77.91 | 77.73 | 80.36 | 80.21 | -0.40 |
| burst-L8-BER0.01 | 93.30 | 94.08 | 98.30 | 98.17 | 98.28 | 97.57 | 97.58 | 0.73 |
| burst-L32-BER0.01 | 97.11 | 97.19 | 98.08 | 98.02 | 98.07 | 97.86 | 97.86 | 0.22 |
| burst-L8-BER0.03 | 81.23 | 82.87 | 93.92 | 93.69 | 93.89 | 92.08 | 92.08 | 1.84 |
| mix-L16-BER0.01 | 96.29 | 96.52 | 98.03 | 98.00 | 98.04 | 97.75 | 97.75 | 0.28 |
| burst-FITRUN-BER0.01 | 97.32 | 97.37 | 98.11 | 98.11 | 98.11 | 98.10 | 98.10 | 0.01 |
| burst-FITRUN-BER0.03 | 92.04 | 92.17 | 94.59 | 94.59 | 94.59 | 94.54 | 94.54 | 0.05 |
| burst-FITMIX-BER0.01 | 97.01 | 97.10 | 98.07 | 98.07 | 98.07 | 97.98 | 97.98 | 0.09 |
| burst-FITMIX-BER0.03 | 91.69 | 91.88 | 94.59 | 94.58 | 94.59 | 94.42 | 94.42 | 0.17 |
### g1 (24,16,8) and g5 (24,12,12) — headline cells (full logs referenced)
g1: grandmix regret 0.05-0.65 pts on 8/10 models; worst 1.47-1.48
(burst-L8-BER0.03: 95.62 -> 94.15). g1 scat-p0.03: grand 91.31
(CRC; BCH-grand 92.11), grandmo-oracle 81.49, grandmo-fit 82.42,
grandmo-fitmix 86.48, grandmix 90.66. g5: grandmix regret 0.00-0.47
pts on all 10 models (worst burst-L8-BER0.03: 98.28 -> 97.82);
g5 scat-p0.03: grand 98.71, grandmo-oracle 92.30, grandmo-fit 96.91,
grandmo-fitmix 97.49, grandmix 98.72.
### Findings
1. **The fitted GRAND-MO prior dominates the assumed L8 prior.**
On iid it recovers most of M1's GRAND-MO liability: g4 scat-p0.03
70.00 -> 77.91 (+7.91), g5 92.30 -> 96.91 (+4.61), g2 96.95 ->
98.70 (+1.75), g1 81.49 -> 82.42 (+0.93). On bursts it ties the
oracle within +/-0.25 pts everywhere (g2 L8-0.03: 97.46 vs 97.48;
g4 L8-0.03: 93.69 vs 93.92). Why: the fitted prior has tiny burst
frequency (f ~= 0.0008) and q1 ~= 1, so it is conservative about
bursts — it behaves nearly like plain GRAND on scattered errors
while still ranking true bursts first.
2. **The mix-fitted prior is safer than the run-fitted prior on iid.**
g1 scat-p0.03: fitmix 86.48 vs fit 82.42 (+4.06); g5: 97.49 vs
96.91. The background term (p0=0.000485) matters: a pure-run
prior (p0 ~= 0) is overconfident that non-burst bits never flip.
On bursts the two fitted priors tie (within 0.2 pts).
3. **Mixture / two-pass selection costs almost nothing.** Worst-case
regret vs the best per-channel specialist is 1.84 pts (g4
burst-L8-BER0.03: 93.92 -> 92.08); median regret across all 40
cells is <= 0.1 pts; on the fitted channels it is 0.00-0.05 pts.
On g4 scat-p0.03 grandmix (80.36) even BEATS plain GRAND (79.96)
by 0.40 pts, because its guess universe (bursts <= 12) includes
weight-5/6 burst patterns that GRAND's W=4 list misses.
4. **grandmix and grand2pass are the same decoder in outcome.**
Within 0.02 pts in 39/40 cells (max difference 0.03 pts, 2-3
trials in 10,000). Prefer grandmix: one list, one scan, no
arbitration logic.
5. **Arbitration is barely better than a coin flip — and it does not
matter.** Two-pass arbitration picks the true pattern in 55-79%
of disagreements (mean ~65%), but disagreements are rare (0.1-24%
of trials), so the regret stays small. The two candidates usually
have similar mixture LLs; the LL is a weak discriminator between
two in-range codewords.
6. **The oracle is not worth chasing.** GRAND-MO with the true
per-channel parameters is not better than the single fixed fitted
prior on bursts (within +/-0.25 pts), and is much worse on iid
(the oracle's f is set by the burst channel's BER, so it
over-weights bursts when the channel is actually iid). M1's
oracle advantage was entirely the iid liability, which the fitted
prior removes. One fixed fitted prior suffices; no per-channel
tuning is needed.
7. **Scan-depth cost of the mixture is real but small.** Mean scan
position on bursts: grandmix 283 vs grandmo 31 (g2 L8-BER0.03) —
~9x deeper, still hundreds of syndrome compares per block,
trivial next to BM.
8. **Code note (qualifies M1).** BCH vs searched CRC under GRAND on
iid at g1: 92.11 vs 91.31 (0.80 pts, ~6 sigma paired) — M1's
"within +/-0.35 at n<=32" holds for g2 (99.38 vs 99.47) but not
g1. At g4 the CRC is worse by 3.05 pts (M1). The CRC's d_min edge
does not translate uniformly into repair rate.
## Experiment C — can the syndrome tell burst from iid? (syndev)
20,000 trials per config, half iid scat / half burst-L8 at the SAME
BER, feature = popcount(syndrome of the error), label = burst?.
Unconditional AUC: g2 ber=0.01: 0.387; ber=0.03: 0.269; g4 ber=0.01:
0.309; ber=0.03: 0.184. AUC < 0.5 means syndrome weight is
ANTI-correlated with burstiness: burst errors have LOWER syndrome
weight, because burst channels leave most blocks clean (only 5-24%
of burst trials are damaged at all, vs 28-86% of iid trials), so a
low/zero syndrome is more likely burst than iid (P(burst|synw=0) =
0.57-0.85). Conditional on the block being damaged (syndrome != 0),
AUC is 0.68 / 0.64 at n=32 (ber 0.01 / 0.03) and 0.49 / 0.47 at
n=64 — weak at n=32, none at n=64. **Hard pre-decode model selection
from the syndrome is not viable.** This justifies the mixture /
two-pass architecture, which never needs a pre-decision.
## Standing notes
- Feasibility is unchanged from M1 #7: GRAND/GRAND-MO/mixture are
viable only at n <= ~128; matching BM's t=32 at n=32768 would need
~1e33 guesses. No deployment change is proposed; this is research
only. The deployed big-block BCH+BM structure stands (M1 #6).
- No article: per instructions, the user reviews before any publish.
## Bugs caught (do not repeat)
1. fit.py run-boundary indexing: mean 0-run was 0.0 for every scenario
(run starts were taken as d==1 positions only, which are 1-run
starts; 0-run starts are the d==-1 boundaries). Fixed by
boundary-based run extraction; also poisoned the data-driven
optimizer init (a = 1/meanrun0) in the first fit round.
2. Loss-scale veto: a relative-error loss with a 1e-6 floor let
near-zero observed lag64/256 (and lag8 for fixed-length runs) veto
the correct burst length — run8ff first fitted b=0.123 (mean burst
8 bits) instead of 0.0156 (64 bits). Fixed: lag8/64/256 reported
but not fitted (tails beyond the 12-bit guess horizon, where
geometric cannot match fixed-length cutoffs); lag scales floored
at 2% of BER; mean-run terms weighted by squared run counts.
3. Optimizer clamp: a,b >= 1e-5 prevented representing rare-burst
channels (run512ff true a ~= 2e-07); lowered to 1e-8.
4. summarize_p3.py regex: the scheme field is %-16s padded, so
`(\S+) n=` silently matched only scheme names >= 16 chars —
every BM row and g1's GRAND row were dropped (shown as nan).
Fixed with \s+.
## Not started
- RaptorQ outer layer (file-level experiment, Milestone 2 item 2).
Scouted: libRaptorQ (Luca Fulchir, LGPL3, C++11 header-only, needs
Eigen3; RFC 6330) is the canonical free implementation; foxsen/raptorQ
(GitHub, no dependencies, claims RFC 6330) is the fallback. Next:
clone on hot_house, build, validate round-trip + overhead curve,
then measure file recovery vs erasure rate at 0/2/5/10% overhead
against BCH-alone and an outer-RS control.
- Short LDPC protograph (conditional on a manufactured reliability
signal; none built yet — assessment pending).
- No article: per instructions, the user reviews before any publish.
-438
View File
@@ -1,438 +0,0 @@
# Phase 2, Milestone 2.2 — RaptorQ outer layer (file-level experiment)
Branch `experiments/randfec` (from Milestone 2.1 `8b501a0`). Research only:
nothing here touches lzply core. Programs: `randfec/p4.cc` (matrix
harness, foxsen real decode), `randfec/p4-bench.cc` (foxsen validation
bench), `randfec/p4-lrqbench.cc` (libRaptorQ cross-check bench),
`randfec/rs_erase_test.c` (real GF(256) erasure-code validator),
`randfec/m2/run_p4.sh` (156-cell driver), `randfec/m2/summarize_p4.py`
(Wilson-CI tables). Logs: `randfec/results/p4-summary.txt` (full tables),
`randfec/results/p4-cells/cell-*.log` (156 cells), `randfec/m2/setup-m22.log`
(build), `randfec/m2/rq-k0-pin1.log`, `randfec/m2/lrq-k101.log`,
`randfec/results/p4-cells/spot-51200-*.log` (50 MB real-decode spots).
Fallback rule (user, Dec 2, 2026): if hot_house is unreachable for more
than 1 hour, relocate to hot_dallas from the latest pushed branch state
(CUDA pauses there, CPU work continues) and keep pushing.
## 0. Snapshot helper gap — fixed
The M2.1 agent found `/root/scripts/git-push-snapshot.sh` does not exist
on hot_house. The hot_newyork original does NOT apply here as-is: it
detects the server by IP and only knows hot_newyork <-> hot_chicago
(104.225.223.162); on parrot it exits 2 ("unknown server"). hot_house
has no public IP and is reached only via the reverse tunnel on
hot_newyork:2203, and hot_chicago is parked. Fix: the NY original is kept
at `/root/scripts/git-push-snapshot.sh.orig-ny`, and an adapted variant
is installed at `/root/scripts/git-push-snapshot.sh` on hot_house. It
builds the zip the same way (temp clone at HEAD, LFS smudge + pointer
check, `<repo>-YYYYMMDD-HHMMSS-<shortsha>.zip` under
`/root/git-backups/<repo>/`, prune to newest 7) and copies it to
hot_newyork by DIRECT scp (verified Dec 3, 2026: parrot reaches
172.93.49.176 directly), verifying the size matches and pruning the
remote copy to 7. No chicago involvement. Used for the M2.2 push.
## 1. Implementations: both build, both validate, foxsen is 10x faster
Cloned on hot_house (`/root/raptorq/`, NOT in the lzply repo — vendored
third-party code is not committed):
- **libRaptorQ** (Luca Fulchir, LGPL3, C++11 header-only, RFC 6330),
HEAD `a394b22`. Needs Eigen3: `apt-get install -y libeigen3-dev`
worked on ParrotOS. CMake then failed on a missing lz4 submodule —
fixed by `git submodule init/update` (external/lz4 r131). Build then
failed on a missing-include bug: `src/deterministic.cpp` uses
`uint64_t` without `#include <cstdint>` (newer GCC exposes it). One
line added locally (recorded in the file); full build then succeeds:
`libRaptorQ.1.a` + `.so.1.0.0-rc2`.
- **foxsen/raptorq** (GitHub, no dependencies, RFC 6330), HEAD `53727d2`.
`make tests`: **54 tests, 54 passed, 0 failed** (README says 44;
the suite has grown).
Overhead curve (random K-subset received, byte-verified recovery):
- foxsen K=100 T=1024, 2000 trials: K+0 **99.65%** (7 failures),
K+1/K+2/K+3/K+5 **100.00%** (2000/2000 each). K=256: K+0 99.80%
(499/500), K+1+ 100%. Round-trip + encode-determinism PASS.
- libRaptorQ K=101 T=1024, 500 trials: K+0 **99.00%** (5 failures),
K+1+ **100.00%**. The two independent implementations agree within
noise (K+0 failure 0.35% vs 1.0%; combined K+2: 0 failures in 3000
trials). Both sit inside the RFC 6330 allowance (<=1% at K+0,
<=0.01% at K+1, <=1e-6 at K+2); foxsen is on the good side of it.
- Speed: foxsen encode/decode 74/83 MB/s @K=100, 63/70 @K=256,
43/43 @K=1024, 14/14 @K=4096 (T=1024, single thread, -O2).
libRaptorQ ~8/8 MB/s @K=101 — ~10x slower. One K=51200 (50 MB)
encode+decode with foxsen took 3m26s. Hence: foxsen is the primary
for the matrix; libRaptorQ is the cross-check.
- foxsen's `MAX_OVERHEAD (40)` is only a precompute cache:
`generate_repairs` computes `Tupl(isi)` on the fly past it, so
arbitrary repair counts work (verified: R=5120 generated at
K=51200). No cap issue.
RS control validated with a REAL codec (`rs_erase_test.c`, GF(256)
Vandermonde erasure code, K=100, T=64, 200 patterns each): R=2, 5, 10
all give **100/100 byte-identical recovery when #lost <= R** and
**100/100 detected failure, 0 silent-wrong, when #lost > R**. The MDS
count rule (`recovers iff #lost <= R`) is therefore real, not assumed.
Caveat: plain GF(256) RS caps at K+R <= 255 symbols, so at K > 255
the RS column is the MDS *bound* (a GF(2^16) RS attains it to 65535
symbols); RaptorQ's gap to it is the measured price of ratelessness.
## 2. Experiment design — the block-size fact that drives everything
lzply's BCH block is NOT 4 KiB. `bch_poly_for_data` picks the smallest
m whose codeword holds the blob, and big blobs are split into blocks of
the m=22 poly: N = 2^22-1 = 4,194,303 bits, t=8 (default `-e 4`) — one
block holds **~512 KiB** with **8 correctable bit errors**. So:
- A 1 MiB file is 2 BCH blocks; a 4 MiB file is 8; a 16 MiB file is 32;
a 50 MiB file is 100.
- One failed block erases a contiguous run of symbols: at T=1024 B,
**512 symbols per block**. The outer layer's repair budget R must
cover whole 512-symbol multiples to survive even one block failure:
overhead >= 100/B % where B = blocks/file (B=2: 50%; B=8: 12.5%;
B=32: 3.1%; B=100: 1%).
- Repair symbols live on the same media, so they fail with the same
block model (the harness erases across all K+R symbols/blocks).
Legs (all schemes on the SAME erasure mask per trial — paired; 95%
Wilson CIs; full tables in `results/p4-summary.txt`):
- **Leg A**: iid symbol loss, K=100 T=1024, REAL foxsen decode,
5000 trials/cell, R in {0,2,5,10}, e in {0.001..0.10}.
- **Leg B**: Gilbert burst symbol loss (mean burst 4 / 16 symbols),
K=100, REAL decode, 5000 trials/cell, same R, e in {0.005..0.05}.
- **Leg C**: BCH-block failures, T=1024, block = 512 symbols.
K=1024 (B=2, 2000 trials, real) and K=4096 (B=8, 1000 trials, real);
K=16384 (B=32, 2000 trials, K+2 model + 50-trial real spots);
K=51200 (B=100, 2000 trials, K+2 model + 12-trial real spots at the
three cells where model and RS disagree most). q (per-block failure)
in {0.001..0.05}, overhead {0,2,5,10}%. Plus blockburst (mean burst
2 blocks) at K=4096 (real) and K=16384 (model).
- **Leg D (anchor)**: BER -> per-block failure q(p) = P(Bin(n,p) > 8),
Poisson table, validated against REAL `lzply_check` on damaged
50 MB archives (see §4).
## 3. Results
### Leg A — iid symbol loss, K=100, real decode (5000 trials/cell)
File recovery %, RaptorQ-real vs RS(MDS) vs BCH-alone:
| e | BCH | RQ-2% | RQ-5% | RQ-10% | RS-10% |
|---|---|---|---|---|---|
| 0.001 | 90.38 | 99.96 | 100.00 | 100.00 | 100.00 |
| 0.005 | 60.34 | 98.40 | 100.00 | 100.00 | 100.00 |
| 0.01 | 36.12 | 91.12 | 99.90 | 100.00 | 100.00 |
| 0.02 | 13.26 | 65.84 | 98.08 | 100.00 | 100.00 |
| 0.05 | 0.46 | 10.94 | 56.02 | 98.18 | 98.20 |
| 0.10 | 0.00 | 0.14 | 4.18 | 45.94 | 45.94 |
**RaptorQ ties RS everywhere: max gap 0.06 pts** (e=0.01 R=2: 91.12
vs 91.18; all other cells <= 0.02). The outer layer is a huge win
over BCH-alone on iid loss (e=0.01: 36% -> 100% at 10% overhead).
Real archive bytes as source (mixed-e4.lzply, 2000 trials, R=10,
e=0.02): iid 100.00%, Gilbert-b4 94.95% vs 95.78% on random source —
0.83 pts apart, ~1.4 sigma of seed noise; no content effect, as
expected (decode success depends only on the erasure pattern, not
the data values).
### Leg B — burst symbol loss, K=100, real decode (5000 trials/cell)
| burst | e | BCH | RQ-2% | RQ-5% | RQ-10% |
|---|---|---|---|---|---|
| 4 | 0.005 | 87.60 | 92.42 | 96.54 | 99.04 |
| 4 | 0.01 | 76.52 | 86.18 | 92.62 | 98.26 |
| 4 | 0.02 | 59.12 | 72.82 | 86.66 | 95.78 |
| 4 | 0.05 | 26.04 | 41.40 | 62.02 | 82.52 |
| 16 | 0.005 | 97.02 | 96.60 | 97.58 | 98.34 |
| 16 | 0.01 | 92.96 | 93.80 | 94.90 | 96.12 |
| 16 | 0.02 | 86.54 | 88.28 | 89.42 | 92.46 |
| 16 | 0.05 | 68.40 | 71.56 | 75.44 | 81.16 |
RaptorQ again ties RS (max gap 0.04 pts). Two burst lessons: long
bursts (16) leave most files untouched, so BCH-alone is already high
and the outer layer adds little (e=0.005: 97.02 -> 98.34 at 10%);
short bursts (4) spread damage across more files and the outer layer
adds a lot (e=0.02: 59.12 -> 95.78 at 10%).
### Leg C — BCH-block failures (the lzply-realistic leg)
File recovery % (rqreal where run, else the K+2 model as a LOWER
bound — see caveat below):
| K (B blocks) | q | BCH | RQ-2% | RQ-5% | RQ-10% |
|---|---|---|---|---|---|
| 1024 (2) | 0.01 | 97.55 | 98.05 | 98.55 | 97.90 |
| 1024 (2) | 0.05 | 91.00 | 90.65 | 90.45 | 89.75 |
| 4096 (8) | 0.01 | 93.20 | 91.70 | 91.70 | 92.20 |
| 4096 (8) | 0.05 | 64.90 | 65.10 | 68.60 | 65.50 |
| 16384 (32) | 0.01 | 71.30 | 71.55 | 95.05 | 99.85 |
| 16384 (32) | 0.02 | 53.60 | 53.15 | 86.55 | 99.75 |
| 16384 (32) | 0.05 | 20.00 | 19.20 | 48.25 | 89.35 |
| 51200 (100) | 0.01 | 37.95 | 73.35* | 99.40* | 100.00* |
| 51200 (100) | 0.02 | 13.35 | 39.75* | 94.05* | 100.00* |
| 51200 (100) | 0.05 | 0.75 | 3.20* | 37.35* | 95.55* |
(* = K+2 model only; real spots below.) Blockburst (2-block bursts)
at K=16384: q=0.01, BCH 86.15 -> RQ-5% 92.75, RQ-10% 97.70 — bursts
cost ~2-3 pts vs iid block failures at the same q, because a 2-block
burst (1024 symbols) exceeds the 5% budget (819) outright.
**The threshold is exact and total: at B=2 and B=8 the outer layer
is IDENTICAL to BCH-alone in every cell** (all four schemes agree to
the trial — one block failure erases 512 symbols, more than the
largest budget R=410). It only starts helping at B=32 (5%/10%
overheads; 2% still ties BCH: 71.55 vs 71.30 at q=0.01, because
R=328 < 512), and at B=100 every overhead helps. The rule is
overhead >= 100/B % to survive a single block failure.
### The K+2 model is a lower bound — real RaptorQ is closer to RS
The RFC rule of thumb (needs K+2 received symbols) UNDERSTATES real
RaptorQ badly at small R, because real decode usually succeeds at
K+0 (99.65%) and K+1 (100%): Leg A, e=0.02, R=2: model 13.16% vs
real 65.84%; R=5: 84.02% vs 98.08%. Overall model==real agreement is
94.96% of 350,300 real-decode trials, but the disagreements
concentrate exactly at the R boundary. Real-beats-RS: 0 trials;
RS-beats-real: 18 trials (all K+0/K+1/K+2 boundary cases) — i.e.
**real RaptorQ never beat the MDS bound and lost to it by at most a
handful of trials in 350k**. The K=51200 model columns (marked *)
are therefore lower bounds; the 12-trial real spots at the three
worst model-vs-RS cells confirm real RQ tracks RS, not the model.
K=51200 real spots (12 trials each): R=1024/q=0.01: real **11/12 =
RS 11/12** (model 9/12); R=1024/q=0.02: real **8/12 = RS 8/12**
(model 4/12 — the model understates by half here); R=2560/q=0.05:
real **7/12 = RS 7/12** (model 5/12). K=16384 real spots (50 trials
each): R=819 q=0.02: real 44/50 = RS 44/50 (model 43/50); R=1638:
50/50 everywhere. Real RQ == RS at every scale tested.
## 4. Bit-level anchor — BER -> block-failure cliff (validated live)
q(p) = P(Bin(n,p) > 8), Poisson (exact to ~1e-6 here):
| BER | m=22 block q (512 KiB) | m=20 block q (128 KiB) |
|---|---|---|
| 1e-7 | 7.6e-10 | 3.9e-15 |
| 5e-7 | 3.3e-4 | 5.2e-9 |
| 1e-6 | 0.0277 | 1.7e-6 |
| 2e-6 | 0.4615 | 3.3e-4 |
| 3e-6 | 0.8796 | 0.0051 |
| 5e-6 | 0.9989 | 0.0851 |
| 1e-5 | ~1.0 | 0.7191 |
Real-archive check (`damage` + `lzply_check`, 50 MB archive,
~100 m=22 blocks, measured BERs): 8.82e-08 -> PASS (37 bits
corrected, exactly the 37 inflicted, 0 uncorrectable); 4.96e-07 ->
PASS (208 corrected, 0 uncorrectable); 1.01e-06 -> FAIL (1
uncorrectable entry); 1.87e-06 -> FAIL; 9.94e-06 -> FAIL. The cliff
sits between 5e-7 (pass) and 1e-6 (fail), exactly as the table says.
In file terms: at BER 1e-6 a 50 MB file has q=0.028/block, so ~2-3
of its 100 blocks fail and the file is lost without an outer layer;
with 10% RaptorQ it recovers — the RS column reads 100.00% at
q=0.01 and 98.20% at q=0.05, and the spots show real RQ tracks RS,
so q=0.028 interpolates to ~99.5%.
## 5. Findings
1. **The outer layer works, but only for big files.** At B>=32
blocks/file (16+ MB) 5-10% overhead buys +24 to +62 pts of file
recovery at q=0.01-0.02. At B<=8 it buys exactly nothing at any
overhead <= 10% — a single 512 KiB block failure exceeds the
whole budget. Any deployment must gate the outer layer on file
size (or, equivalently, interleave symbols across blocks — not
tested; interleaving would turn a block failure into scattered
symbol damage inside many symbols, which an erasure code cannot
repair at all, so it is not an obvious fix).
2. **RaptorQ ties RS.** Across 350,300 real-decode trials RaptorQ
never beat the MDS bound and lost to it in 18 trials. At K=100
the max gap is 0.06 pts. The price of ratelessness is ~zero at
this scale — but so is its advantage for archival use, where the
redundancy is fixed at write time anyway. The experiment shows
the LAYER helps (at large B), not that RaptorQ specifically
beats RS. A GF(2^16) RS outer layer would do the same job, 2
symbols better; RaptorQ's edge is only operational (no
pre-commit to R, any K up to 56403, no 255-symbol cap).
3. **The K+2 model is a lower bound, not the truth.** Use real
decodes (or RS as the upper bound) for headline numbers; the
model understates RQ by up to ~50 pts at R=2.
4. **Both implementations are real RFC 6330.** They agree on the
overhead curve within noise; foxsen is ~10x faster and has a
passing 54-test suite; libRaptorQ is the canonical LGPL3 code
but needed one missing-include fix and its Eigen/lz4 deps.
5. **Speed is a deployment question, not a recovery one.**
foxsen: 43 MB/s @K=1024 down to ~15 MB/s @K=4096; a 50 MB
encode+decode took 3m26s single-threaded. Parallelises across
files; per-file latency at 50 MB is minutes, not seconds.
6. **No deployment change proposed.** This is research only. If
ever deployed, the gate would be: files with >= 32 BCH blocks,
5-10% repair stream stored alongside, RaptorQ or RS equivalent.
## Bugs caught (do not repeat)
1. p4 rqmod trivial case: the first version scored "all source
symbols arrived" as a K+2-model failure when repairs were also
lost (n_recv < K+2 with n_lost_src == 0). Fixed: trivial
recovery when nothing is missing, in both model and real paths.
2. summarize_p4.py prefers the largest-trials cell when a config
has both a model run and a real spot run — the K=16384 rqreal
spots were hidden behind the 2000-trial model cells in the
tables. Spots are reported separately (see §3 and the spot logs).
3. `pkill -f lrq_bench` self-matched the ssh command line that
contained the string (same trap as the poll.sh note in
AGENTS.md): use `pkill -f "lrq_bench[.]"` or a PID, never a bare
substring that appears in your own command.
4. Two-file stdin transfer: a second `cat > file` in the same ssh
invocation reads EOF after the first `cat` consumes stdin —
transfer one file per ssh call (the summarize script arrived
as 0 bytes this way and had to be re-sent).
5. `cd` inside a backgrounded `&&`-list does not change the
foreground shell's directory — the damage commands ran from
/root and failed; re-ran with absolute paths.
## Not started
- ~~Short LDPC protograph (Milestone 2.3) — assessment pending.~~ DONE,
see §6 below.
- No article: per instructions, the user reviews before any publish.
## 6. Milestone 2.3 — short LDPC protograph assessment: NO
### 6.1 Can a reliability signal be manufactured? No — and the reasons are structural
LDPC belief propagation needs per-bit reliabilities (LLRs). lzply's
channel is hard-decision: a bit is right or wrong, with no confidence
attached. Candidate sources, each assessed:
1. **Deep-repair time-of-arrival.** Deep repair records the LEVEL
(L0–L3) at which a block was repaired — a per-BLOCK signal, not
per-bit. It says nothing about which bits inside the block are
wrong. Too coarse for BP; at most it re-weights whole blocks.
2. **BCH syndrome weight / BM failure margin.** M2.1 Experiment C
measured this: syndrome weight is ANTI-correlated with burstiness
(AUC 0.18–0.39 unconditional; 0.47–0.49 at n=64 conditional on the
block being damaged). The syndrome is a global function of the
error pattern; it carries no per-bit information. No.
3. **Re-reads.** Bit-rot on archival media is stable: re-reading
returns the same bits. No new information (unless the medium
itself is marginal/noisy, which is not lzply's model). No.
4. **Compressed-data plausibility (LZ77 stream).** A wrong bit often
breaks decompression — a real signal, but at block granularity,
and localising WHICH bit is wrong requires trying flips and
checking validity, which is GRAND-style search, not a per-bit LLR
input to BP. It also only exists for compressed entries. Not a
usable reliability signal.
5. **RS/CRC oracle agreement.** Binary (right/wrong candidate), not
per-bit. No.
6. **Neighbouring-block failures.** A failed neighbour raises the
prior that this block has errors — again block-level, and it only
makes the prior more bursty, which GRAND-MO already models. No.
**Verdict: no per-bit reliability signal exists in lzply's channel.**
The LDPC thread therefore stands or falls on HARD-decision decoding.
### 6.2 Measured: hard-decision LDPC vs BCH, and what soft info would buy
Program: `randfec/ldpc_test.c` (PEG-constructed regular LDPC,
sequential bit-flipping = the standard stronger hard decoder;
sum-product BP with TRUE iid LLRs = the upper bound; real lzply
BCH+BM via p2's `bm_trial` verbatim). Same (message,error) stream per
scheme, 10,000 trials/cell, p2's six channels. Two builds:
- **(32,16) (3,6)-regular, PEG, girth 6 (0 4-cycles), d_min = 4**
(9 weight-4 codewords, exact enumeration). BCH m8t2 counterpart is
p2 g2 (d_min 5). BM replication matches p2 within noise
(scat-0.01: 99.68% here vs 99.53% in p2; scat-0.03: 93.04 vs 93.07).
- **(64,48) (3,12)-regular, PEG, 83-85 4-cycles.** Girth 6 is
IMPOSSIBLE here by counting: sum_v C(3,2) = 192 check-pair
incidences over C(16,2) = 120 check pairs, so at least 72
4-cycles for ANY (3,12)-regular code at this size. (A random
matrix is worse: ~80-118. The paper's (15,10) protograph must be
irregular and/or low-degree to avoid this; rate 3/4 at n=64 is
structurally hostile to LDPC.)
Repair rate % (misc = converged to a WRONG codeword; in lzply the
CRC16/SHA oracle would reject those, so they are already counted as
failures in the rates, not silent corruption):
**(32,16) — the fair test:**
| model | ldpc-bitflip | bch-bm | ldpc-softBP* |
|---|---|---|---|---|
| scat-p0.01 | 98.75 (misc 17) | 99.68 (0) | 99.67 (22) |
| scat-p0.03 | 88.88 (152) | 93.04 (0) | 94.90 (177) |
| burst-L8-0.01 | 96.55 (36) | 96.57 (0) | — |
| burst-L32-0.01 | 98.00 (53) | 97.99 (0) | — |
| burst-L8-0.03 | 89.57 (124) | 89.25 (1) | — |
| mix-L16-0.01 | 97.85 (36) | 97.81 (1) | — |
(* soft BP with TRUE LLRs, iid channels only — the upper bound.)
**(64,48) — the rate-3/4 case:**
| model | ldpc-bitflip | bch-bm | ldpc-softBP* |
|---|---|---|---|
| scat-p0.01 | 90.75 (74) | 97.21 (10) | 93.85 (77) |
| scat-p0.03 | 54.11 (290) | 70.23 (81) | 60.40 (189) |
| burst-L8-0.01 | 92.56 (49) | 93.37 (9) | — |
| burst-L32-0.01 | 96.83 (17) | 96.90 (6) | — |
| burst-L8-0.03 | 79.02 (109) | 80.79 (21) | — |
| mix-L16-0.01 | 95.99 (19) | 96.65 (7) | — |
### 6.3 Findings
1. **Hard-decision LDPC loses to BCH+BM on iid.** (32,16):
-4.16 pts at p=0.03 (88.88 vs 93.04), -0.93 at p=0.01. The
PEG code's d_min is 4 vs BCH's 5, and sequential bit-flipping
fixes only 71.7% of weight-2 errors (selftest: 1000/1000 at
weight 1, 717/1000 at weight 2 — tie-breaking between a correct
bit and an error bit that both show 2 unsatisfied checks).
BCH+BM fixes ALL weight ≤ 2 by construction.
2. **Soft information WOULD help — but only a little, and it does
not exist.** True-LLR soft BP beats BM by +1.86 pts at (32,16)
p=0.03 (94.90 vs 93.04) and ties at p=0.01. So the soft gap is
real (hard→soft is +6.02 pts at p=0.03) — but the prize for
manufacturing LLRs is under 2 pts over the deployed decoder,
and §6.1 says the LLRs cannot be manufactured. Not worth chasing.
3. **At rate 3/4, even soft information does not rescue LDPC.**
(64,48): TRUE-LLR soft BP scores 93.85/60.40 vs BM's 97.21/70.23
— it LOSES by 3-10 pts. The 4-cycle density (≥72 unavoidable)
breaks BP outright (selftest: soft BP fixes 1/200 weight-3
errors). The literature's +2.5 dB was at (15,10), rate 2/3,
with a designed protograph and soft decoding; it does not
transfer to lzply's rate-3/4 short blocks.
4. **On bursts, LDPC ties BM and both lose to GRAND-MO/CRC.**
Burst cells are ties within ±0.35 pts (both fail the same
heavy bursts); p2's CRC+GRAND-MO is 97.29/91.91 at burst-L8
vs LDPC/BM ~96.5/89.5. Nothing here changes the M1/M2.1
conclusion that the mixture GRAND decoder is the best short-
block decoder on lzply's channels.
5. **LDPC miscorrects far more than BM.** (32,16) p=0.03:
bit-flip 152, soft BP 177 wrong-codeword convergences per
10,000 trials vs BM 0. The oracle would catch them, but they
are lost repairs either way — and a decoder that converges
wrong 1.8% of the time is a poor fit for an archival format
that relies on the oracle as a backstop.
6. **Verdict: STOP the LDPC thread.** No reliability signal can
be manufactured (§6.1); hard-decision LDPC loses to the
deployed BCH+BM; the soft upper bound gains < 2 pts at the
fair test point and loses outright at rate 3/4. No further
LDPC work is recommended. (If soft information ever became
available — e.g. a future medium that returns read confidences
— the (32,16) soft-BP result says the gain over BM would be
~2 pts at BER 0.03, which bounds the value of that work.)
## Appendix — bugs caught in M2.2/M2.3 (do not repeat)
6. Random short LDPC is unusable: a random (3,12)-regular (64,48)
matrix has ~80 4-cycles and parallel bit-flipping fails even on
weight-1 errors (a correct variable sharing 2 checks with the
error flips too, then cascades). PEG with random restarts is the
minimum viable construction; at (32,16) it reaches 0 4-cycles.
7. Parallel Gallager-B oscillates at weight >= 2 even on girth-6
graphs (a correct variable can sit on two unsatisfied checks, one
from each error). Sequential single-bit flipping (max unsatisfied
checks, recompute each step) is the standard stronger hard
decoder; use it, not parallel.
8. `gcc ... | head -10` kills the compiler with SIGPIPE when the
warning stream exceeds 10 lines — the link never runs and the
binary is missing. Redirect compiler output to a file instead.
9. Hardcoded printf label: the matrix header said "(64,48)" for the
(32,16) build. Parameterise labels from the same -D flags as the
geometry; the numbers were unaffected (re-run bit-identical).
-170
View File
@@ -1,170 +0,0 @@
# Random equations with FEC-like properties — search report
Branch `experiments/randfec` (from lzply main `b27b345`). Research only:
nothing here touches lzply core. Program: `randfec/randfec.c` (C11,
stdlib only, `-O2`), driver scripts `run_sweep*.sh`, raw logs
`results/sweep*-*.log`. All numbers below come from those logs.
## What "FEC-like" means here (measured, not asserted)
For a code with n codeword bits, k data bits, r parity bits (n = k+r):
- `d_min` — minimum Hamming distance between distinct codewords.
Linear codes: exact by Gray-code enumeration (k <= 25). Nonlinear:
exact pairwise distance (k <= 10). Large k: low-weight-message
enumeration (`verify`, exact whenever d_min <= 6) plus syndrome
certification (all weight-<=t errors have distinct nonzero syndromes
<=> d_min >= 2t+1).
- `t = floor((d_min-1)/2)` — random-error correction radius.
- `b_max` — longest burst length such that *every* burst pattern of
length <= b_max has a distinct nonzero syndrome (the union over
lengths matters: Hamming(7,4) has b_max = 1, not 2, because a
length-1 burst aliases a length-2 burst).
- `A_dmin` — number of minimum-weight codewords (tie-breaker).
- Encode throughput, table-driven CRC where applicable.
Baselines on the same harness, same (n,k): CRC-16/CCITT-FALSE
shortened, BCH shortened (generator polys from `bch_polys.h`,
ids 0x0001..0x0004), RS quoted analytically (byte-symbol code).
## Headline result
**Random CRC polynomials win. Everything else tried does not.**
Random generator polynomials of degree r, scored exactly, beat the
shortened-BCH and CRC-16 baselines at every block size tested from
n=16 to n=64. ROT/XOR mixes, product codes, and nonlinear hybrids
all lose to plain random cyclic codes at the same (n,k). No new
system was found that beats random cyclic codes, so nothing is
proposed for integration on distance grounds. (RS keeps its niche:
see below.)
## Winners — random cyclic codes (family `cyclic`)
| n | k | r | best g | d_min | t | b_max | baseline at same (n,k) |
|---|---|---|--------|-------|---|-------|------------------------|
| 16 | 8 | 8 | 0x1d7 | 5 | 2 | 3 | BCH m8t1: 3/1 |
| 24 | 16 | 8 | 0x1f9 | 4 | 1 | 3 | BCH m8t1: 3/1 |
| 24 | 12 | 12 | 0x1343 | 6 | 2 | 6 | BCH m7t2 (r=14): 6/6 — same protection, 2 fewer parity bits |
| 32 | 16 | 16 | 0x109b1 | 7 | 3 | 7 | BCH m8t2: 6/6; CRC-16: 4/5 |
| 32 | 24 | 8 | 0x1e3 | 4 | 1 | 3 | BCH m8t1: 3/1 |
| 64 | 48 | 16 | 0x14669 | 6 | 2 | 6 | BCH m8t2: 5/6; CRC-16: 4/5 |
| 64 | 56 | 8 | 0x1cb | 4 | 1 | 2 | BCH m8t1: 3/1 |
Hit rates (random draws reaching the best d_min): n=16 r=8: 28/2000
reach 5; n=24 r=12: 486/2000 reach 6; n=32 r=16: 14/1000 reach 7;
n=64 r=16: 28/200 reach 6; n=64 r=8: 34/100 reach 4. Good random
codes are common, not rare — this is the Gilbert–Varshamov bound
doing its job at short lengths, where BCH's long-block structure is
wasted by shortening. Encode cost is unchanged: table-driven CRC,
~500 MB/s single-threaded scalar (measured), same as CRC-16.
Head-to-head against the product-code winners, same (n,k):
random cyclic reaches d_min 13 / b_max 11 at (35,8,r=27) and
d_min 12 / b_max 10 at (25,4,r=21).
## Rejects (with numbers)
- **ROT/XOR CRC** (`rotxor`, 11,000 candidates): never beats plain
cyclic at the same (n,k), usually worse. n=32 r=16: best d_min 6
vs cyclic 7. n=32 r=8: 836/1000 draws have d_min 2 (cyclic: 215),
15/1000 are degenerate (d_min 1 — the state machine collapses).
Expected in hindsight: rotations and XORs are linear over GF(2),
so this family is a reparameterisation of linear codes; the
rotation constraint only shrinks the fraction of good codes.
Also ~50x slower to encode (bit-serial only, ~7 MB/s, no table
form) for equal-or-worse distance.
- **Product codes, 2D/3D** (`product`, 1,850 configs): best d_min 9
at (35,8,r=27) and (25,4,r=21), b_max 9/8. Random cyclic at the
same (n,k) reaches d_min 13/12 and b_max 11/10. Burst bits per
parity bit 0.33 vs 0.41 for cyclic. The 2x2x2 parity cube
([27,8], d_min 8) also loses to random cyclic at the same size.
Only unmeasured virtue left: decoder simplicity (iterative
row/column checks, no Berlekamp–Massey). The d_min formula
(product of axis d_min) was verified against brute force on 1,460
configs, 0 mismatches.
- **Nonlinear hybrids** (`nonlin`, ~2,800 candidates; kinds: odd
multiply, add-message, add-byte-sum, nibble S-box, Fletcher):
best d_min 4 at (16,8,8) vs linear 5; best 5 at (24,8,16) vs
BCH 6 (b_max 2 vs 7). Fletcher at r=8 is degenerate (d_min 1:
the nibble-truncated variant ignores the high nibble — a
construction artifact, not a property of Fletcher); at r=16 its
best is 3. Nonlinearity costs distance here; nothing tested
beats the linear codes.
- **n=16, r=4**: all 2,000 random cyclic codes have d_min 2.
Structural: every odd degree-4 polynomial divides x^m+1 for
some m <= 15, so a weight-2 codeword always exists.
- **RS is not beaten, it is complemented.** RS(4,2) corrects an
aligned 2-byte burst with 16 parity bits = 1.00 burst-bit per
parity-bit; the best cyclic code at n=32 r=16 manages 7/16 =
0.44. RS still wins on aligned byte bursts; random cyclic wins
on scattered-bit correction (t=3 bits vs RS t=1 byte) and on
d_min. Different niches.
## Scaling: reuse fails, fresh search works
Reusing a small-block winner at n=64 regresses hard (verified
exactly with lowmsg + syndrome certification):
| poly | d_min at home size | d_min at n=64 | BCH at n=64, same r |
|------|--------------------|---------------|---------------------|
| 0x1d7 (r=8) | 5 @ n=16 | 2 | 3 |
| 0x1343 (r=12) | 6 @ n=24 | 4 | 5 (r=14) |
| 0x109b1 (r=16) | 7 @ n=32 | 5 | 5 |
But searching *at* n=64 recovers the edge: random search at
n=64 finds d_min 6 (r=16, vs BCH 5) and d_min 4 (r=8, vs BCH 3).
Lesson: the good codes are size-specific; search at the size you
deploy, do not carry polynomials up.
## Methodological findings (bugs caught by the harness itself)
- Random-sampling d_min at large k is unreliable: sampled d_min
said 13 for the n=64 r=8 winner while the true d_min is 2
(rare low-weight codewords are missed). Fixed with
low-weight-message enumeration (exact when d_min <= 6) and
syndrome certification; `verify` brackets d_min from both sides.
Two sampled n=64 sweeps were thrown out and redone.
- Burst correction must test the *union* of burst syndromes over
all lengths <= b, not each length separately (Hamming(7,4)
b_max is 1, not 2).
- Greedy-descent d_min search must forbid walking to the zero
codeword (m=0).
- Self-test: 9/9 pass (CRC-16 check value 0x29B1, rotxor==cyclic
at zero params, product d_min formula vs brute force, shortened
BCH meets designed distance, Hamming(7,4), single parity).
## Candidate counts
| family | candidates evaluated |
|--------|---------------------|
| cyclic (random CRC) | ~12,200 (10,000 @ n<=32, 600 head-to-head, 300 @ n=64 lowmsg, plus baselines/verifies) |
| rotxor | 11,000 |
| product (2D/3D) | 1,850 configs |
| nonlin | ~2,800 |
| **total** | **~27,500** |
## Reproduce
```
cd randfec && make && ./randfec selftest # 9/9 pass
./randfec baseline
bash run_sweep.sh all # stage 1: n<=32, all families (~3 min)
bash run_sweep2.sh # stage 2: exact k=24, head-to-head, scale
bash run_sweep3.sh # stage 3: verify/scale-up bracket
bash run_sweep4.sh # stage 4: baselines @ n=64, nonlin r=16
bash run_sweep5.sh # stage 5: search AT n=64 (lowmsg)
./randfec verify cyclic g=0x109b1 r=16 n=32 W=6 tmax=4
```
## Conclusion for integration
No candidate beats or genuinely complements the baselines in a way
that justifies new lzply machinery. The one actionable finding is
narrow and cheap: **at short block sizes, a randomly-searched CRC
polynomial beats the shortened-BCH polynomials lzply currently
uses** (e.g. d_min 7 vs 6 at n=32 r=16, d_min 5 vs 3 at n=16 r=8),
at identical encode cost (table-driven CRC) — but the decoder
would still be Berlekamp–Massey, and the win is one extra
correctable bit at small sizes. Whether that is worth a BCH-poly
swap is a separate decision; this job makes no integration change.
-316
View File
@@ -1,316 +0,0 @@
/* cuda_dmin.cu - GPU-accelerated d_min certification for cyclic codes.
*
* Certifies d_min >= 2t+1 for a cyclic (CRC-style) code by checking that
* all error patterns of weight <= t have distinct nonzero syndromes.
* One thread block per candidate polynomial; 256 threads cooperate.
* Syndromes live in a per-block epoch-tagged hash table in global memory
* (no clearing between candidates: epoch = candidate iteration + 1).
* Pattern enumeration: weight-1 singles, weight-2 pairs, weight-3
* triples (outer (i,j) pair per thread, inner k loop). t=2 or t=3.
*
* Host modes:
* sweep n r t ncand seed [outfile] GPU sweep, survivors to outfile
* cpu n r t ncand seed CPU reference (sort-based), timing
* xcheck n r t ncand seed GPU vs CPU bit-for-bit agreement
* cpucheck n r t polyfile sort-based certify of listed polys
* A candidate "passes" iff all weight<=t syndromes are distinct & nonzero.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <time.h>
#include <cuda_runtime.h>
#define LOGT 21
#define TSIZE (1u << LOGT)
#define TMASK (TSIZE - 1)
static uint64_t rng_s;
static void rng_seed(uint64_t s){ rng_s = s ? s : 0x9E3779B97F4A7C15ULL; }
static uint64_t rng_next(void){
uint64_t x = rng_s; x ^= x >> 12; x ^= x << 25; x ^= x >> 27;
rng_s = x; return x * 0x2545F4914F6CDD1DULL;
}
static double now_sec(void){
struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts);
return ts.tv_sec + ts.tv_nsec * 1e-9;
}
/* host poly_mod (also used by CPU path) */
static uint32_t poly_mod_h(uint64_t v, int deg_v, uint64_t g, int r){
for(int i = deg_v - 1; i >= r; i--)
if((v >> i) & 1ULL) v ^= (g << (i - r));
return (uint32_t)(v & ((r >= 64) ? ~0ULL : ((1ULL << r) - 1)));
}
static void single_syn_h(uint64_t g, int r, int n, uint32_t *s){
/* x^m mod g by linear recurrency: x^r == glow (mod g).
* The old (1ULL<<j)<<r form overflows for j+r >= 64 (n > 64). */
uint32_t mask = (r >= 32) ? 0xFFFFFFFFu : ((1u << r) - 1);
uint32_t glow = (uint32_t)(g & mask);
uint32_t pw[128];
uint32_t rem = 1; /* x^0 */
pw[0] = 1;
for(int m = 1; m < n; m++){
int top = (rem >> (r - 1)) & 1u;
rem = (uint32_t)((rem << 1) & mask);
if(top) rem ^= glow;
pw[m] = rem;
}
for(int i = 0; i < n; i++)
s[i] = (i < r) ? (1u << i) : pw[i];
}
/* ---------------- device ---------------- */
__device__ static uint32_t poly_mod_d(uint64_t v, int deg_v, uint64_t g, int r){
for(int i = deg_v - 1; i >= r; i--)
if((v >> i) & 1ULL) v ^= (g << (i - r));
return (uint32_t)(v & ((r >= 64) ? ~0ULL : ((1ULL << r) - 1)));
}
/* Insert syndrome v into this block's epoch-tagged table.
* Returns 1 if v was already present (duplicate), 0 if inserted.
* v != 0 is required. fail flag set by caller on duplicate. */
__device__ static __forceinline__ int table_insert(uint64_t *table, uint32_t v, uint32_t ep){
uint32_t h = (v * 2654435761u) >> (32 - LOGT);
uint64_t want = ((uint64_t)ep << 32) | v;
while(true){
uint64_t cur = table[h];
uint32_t cur_ep = (uint32_t)(cur >> 32);
if(cur_ep != ep){
uint64_t old = atomicCAS((unsigned long long *)&table[h],
(unsigned long long)cur,
(unsigned long long)want);
if(old == cur) return 0;
cur = old;
cur_ep = (uint32_t)(cur >> 32);
if(cur_ep != ep) continue;
}
if((uint32_t)cur == v) return 1; /* duplicate */
h = (h + 1) & TMASK;
}
}
__global__ void certify_kernel(const uint64_t *polys, uint8_t *pass, int ncand,
int n, int r, int tlevel, uint64_t *pool){
__shared__ uint32_t s[128];
__shared__ uint32_t pw[128];
__shared__ int fail;
__shared__ uint32_t ep;
int tid = threadIdx.x;
int nthreads = blockDim.x;
int bid = blockIdx.x;
uint64_t *table = pool + (size_t)bid * TSIZE;
for(int c = bid, it = 0; c < ncand; c += gridDim.x, it++){
if(tid == 0){ fail = 0; ep = (uint32_t)(it + 1); }
uint64_t g = polys[c];
if(tid == 0){
uint32_t mask = (r >= 32) ? 0xFFFFFFFFu : ((1u << r) - 1);
uint32_t glow = (uint32_t)(g & mask);
uint32_t rem = 1;
pw[0] = 1;
for(int m = 1; m < n; m++){
int top = (rem >> (r - 1)) & 1u;
rem = (uint32_t)((rem << 1) & mask);
if(top) rem ^= glow;
pw[m] = rem;
}
}
__syncthreads();
for(int i = tid; i < n; i += nthreads)
s[i] = (i < r) ? (1u << i) : pw[i];
__syncthreads();
uint32_t myep = ep;
/* weight 1 */
for(int i = tid; i < n && !fail; i += nthreads){
uint32_t v = s[i];
if(v == 0 || table_insert(table, v, myep)) atomicExch(&fail, 1);
}
__syncthreads();
if(fail){ __syncthreads(); continue; }
/* pair count C(n,2); thread's slice decoded to (i,j) */
long npair = (long)n * (n - 1) / 2;
for(long q = tid; q < npair && !fail; q += nthreads){
/* decode q -> (i,j), i<j */
long qq = q; int i = 0;
while(qq >= (n - 1 - i)){ qq -= (n - 1 - i); i++; }
int j = i + 1 + (int)qq;
uint32_t v = s[i] ^ s[j];
if(v == 0 || table_insert(table, v, myep)) atomicExch(&fail, 1);
if(tlevel >= 3){
/* triples (i,j,k), k>j */
for(int k = j + 1; k < n && !fail; k++){
uint32_t v3 = v ^ s[k];
if(v3 == 0 || table_insert(table, v3, myep)){ atomicExch(&fail, 1); break; }
}
}
}
__syncthreads();
if(tid == 0) pass[c] = fail ? 0 : 1;
__syncthreads();
}
}
/* ---------------- CPU reference (sort-based) ---------------- */
static int cmp_u32(const void *a, const void *b){
uint32_t x = *(const uint32_t *)a, y = *(const uint32_t *)b;
return (x > y) - (x < y);
}
/* certify one poly on CPU: 1 pass (dmin >= 2t+1), 0 fail. t = 2, 3 or 4. */
static int cpu_certify(uint64_t g, int n, int r, int t){
uint32_t s[128];
single_syn_h(g, r, n, s);
size_t cap = (size_t)n + (size_t)n * (n - 1) / 2;
if(t >= 3) cap += (size_t)n * (n - 1) * (n - 2) / 6;
if(t >= 4) cap += (size_t)n * (n - 1) * (n - 2) * (n - 3) / 24;
uint32_t *arr = (uint32_t *)malloc(cap * sizeof *arr);
size_t m = 0;
for(int i = 0; i < n; i++){
if(s[i] == 0){ free(arr); return 0; }
arr[m++] = s[i];
}
for(int i = 0; i < n; i++)
for(int j = i + 1; j < n; j++){
uint32_t v = s[i] ^ s[j];
if(v == 0){ free(arr); return 0; }
arr[m++] = v;
}
if(t >= 3)
for(int i = 0; i < n; i++)
for(int j = i + 1; j < n; j++)
for(int k = j + 1; k < n; k++){
uint32_t v = s[i] ^ s[j] ^ s[k];
if(v == 0){ free(arr); return 0; }
arr[m++] = v;
}
if(t >= 4)
for(int i = 0; i < n; i++)
for(int j = i + 1; j < n; j++)
for(int k = j + 1; k < n; k++)
for(int l = k + 1; l < n; l++){
uint32_t v = s[i] ^ s[j] ^ s[k] ^ s[l];
if(v == 0){ free(arr); return 0; }
arr[m++] = v;
}
qsort(arr, m, sizeof *arr, cmp_u32);
int ok = 1;
for(size_t i = 1; i < m; i++) if(arr[i] == arr[i - 1]){ ok = 0; break; }
free(arr);
return ok;
}
static uint64_t rand_poly(int r){
uint64_t low;
do { low = rng_next() & ((r >= 64) ? ~0ULL : ((1ULL << r) - 1)); }
while((low & 1ULL) == 0);
return (1ULL << r) | low;
}
#define CUDA_CHECK(x) do{ cudaError_t e = (x); if(e != cudaSuccess){ \
fprintf(stderr, "CUDA %s at %s:%d\n", cudaGetErrorString(e), __FILE__, __LINE__); return 1; } }while(0)
int main(int argc, char **argv){
if(argc < 2){
fprintf(stderr, "usage: cuda_dmin sweep|cpu|xcheck|cpucheck n r t ...\n");
return 1;
}
const char *mode = argv[1];
if(!strcmp(mode, "cpucheck")){
if(argc < 6){ fprintf(stderr, "cpucheck n r t polyfile\n"); return 1; }
int n = atoi(argv[2]), r = atoi(argv[3]), t = atoi(argv[4]);
FILE *f = fopen(argv[5], "r");
if(!f){ perror("polyfile"); return 1; }
char line[128];
while(fgets(line, sizeof line, f)){
uint64_t g = strtoull(line, NULL, 0);
if(!g) continue;
printf("0x%llx %s\n", (unsigned long long)g,
cpu_certify(g, n, r, t) ? "PASS" : "FAIL");
}
fclose(f);
return 0;
}
if(argc < 7){ fprintf(stderr, "usage: cuda_dmin sweep|cpu|xcheck n r t ncand seed [outfile]\n"); return 1; }
int n = atoi(argv[2]), r = atoi(argv[3]), t = atoi(argv[4]);
int ncand = atoi(argv[5]);
uint64_t seed = strtoull(argv[6], NULL, 0);
if(n < 8 || n > 128 || r < 4 || r > 32 || (t != 2 && t != 3 && t != 4) || ncand <= 0){
fprintf(stderr, "bad params (n 8..128, r 4..32, t 2|3|4)\n");
return 1;
}
if(t == 4 && strcmp(mode, "cpu") && strcmp(mode, "cpucheck")){ fprintf(stderr, "t=4 is CPU-only (cpu/cpucheck modes)\n"); return 1; }
rng_seed(seed);
uint64_t *polys = (uint64_t *)malloc((size_t)ncand * sizeof *polys);
for(int i = 0; i < ncand; i++) polys[i] = rand_poly(r);
printf("# cuda_dmin mode=%s n=%d r=%d t=%d (dmin>=%d) ncand=%d seed=0x%llx\n",
mode, n, r, t, 2 * t + 1, ncand, (unsigned long long)seed);
fflush(stdout);
if(!strcmp(mode, "cpu")){
double t0 = now_sec();
int npass = 0;
for(int i = 0; i < ncand; i++) npass += cpu_certify(polys[i], n, r, t);
double dt = now_sec() - t0;
printf("CPU ncand=%d pass=%d (%.3f%%) secs=%.2f cands_per_sec=%.1f\n",
ncand, npass, 100.0 * npass / ncand, dt, ncand / dt);
return 0;
}
/* GPU path */
int dev = 0;
cudaDeviceProp prop;
CUDA_CHECK(cudaGetDeviceProperties(&prop, dev));
printf("# gpu: %s %d SMs, %zu MB\n", prop.name, prop.multiProcessorCount,
prop.totalGlobalMem >> 20);
uint64_t *d_polys; uint8_t *d_pass;
CUDA_CHECK(cudaMalloc(&d_polys, (size_t)ncand * sizeof *d_polys));
CUDA_CHECK(cudaMalloc(&d_pass, (size_t)ncand));
CUDA_CHECK(cudaMemcpy(d_polys, polys, (size_t)ncand * sizeof *d_polys, cudaMemcpyHostToDevice));
int nblocks = 128;
size_t pool_bytes = (size_t)nblocks * TSIZE * sizeof(uint64_t);
uint64_t *pool;
CUDA_CHECK(cudaMalloc(&pool, pool_bytes));
CUDA_CHECK(cudaMemset(pool, 0, pool_bytes));
printf("# pool: %d blocks x 2^%d slots = %.2f GB\n", nblocks, LOGT, pool_bytes / 1e9);
fflush(stdout);
cudaEvent_t ev0, ev1;
cudaEventCreate(&ev0); cudaEventCreate(&ev1);
cudaEventRecord(ev0);
certify_kernel<<<nblocks, 256>>>(d_polys, d_pass, ncand, n, r, t, pool);
CUDA_CHECK(cudaGetLastError());
CUDA_CHECK(cudaDeviceSynchronize());
cudaEventRecord(ev1);
cudaEventSynchronize(ev1);
float ms = 0; cudaEventElapsedTime(&ms, ev0, ev1);
uint8_t *pass = (uint8_t *)malloc(ncand);
CUDA_CHECK(cudaMemcpy(pass, d_pass, ncand, cudaMemcpyDeviceToHost));
int npass = 0;
for(int i = 0; i < ncand; i++) npass += pass[i];
printf("GPU ncand=%d pass=%d (%.4f%%) secs=%.3f cands_per_sec=%.1f\n",
ncand, npass, 100.0 * npass / ncand, ms / 1000.0, ncand / (ms / 1000.0));
if(!strcmp(mode, "xcheck")){
double t0 = now_sec();
int bad = 0;
for(int i = 0; i < ncand; i++){
int c = cpu_certify(polys[i], n, r, t);
if(c != pass[i]){
if(bad < 5) printf("MISMATCH i=%d poly=0x%llx gpu=%d cpu=%d\n",
i, (unsigned long long)polys[i], pass[i], c);
bad++;
}
}
printf("XCHECK ncand=%d mismatches=%d cpu_secs=%.2f\n", ncand, bad, now_sec() - t0);
return bad ? 1 : 0;
}
if(argc > 7){
FILE *f = fopen(argv[7], "w");
if(!f){ perror("outfile"); return 1; }
for(int i = 0; i < ncand; i++)
if(pass[i]) fprintf(f, "0x%llx\n", (unsigned long long)polys[i]);
fclose(f);
printf("# survivors written to %s\n", argv[7]);
} else {
int shown = 0;
for(int i = 0; i < ncand && shown < 20; i++)
if(pass[i]){ printf("SURVIVOR 0x%llx\n", (unsigned long long)polys[i]); shown++; }
}
return 0;
}
-23
View File
@@ -1,23 +0,0 @@
/* fit_params.h - GENERATED by randfec/m2/mk_p3.py from fits2 json files.
* Gilbert models fitted to REAL lzply damage (see randfec/m2/fit.py).
* FIT_RUN: big-run4ff (nbits=419449016, ber=0.000762524).
* FIT_MIX: big-mix (nbits=419449016, ber=0.00126099).
* a=P(G->B), b=P(B->G), p0=flip prob in G, q1=flip prob in B.
* Do not hand-edit: regenerate with mk_p3.py after refitting. */
#ifndef FIT_PARAMS_H
#define FIT_PARAMS_H
#define FIT_RUN_A 2.155664090060564e-05
#define FIT_RUN_B 0.02845642285470762
#define FIT_RUN_P0 2.2603242979035746e-06
#define FIT_RUN_Q1 0.999997739675702
#define FIT_RUN_F 0.0007569582281611668
#define FIT_RUN_MEAN_BURST 35.141451373062075
#define FIT_RUN_MEAN_GAP 46389.41682105512
#define FIT_MIX_A 2.6838142963847655e-05
#define FIT_MIX_B 0.033926097644145316
#define FIT_MIX_P0 0.0004846915354771534
#define FIT_MIX_Q1 0.9834763956343967
#define FIT_MIX_F 0.0007904513215625152
#define FIT_MIX_MEAN_BURST 29.475833338956733
#define FIT_MIX_MEAN_GAP 37260.40215774433
#endif /* FIT_PARAMS_H */
-541
View File
@@ -1,541 +0,0 @@
// ldpc_test.c — M2.3 short-LDPC assessment: can hard-decision LDPC beat
// BCH, and what would soft information buy?
//
// Question (from ~/workspace/lzply-new-methods.md §5): a customised
// (15,10) LDPC beat BCH by 2.5 dB at BER 1e-4 — but with SOFT decoding.
// lzply's channel is hard-decision (a bit is right or wrong, no LLR).
// This program measures, on p2's exact channels and trial discipline
// (same (message,error) stream per scheme, 10,000 trials/cell):
// ldpc-bf : (N,K) regular LDPC, Gallager-B bit-flipping
// (hard decisions only — all lzply can supply).
// ldpc-sp : same LDPC, sum-product BP with TRUE iid LLRs (the
// upper bound: what soft information WOULD buy, if it
// existed). Run on the iid channels only, where the true
// LLR is well-defined.
// bch-bm : real lzply BCH m8t2 (poly 0x0004) + BM, p2's bm_trial
// verbatim (the deployed decoder to beat).
// Two builds (one source, -D flags):
// (32,16) (3,6)-regular — rate 1/2, girth-6 feasible via PEG,
// exact BCH counterpart (p2 g2). The fair test.
// (64,48) (3,12)-regular — rate 3/4; girth-6 is IMPOSSIBLE here by
// counting (sum_v C(dv,2)=192 > C(16,2)=120 check pairs), so it
// demonstrates the rate-3/4 structural failure of hard decoding.
//
// If ldpc-bf loses to bch-bm while ldpc-sp wins, the gap IS the missing
// reliability signal — and §5's "needs soft information" verdict is
// measured, not asserted. If ldpc-bf wins outright, LDPC is viable
// without soft info (unexpected).
//
// Build (on hot_house):
// gcc -O2 -std=c11 -D_POSIX_C_SOURCE=200809L -o ldpc_test ldpc_test.c ../bch.c -lm
// gcc -O2 -std=c11 -D_POSIX_C_SOURCE=200809L -DLDPC_N=64 -DLDPC_R=16 -DLDPC_K=48 -DLDPC_DV=3 -DLDPC_DC=12 -o ldpc_test64 ldpc_test.c ../bch.c -lm
// Usage:
// ./ldpc_test selftest
// ./ldpc_test matrix [trials] [seed]
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <math.h>
#include "../bch.h"
// LDPC geometry: compile-time parameters so both test points can be
// built from one source:
// (32,16) (3,6)-regular — rate 1/2, girth-6 feasible, exact BCH
// counterpart (p2 g2, bch-m8t2 + BM). Default build.
// (64,48) (3,12)-regular — rate 3/4; girth-6 is IMPOSSIBLE here by
// counting (see build note in build_ldpc), so it demonstrates
// the rate-3/4 structural failure of hard decoding.
// Build: gcc ... -DLDPC_N=32 -DLDPC_R=16 -DLDPC_K=16 -DLDPC_DV=3 -DLDPC_DC=6 ...
#ifndef LDPC_N
#define LDPC_N 32
#endif
#ifndef LDPC_R
#define LDPC_R 16
#endif
#ifndef LDPC_K
#define LDPC_K 16
#endif
#ifndef LDPC_DV
#define LDPC_DV 3
#endif
#ifndef LDPC_DC
#define LDPC_DC 6
#endif
#define N LDPC_N
#define R LDPC_R
#define K LDPC_K
#define DV LDPC_DV
#define DC LDPC_DC
#define KMASK ((K) >= 64 ? ~0ULL : ((1ULL << (K)) - 1ULL))
/* ---------------- PRNG: xorshift64* (same as p2) ---------------- */
static uint64_t rng_s;
static void rng_seed(uint64_t s){ rng_s = s ? s : 0x9E3779B97F4A7C15ULL; }
static uint64_t rng_next(void){
uint64_t x = rng_s; x ^= x >> 12; x ^= x << 25; x ^= x >> 27;
rng_s = x; return x * 0x2545F4914F6CDD1DULL;
}
static double rng_uniform(void){ return (rng_next() >> 11) * (1.0 / 9007199254740992.0); }
/* ---------------- damage channels (p2 verbatim) ---------------- */
typedef struct { double a, b, p0, q1, f; } gmodel_t;
typedef struct { int kind; double p; gmodel_t gm; } chan_t;
static uint64_t chan_draw(const chan_t *ch, int n){
uint64_t e = 0;
if(ch->kind == 0){
for(int i = 0; i < n; i++)
if(rng_uniform() < ch->p) e |= 1ULL << i;
return e;
}
int state = (rng_uniform() < ch->gm.f) ? 1 : 0;
for(int i = 0; i < n; i++){
double fp = state ? ch->gm.q1 : ch->gm.p0;
if(rng_uniform() < fp) e |= 1ULL << i;
double u = rng_uniform();
state = state ? ((u < ch->gm.b) ? 0 : 1) : ((u < ch->gm.a) ? 1 : 0);
}
return e;
}
static chan_t chan_burst(double L, double ber, double p0, double q1){
chan_t ch; ch.kind = 1;
double f = (ber - p0) / (q1 - p0);
double b = 1.0 / L;
ch.gm.b = b; ch.gm.a = f * b / (1.0 - f);
ch.gm.p0 = p0; ch.gm.q1 = q1; ch.gm.f = f;
ch.p = ber;
return ch;
}
/* ---------------- BM baseline via real lzply bch.c (p2 verbatim) ---------------- */
static void msg_to_data(uint64_t msg, int k, int D, uint8_t *data){
memset(data, 0, D);
for(int j = 0; j < k; j++){
if((msg >> j) & 1ULL){
int s = k - 1 - j;
data[s / 8] |= (uint8_t)(1u << (7 - (s % 8)));
}
}
}
static int bm_trial(uint64_t msg, uint64_t e, const bch_poly_t *poly, int D, int n){
uint8_t data[64], enc[128], cor[128], dec[64];
msg_to_data(msg, 8 * D, D, data);
size_t slen = bch_block_stored_len(D, poly);
if(bch_encode_block(data, D, poly, enc) != 0) return 0;
memcpy(cor, enc, slen);
for(int i = 0; i < n; i++){
if((e >> i) & 1ULL){
int s = n - 1 - i;
cor[s / 8] ^= (uint8_t)(1u << (7 - (s % 8)));
}
}
int corr = 0;
int rc = bch_decode_block(cor, slen, D, poly, dec, &corr);
if(rc != 0) return 0;
return (memcmp(dec, data, D) == 0) ? 1 : -1;
}
/* ---------------- LDPC (64,48) (3,12)-regular ---------------- */
/* H as bitmask rows: hrow[i] = 64-bit mask of variables in check i.
* vneigh[j] = list of DV checks touching variable j. */
static uint64_t hrow[R];
static int vneigh[N][DV];
static int cneigh[R][DC];
/* Systematic encoder: pivot columns + RREF rows over GF(2).
* After build_ldpc: piv[c] = pivot column of check c (after elimination),
* and for each pivot column, prow[c] = mask of FREE columns it depends on. */
static int piv[R];
static uint64_t prow[R];
static int n4cycles = -1;
static int gf2_rank64(uint64_t *rows, int nrows) {
int r = 0;
for (int c = 0; c < N && r < nrows; c++) {
int p = -1;
for (int i = r; i < nrows; i++) if ((rows[i] >> c) & 1ULL) { p = i; break; }
if (p < 0) continue;
uint64_t t = rows[r]; rows[r] = rows[p]; rows[p] = t;
for (int i = 0; i < nrows; i++)
if (i != r && ((rows[i] >> c) & 1ULL)) rows[i] ^= rows[r];
r++;
}
return r;
}
static int peg_attempt(uint64_t *hout) {
// One PEG pass with random variable order and random tie-breaks.
// Returns the 4-cycle count (0 = girth >= 6).
uint64_t h[R]; memset(h, 0, sizeof h);
int cdeg[R]; memset(cdeg, 0, sizeof cdeg);
int vadj[N][DV];
int vdeg[N]; memset(vdeg, 0, sizeof vdeg);
int order[N]; for (int j = 0; j < N; j++) order[j] = j;
for (int j = N - 1; j > 0; j--) {
int k = (int)(rng_next() % (uint64_t)(j + 1));
int t = order[j]; order[j] = order[k]; order[k] = t;
}
for (int oj = 0; oj < N; oj++) {
int j = order[oj];
for (int e = 0; e < DV; e++) {
int cdepth[R]; for (int i = 0; i < R; i++) cdepth[i] = -1;
char vseen[N]; memset(vseen, 0, sizeof vseen);
int q_is[256], q_id[256], q_d[256], qh = 0, qt = 0;
vseen[j] = 1;
q_is[qt] = 0; q_id[qt] = j; q_d[qt] = 0; qt++;
while (qh < qt) {
int isc = q_is[qh], id = q_id[qh], d = q_d[qh]; qh++;
if (!isc) {
for (int k = 0; k < vdeg[id]; k++) {
int c = vadj[id][k];
if (cdepth[c] < 0) {
cdepth[c] = d + 1;
q_is[qt] = 1; q_id[qt] = c; q_d[qt] = d + 1; qt++;
}
}
} else {
for (int v = 0; v < N; v++) {
if (!((h[id] >> v) & 1ULL)) continue;
if (!vseen[v]) {
vseen[v] = 1;
q_is[qt] = 0; q_id[qt] = v; q_d[qt] = d + 1; qt++;
}
}
}
}
int best = -1, bestdepth = -2, bestdeg = 1 << 30;
for (int c = 0; c < R; c++) {
if (cdeg[c] >= DC) continue;
int dd = (cdepth[c] < 0) ? 1000 : cdepth[c];
if (dd > bestdepth || (dd == bestdepth && cdeg[c] < bestdeg)) {
best = c; bestdepth = dd; bestdeg = cdeg[c];
} else if (dd == bestdepth && cdeg[c] == bestdeg && (rng_next() & 1)) {
best = c; // random tie-break
}
}
if (best < 0) return -1;
h[best] |= 1ULL << j;
vadj[j][vdeg[j]++] = best;
cdeg[best]++;
}
}
for (int i = 0; i < R; i++) if (cdeg[i] != DC) return -1;
uint64_t hc[R]; memcpy(hc, h, sizeof h);
if (gf2_rank64(hc, R) < R) return -1;
int c4 = 0;
for (int a = 0; a < R; a++) for (int b = a + 1; b < R; b++) {
int cnt = __builtin_popcountll(h[a] & h[b]);
if (cnt >= 2) c4 += cnt * (cnt - 1) / 2;
}
memcpy(hout, h, sizeof h);
return c4;
}
static void build_ldpc(void) {
// PEG with random restarts; keep the fewest-4-cycle matrix.
// (At (32,16) 0 is feasible by counting; at (64,48) the minimum
// is 72 — see the counting bound in the header.)
uint64_t best_h[R]; int best4 = 1 << 30;
for (int att = 0; att < 200; att++) {
uint64_t h[R];
int c4 = peg_attempt(h);
if (c4 < 0) continue;
if (c4 < best4) { best4 = c4; memcpy(best_h, h, sizeof h); if (c4 == 0) break; }
}
if (best4 == (1 << 30)) { fprintf(stderr, "ldpc build failed\n"); exit(1); }
memcpy(hrow, best_h, sizeof hrow);
n4cycles = best4;
// neighbor lists
for (int j = 0; j < N; j++) {
int d = 0;
for (int i = 0; i < R; i++) if ((hrow[i] >> j) & 1ULL) vneigh[j][d++] = i;
if (d != DV) { fprintf(stderr, "var %d degree %d\n", j, d); exit(1); }
}
for (int i = 0; i < R; i++) {
int d = 0;
for (int j = 0; j < N; j++) if ((hrow[i] >> j) & 1ULL) cneigh[i][d++] = j;
if (d != DC) { fprintf(stderr, "check %d degree %d\n", i, d); exit(1); }
}
// systematic form: RREF of H with column pivots
uint64_t rows[R]; memcpy(rows, hrow, sizeof rows);
int colof[R]; // row -> pivot col
int r = 0;
for (int c = 0; c < N && r < R; c++) {
int p = -1;
for (int i = r; i < R; i++) if ((rows[i] >> c) & 1ULL) { p = i; break; }
if (p < 0) continue;
uint64_t t = rows[r]; rows[r] = rows[p]; rows[p] = t;
for (int i = 0; i < R; i++)
if (i != r && ((rows[i] >> c) & 1ULL)) rows[i] ^= rows[r];
colof[r] = c; r++;
}
if (r < R) { fprintf(stderr, "ldpc rank fail\n"); exit(1); }
// pivot set + per-pivot free-column masks
char is_piv[N]; memset(is_piv, 0, sizeof is_piv);
for (int i = 0; i < R; i++) { piv[i] = colof[i]; is_piv[colof[i]] = 1; }
for (int i = 0; i < R; i++) {
uint64_t m = 0;
for (int j = 0; j < N; j++)
if (!is_piv[j] && ((rows[i] >> j) & 1ULL)) m |= 1ULL << j;
prow[i] = m;
}
}
/* Encode: free columns (48) carry the message bits in order; pivot bits
* are the XOR of their free-column masks. Message = low 48 bits of msg. */
static uint64_t ldpc_encode(uint64_t msg) {
char is_piv[N]; memset(is_piv, 0, sizeof is_piv);
for (int i = 0; i < R; i++) is_piv[piv[i]] = 1;
uint64_t c = 0;
int fi = 0;
for (int j = 0; j < N; j++)
if (!is_piv[j]) { if ((msg >> fi) & 1ULL) c |= 1ULL << j; fi++; }
for (int i = 0; i < R; i++) {
int bit = __builtin_parityll(c & prow[i]);
if (bit) c |= 1ULL << piv[i];
}
return c;
}
static int ldpc_syndrome0(uint64_t c) {
for (int i = 0; i < R; i++)
if (__builtin_parityll(c & hrow[i])) return 0;
return 1;
}
/* Sequential bit-flipping: each iteration flip the single variable with
* the most unsatisfied checks (needs >= 2 of DV), recompute, repeat.
* Parallel Gallager-B flips all such variables at once and oscillates
* on 4-cycle-free graphs too at weight >= 2 (a correct variable can
* sit on two unsatisfied checks, one from each error); sequential
* flipping is the standard stronger hard-decision decoder and is still
* purely hard-decision (no LLRs). Returns 1/0/-1 as before. */
static int ldpc_bitflip(uint64_t rx, uint64_t tx) {
uint64_t x = rx;
for (int it = 0; it < 200; it++) {
if (ldpc_syndrome0(x)) return (x == tx) ? 1 : -1;
int best = -1, bestu = 1;
for (int j = 0; j < N; j++) {
int unsat = 0;
for (int d = 0; d < DV; d++)
if (__builtin_parityll(x & hrow[vneigh[j][d]])) unsat++;
if (unsat > bestu) { bestu = unsat; best = j; }
}
if (best < 0) return 0; // stuck: no variable looks wrong
x ^= 1ULL << best;
}
return ldpc_syndrome0(x) ? ((x == tx) ? 1 : -1) : 0;
}
/* Sum-product BP with TRUE iid LLRs (upper bound). L = log((1-p)/p).
* Returns 1/0/-1 as above. */
static int ldpc_softbp(uint64_t rx, uint64_t tx, double p) {
double L = log((1.0 - p) / p);
static double v2c[N][DV], c2v[R][DC];
double ch[N];
for (int j = 0; j < N; j++) {
ch[j] = ((rx >> j) & 1ULL) ? -L : L;
for (int d = 0; d < DV; d++) v2c[j][d] = ch[j];
}
for (int it = 0; it < 50; it++) {
// check -> variable
for (int i = 0; i < R; i++) {
for (int a = 0; a < DC; a++) {
double prod = 1.0;
for (int b = 0; b < DC; b++) {
if (b == a) continue;
int v = cneigh[i][b];
int d = 0; while (vneigh[v][d] != i) d++;
prod *= tanh(0.5 * v2c[v][d]);
}
if (prod > 0.999999999999) prod = 0.999999999999;
if (prod < -0.999999999999) prod = -0.999999999999;
double m = 2.0 * atanh(prod);
if (m > 50.0) m = 50.0; if (m < -50.0) m = -50.0;
c2v[i][a] = m;
}
}
// hard decision from posteriors
uint64_t x = 0;
for (int j = 0; j < N; j++) {
double post = ch[j];
for (int d = 0; d < DV; d++) {
int i = vneigh[j][d];
int a = 0; while (cneigh[i][a] != j) a++;
post += c2v[i][a];
}
if (post < 0) x |= 1ULL << j;
}
if (ldpc_syndrome0(x)) return (x == tx) ? 1 : -1;
// variable -> check
for (int j = 0; j < N; j++) {
for (int d = 0; d < DV; d++) {
double s = ch[j];
for (int d2 = 0; d2 < DV; d2++) {
if (d2 == d) continue;
int i = vneigh[j][d2];
int a = 0; while (cneigh[i][a] != j) a++;
s += c2v[i][a];
}
if (s > 50.0) s = 50.0; if (s < -50.0) s = -50.0;
v2c[j][d] = s;
}
}
}
return 0;
}
static int selftest(void) {
int fails = 0;
rng_seed(12345);
build_ldpc();
printf("ldpc built: 4-cycles=%d\n", n4cycles);
// debug: fixed message, single error at bit 5, trace bit-flip
{
uint64_t m = 0x12345ULL & KMASK;
uint64_t c = ldpc_encode(m);
printf("debug: syndrome0(codeword)=%d\n", ldpc_syndrome0(c));
uint64_t x = c ^ (1ULL << 5);
for (int it = 0; it < 4; it++) {
int sw = 0;
for (int i = 0; i < R; i++) if (__builtin_parityll(x & hrow[i])) sw++;
printf("debug it=%d synw=%d x==c? %d\n", it, sw, x == c);
if (sw == 0) break;
int best = -1, bestu = 1;
for (int j = 0; j < N; j++) {
int unsat = 0;
for (int d = 0; d < DV; d++)
if (__builtin_parityll(x & hrow[vneigh[j][d]])) unsat++;
if (unsat > bestu) { bestu = unsat; best = j; }
}
printf("debug flip bit %d (unsat %d)\n", best, bestu);
if (best < 0) break;
x ^= 1ULL << best;
}
}
// codewords have zero syndrome; encode is injective on messages
for (int t = 0; t < 1000; t++) {
uint64_t m = rng_next() & KMASK; // 48-bit message
uint64_t c = ldpc_encode(m);
if (!ldpc_syndrome0(c)) { printf("SELFTEST FAIL syndrome\n"); fails++; break; }
if (ldpc_encode(m) != c) { printf("SELFTEST FAIL determinism\n"); fails++; break; }
}
// bit-flip fixes all weight-1 errors (1000 samples); weight-2 is
// measured, not required perfect (sequential flipping can still
// stall on some weight-2 patterns; the matrix reports the rate).
for (int w = 1; w <= 2; w++) {
int ok = 0;
for (int t = 0; t < 1000; t++) {
uint64_t m = rng_next() & KMASK;
uint64_t c = ldpc_encode(m);
uint64_t e = 0;
while (__builtin_popcountll(e) < w) {
int j = (int)(rng_next() % N);
e |= 1ULL << j;
}
if (ldpc_bitflip(c ^ e, c) == 1) ok++;
}
printf("bitflip weight-%d: %d/1000\n", w, ok);
if (w == 1 && ok != 1000) { printf("SELFTEST FAIL bitflip w=1\n"); fails++; }
// w=2 threshold only for the girth-6 build (N=32); the (64,48)
// code is structurally 4-cycle-dense and its w=2 rate is the
// measurement, not a bug check.
if (w == 2 && N == 32 && ok < 600) { printf("SELFTEST FAIL bitflip w=2 low\n"); fails++; }
}
// soft BP fixes weight-1..3 on iid p=0.01 (LLR from p)
for (int w = 1; w <= 3 && !fails; w++) {
int ok = 0;
for (int t = 0; t < 200; t++) {
uint64_t m = rng_next() & KMASK;
uint64_t c = ldpc_encode(m);
uint64_t e = 0;
while (__builtin_popcountll(e) < w) {
int j = (int)(rng_next() % N);
e |= 1ULL << j;
}
if (ldpc_softbp(c ^ e, c, 0.01) == 1) ok++;
}
printf("softbp weight-%d: %d/200\n", w, ok);
// sanity bound only, N=32 build: whether BP is broken shows up
// as a much lower number; the exact w=3 rate depends on the
// code's trapping sets (see the dmin subcommand). The (64,48)
// build is report-only (its 4-cycle density breaks BP outright).
if (N == 32 && ok < 100) { printf("SELFTEST FAIL softbp w=%d\n", w); fails++; }
}
// BM baseline sanity (p2's selftest equivalent): 1-bit fix
const bch_poly_t *poly = bch_poly_by_id(0x0004);
int ok = 0;
for (int t = 0; t < 200; t++) {
uint64_t m = rng_next() & KMASK;
if (bm_trial(m, 1ULL << (rng_next() % N), poly, K/8, N) == 1) ok++;
}
printf("bm 1-bit: %d/200\n", ok);
if (ok != 200) fails++;
printf(fails ? "SELFTEST %d FAILURES\n" : "SELFTEST ALL PASS\n", fails);
return fails ? 1 : 0;
}
int main(int argc, char **argv) {
if (argc > 1 && !strcmp(argv[1], "selftest")) return selftest();
if (argc > 1 && !strcmp(argv[1], "dmin")) {
// Exact minimum distance by enumerating all 2^K codewords.
// Only feasible for small K (the (32,16) build).
if (K > 20) { fprintf(stderr, "dmin: K=%d too big to enumerate\n", K); return 2; }
rng_seed(424242);
build_ldpc();
printf("# ldpc (%d,%d) 4-cycles=%d\n", N, K, n4cycles);
long spectrum[12]; memset(spectrum, 0, sizeof spectrum);
int dmin = N + 1;
uint64_t total = 1ULL << K;
for (uint64_t m = 1; m < total; m++) {
int w = __builtin_popcountll(ldpc_encode(m));
if (w <= 11) spectrum[w]++;
if (w < dmin) dmin = w;
}
printf("d_min=%d\n", dmin);
for (int w = 1; w <= 11; w++)
if (spectrum[w]) printf("weight %d: %ld codewords\n", w, spectrum[w]);
return 0;
}
int trials = argc > 2 ? atoi(argv[2]) : 10000;
uint64_t seed = argc > 3 ? strtoull(argv[3], NULL, 10) : 777;
rng_seed(424242);
build_ldpc();
printf("# ldpc (%d,%d) (%d,%d)-regular, 4-cycles=%d\n", N, K, DV, DC, n4cycles);
printf("# trials=%d seed=%llu\n", trials, (unsigned long long)seed);
rng_seed(seed);
const bch_poly_t *poly = bch_poly_by_id(0x0004);
if (!poly) { fprintf(stderr, "no bch poly\n"); return 1; }
struct { const char *name; chan_t ch; } models[6];
int nm = 0;
models[nm].name = "scat-p0.01"; models[nm].ch.kind = 0; models[nm].ch.p = 0.01; nm++;
models[nm].name = "scat-p0.03"; models[nm].ch.kind = 0; models[nm].ch.p = 0.03; nm++;
models[nm].name = "burst-L8-BER0.01"; models[nm].ch = chan_burst(8, 0.01, 0.0, 0.95); nm++;
models[nm].name = "burst-L32-BER0.01"; models[nm].ch = chan_burst(32, 0.01, 0.0, 0.95); nm++;
models[nm].name = "burst-L8-BER0.03"; models[nm].ch = chan_burst(8, 0.03, 0.0, 0.95); nm++;
models[nm].name = "mix-L16-BER0.01"; models[nm].ch = chan_burst(16, 0.01, 0.002, 0.95); nm++;
for (int mi = 0; mi < nm; mi++) {
long bf_ok = 0, bf_misc = 0, sp_ok = 0, sp_misc = 0, bm_ok = 0, bm_misc = 0;
int is_iid = models[mi].ch.kind == 0;
for (int t = 0; t < trials; t++) {
uint64_t m = rng_next() & KMASK;
uint64_t e = chan_draw(&models[mi].ch, N);
uint64_t tx = ldpc_encode(m);
uint64_t rx = tx ^ e;
int r = ldpc_bitflip(rx, tx);
if (r == 1) bf_ok++; else if (r == -1) bf_misc++;
if (is_iid) {
int s = ldpc_softbp(rx, tx, models[mi].ch.p);
if (s == 1) sp_ok++; else if (s == -1) sp_misc++;
}
int b = bm_trial(m, e, poly, K/8, N);
if (b == 1) bm_ok++; else if (b == -1) bm_misc++;
}
printf("%-18s trials=%d bf=%ld (%.2f%%, misc %ld) bm=%ld (%.2f%%, misc %ld)",
models[mi].name, trials, bf_ok, 100.0 * bf_ok / trials, bf_misc,
bm_ok, 100.0 * bm_ok / trials, bm_misc);
if (is_iid) printf(" sp-trueLLR=%ld (%.2f%%, misc %ld)", sp_ok, 100.0 * sp_ok / trials, sp_misc);
printf("\n");
fflush(stdout);
}
return 0;
}
-118
View File
@@ -1,118 +0,0 @@
/* damage.c - apply realistic corruption to a real lzply archive.
*
* Usage:
* damage <orig> <out> iid <ber> <seed>
* damage <orig> <out> runs <runlen_bytes> <runs_per_MB> <xor:ff|rand|zero> <seed>
* damage <orig> <out> mix <ber_bg> <runlen_bytes> <runs_per_MB> <xor> <seed>
*
* Modes mirror the project's own test corrupters (tests/corrupt_bits.c
* = scattered single-bit flips, tests/corrupt_run.c = contiguous byte
* run XOR 0xff) but with calibrated rates and exact BER accounting:
* the reported BER is measured by comparing orig vs out byte by byte,
* not by counting what was requested (overlapping runs, random-xor
* bytes that happen to equal the original, etc. all show up in the
* measured number). Deterministic for a given seed.
*
* The XOR of orig vs out is exactly the channel error pattern on the
* stored BCH codeword bits, so fit.py can fit a channel model to it.
*/
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <math.h>
static uint64_t rng_s;
static void rng_seed(uint64_t s){ rng_s = s ? s : 0x9E3779B97F4A7C15ULL; }
static uint64_t rng_next(void){
uint64_t x = rng_s; x ^= x >> 12; x ^= x << 25; x ^= x >> 27;
rng_s = x; return x * 0x2545F4914F6CDD1DULL;
}
static double rng_uniform(void){ return (rng_next() >> 11) * (1.0 / 9007199254740992.0); }
static uint8_t *read_all(const char *path, long *size_out){
FILE *f = fopen(path, "rb");
if(!f){ perror("open"); exit(1); }
fseek(f, 0, SEEK_END);
long n = ftell(f);
fseek(f, 0, SEEK_SET);
uint8_t *buf = malloc(n ? n : 1);
if(!buf){ fprintf(stderr, "oom\n"); exit(1); }
if(n && fread(buf, 1, n, f) != (size_t)n){ fprintf(stderr, "short read\n"); exit(1); }
fclose(f);
*size_out = n;
return buf;
}
int main(int argc, char **argv){
if(argc < 5){ fprintf(stderr, "usage: damage <orig> <out> iid|runs|mix ...\n"); return 1; }
long size;
uint8_t *orig = read_all(argv[1], &size);
uint8_t *out = malloc(size ? size : 1);
memcpy(out, orig, size);
const char *mode = argv[3];
long runs_done = 0;
if(!strcmp(mode, "iid")){
double ber = atof(argv[4]);
rng_seed(strtoull(argv[5], NULL, 0));
/* geometric skipping: gap in bits ~ Geom(ber) */
double log1m = log(1.0 - ber);
long pos = (long)(log(1.0 - rng_uniform()) / log1m); /* first flip bit */
while(pos < 8 * size){
out[pos / 8] ^= (uint8_t)(1u << (7 - (pos % 8)));
long gap = (long)(log(1.0 - rng_uniform()) / log1m) + 1;
pos += gap;
}
} else if(!strcmp(mode, "runs") || !strcmp(mode, "mix")){
double ber_bg = 0.0;
long runlen; double per_mb; const char *xorname; uint64_t seed;
if(!strcmp(mode, "runs")){
runlen = atol(argv[4]); per_mb = atof(argv[5]);
xorname = argv[6]; seed = strtoull(argv[7], NULL, 0);
} else {
ber_bg = atof(argv[4]); runlen = atol(argv[5]); per_mb = atof(argv[6]);
xorname = argv[7]; seed = strtoull(argv[8], NULL, 0);
}
rng_seed(seed);
if(ber_bg > 0.0){
double log1m = log(1.0 - ber_bg);
long pos = (long)(log(1.0 - rng_uniform()) / log1m);
while(pos < 8 * size){
out[pos / 8] ^= (uint8_t)(1u << (7 - (pos % 8)));
long gap = (long)(log(1.0 - rng_uniform()) / log1m) + 1;
pos += gap;
}
}
long nruns = (long)(per_mb * ((double)size / 1048576.0) + 0.5);
for(long r = 0; r < nruns; r++){
long start = (long)(rng_uniform() * (double)(size - runlen + 1));
if(start < 0) start = 0;
for(long i = 0; i < runlen && start + i < size; i++){
uint8_t m;
if(!strcmp(xorname, "ff")) m = 0xff;
else if(!strcmp(xorname, "rand")) m = (uint8_t)rng_next();
else if(!strcmp(xorname, "zero")) m = out[start + i]; /* set byte to 0 */
else { fprintf(stderr, "bad xor %s\n", xorname); return 1; }
out[start + i] ^= m;
}
runs_done++;
}
} else { fprintf(stderr, "bad mode %s\n", mode); return 1; }
/* exact measured stats: compare orig vs out */
long bytes_changed = 0, bits = 0;
for(long i = 0; i < size; i++){
uint8_t d = orig[i] ^ out[i];
if(d){ bytes_changed++; bits += __builtin_popcount(d); }
}
FILE *f = fopen(argv[2], "wb");
if(!f){ perror("open out"); return 1; }
if(size && fwrite(out, 1, size, f) != (size_t)size){ fprintf(stderr, "short write\n"); return 1; }
fclose(f);
printf("DAMAGE mode=%s size=%ld bytes_changed=%ld bits_flipped=%ld ber=%.6g runs=%ld\n",
mode, size, bytes_changed, bits,
size ? (double)bits / (8.0 * (double)size) : 0.0, runs_done);
return 0;
}
-217
View File
@@ -1,217 +0,0 @@
#!/usr/bin/env python3
"""fit.py - fit a Gilbert 2-state burst channel to real lzply damage.
Usage: fit.py <orig> <corrupt> <name> [--outdir DIR]
Reads orig vs corrupt archives, takes the XOR as the channel error
pattern on the stored BCH codeword bits, and:
1. reports observed statistics (BER, lag-k P(11) joints, mean 1-run
/ 0-run, max 1-run, window-weight histograms for w=32/64),
2. fits a Gilbert model (a=P(G->B), b=P(B->G), p0=flip prob in G,
q1=flip prob in B) by matching 5 moments (BER + lag-1/2/4/8
P(11)) computed exactly from the 4-state (state,bit) chain,
via random-restart coordinate descent in transformed space,
3. writes <outdir>/<name>.json with observed stats + fitted params
(and prints a one-line FIT line for fit_params.h).
Moment formulas: Y=(state,bit) is a 4-state chain with transition
P_Y[(s,x),(s',x')] = T[s,s'] * e_{s'}(x'), stationary piY(s,x) =
pi_s * e_s(x). BER = sum piY(.,1). P11(lag k) = piY' D1 P_Y^k D1 1.
Mean 1-run = BER / (BER - P11(1)); mean 0-run = (1-BER) / (BER - P11(1)).
Validation against simulation is done separately by gilsim.c, which
prints the same statistics for the fitted parameters.
"""
import sys, os, json, math
import numpy as np
def stats_of(bits):
n = len(bits)
ber = float(bits.mean())
j = {}
for k in (1, 2, 4, 8, 64, 256):
j[k] = float((bits[:-k] & bits[k:]).mean()) if n > k else 0.0
# run lengths: pad with 0 both ends; a run starts at padded index
# bnd+1 where d[bnd] != 0; runs[0] and runs[-1] touch the pads.
padded = np.concatenate(([0], bits, [0])).astype(np.int8)
d = np.diff(padded)
bnd = np.flatnonzero(d != 0)
starts_p = np.concatenate(([0], bnd + 1))
ends_p = np.concatenate((bnd + 1, [len(padded)]))
lens = ends_p - starts_p
vals = padded[starts_p]
# drop the two pad-touching runs (first and last); negligible count
if len(lens) > 2:
lens, vals = lens[1:-1], vals[1:-1]
r1 = lens[vals == 1]
r0 = lens[vals == 0]
def whist(W):
nw = n // W
w = bits[:nw * W].reshape(nw, W).sum(axis=1)
hist = [(float((w == i).mean())) for i in range(9)] + [float((w >= 9).mean())]
return hist, float((w > 2).mean()), float((w > 4).mean())
h32, p32gt2, p32gt4 = whist(32)
h64, p64gt2, p64gt4 = whist(64)
return {
"nbits": int(n), "ber": ber,
"lag1": j[1], "lag2": j[2], "lag4": j[4], "lag8": j[8],
"lag64": j[64], "lag256": j[256],
"meanrun1": float(r1.mean()) if len(r1) else 0.0,
"meanrun0": float(r0.mean()) if len(r0) else 0.0,
"maxrun1": int(r1.max()) if len(r1) else 0,
"nrun1": int(len(r1)), "nrun0": int(len(r0)),
"win32_hist": h32, "win32_pgt2": p32gt2, "win32_pgt4": p32gt4,
"win64_hist": h64, "win64_pgt2": p64gt2, "win64_pgt4": p64gt4,
}
def model_moments(a, b, p0, q1):
f = a / (a + b)
pi = np.array([1 - f, f])
T = np.array([[1 - a, a], [b, 1 - b]])
e1 = np.array([p0, q1]) # P(bit=1 | state)
# Y order: (G,0),(G,1),(B,0),(B,1)
PY = np.zeros((4, 4))
for s in range(2):
for sp in range(2):
PY[s * 2 + 0, sp * 2 + 0] = T[s, sp] * (1 - e1[sp])
PY[s * 2 + 0, sp * 2 + 1] = T[s, sp] * e1[sp]
PY[s * 2 + 1, sp * 2 + 0] = T[s, sp] * (1 - e1[sp])
PY[s * 2 + 1, sp * 2 + 1] = T[s, sp] * e1[sp]
piY = np.array([pi[0] * (1 - p0), pi[0] * p0, pi[1] * (1 - q1), pi[1] * q1])
D1 = np.diag([0.0, 1.0, 0.0, 1.0])
one = np.ones(4)
ber = float(piY @ np.array([0.0, 1.0, 0.0, 1.0]))
lags = {}
for k in (1, 2, 4, 8, 64, 256):
Ppow = np.linalg.matrix_power(PY, k)
lags[k] = float(piY @ D1 @ Ppow @ D1 @ one)
# mean run lengths from the renewal identity:
# P(a 1-run starts) = BER - P11(1); mean 1-run = BER / that.
pstart = max(ber - lags[1], 1e-12)
return ber, lags, ber / pstart, (1.0 - ber) / pstart
def loss_of(theta, obs):
# theta = (log a, log b, logit p0, logit q1)
a = math.exp(theta[0]); b = math.exp(theta[1])
p0 = 1.0 / (1.0 + math.exp(-theta[2]))
q1 = 1.0 / (1.0 + math.exp(-theta[3]))
if a >= 2 or b >= 2 or a <= 0 or b <= 0:
return 1e9
ber, lags, mr1, mr0 = model_moments(a, b, p0, q1)
# Loss moments: BER + lag-1/2/4 joints + mean run lengths.
# lag8 is REPORTED only, not fitted: fixed-length damage has a hard
# cutoff (runs of exactly 8 bits give observed lag8 ~= 0) while any
# geometric Gilbert model with mean burst 8 gives lag8 ~= 0.34*BER;
# including it lets a ~0 observed moment veto the right burst length.
# lag64/256 likewise (tail behaviour beyond the GRAND guess-list
# horizon of 12 bits). Mean-run terms use squared-count weights:
# a 1-sample mean (e.g. 2 runs in the whole file) carries ~no
# information about the mean and must not steer the fit.
w1 = min(1.0, obs["nrun1"] / 30.0) ** 2
w0 = min(1.0, obs["nrun0"] / 30.0) ** 2
terms = [
((ber - obs["ber"]) / max(obs["ber"], 1e-4)) ** 2,
((lags[1] - obs["lag1"]) / max(obs["lag1"], 0.02 * obs["ber"])) ** 2,
((lags[2] - obs["lag2"]) / max(obs["lag2"], 0.02 * obs["ber"])) ** 2,
((lags[4] - obs["lag4"]) / max(obs["lag4"], 0.02 * obs["ber"])) ** 2,
w1 * ((mr1 - obs["meanrun1"]) / max(obs["meanrun1"], 2.0)) ** 2,
w0 * ((mr0 - obs["meanrun0"]) / max(obs["meanrun0"], 50.0)) ** 2,
]
return sum(terms)
def fit(obs):
rng = np.random.default_rng(12345)
inits = [
(math.log(0.001), math.log(0.125), -7.0, 2.0),
(math.log(0.01), math.log(0.25), -6.0, 0.0),
(math.log(0.05), math.log(0.5), -5.0, 0.0),
(math.log(0.5), math.log(0.5), -4.0, -1.0),
(math.log(0.0002), math.log(0.05), -8.0, 3.0),
(math.log(0.002), math.log(0.5), -6.0, 2.0),
]
# data-driven init: b ~ 1/meanrun1, a ~ 1/meanrun0
mr1 = max(obs["meanrun1"], 1.5); mr0 = max(obs["meanrun0"], 2.0)
inits.append((math.log(1.0 / mr0), math.log(1.0 / mr1), -6.0, 1.0))
# iid init: p0 = q1 = BER (states indistinguishable)
ber0 = max(min(obs["ber"], 0.4), 1e-5)
lp = math.log(ber0 / (1.0 - ber0))
inits.append((math.log(0.5), math.log(0.5), lp, lp))
def descend(th):
th = list(th); L = loss_of(th, obs)
step = [0.7, 0.7, 1.0, 1.0]
for _ in range(400):
improved = False
for i in range(4):
for sgn in (1, -1):
cand = list(th); cand[i] += sgn * step[i]
cand[0] = min(max(cand[0], math.log(1e-8)), math.log(1.5))
cand[1] = min(max(cand[1], math.log(1e-8)), math.log(1.5))
cand[2] = min(max(cand[2], -13.0), 13.0)
cand[3] = min(max(cand[3], -13.0), 13.0)
Lc = loss_of(cand, obs)
if Lc < L - 1e-12:
th, L = cand, Lc; improved = True
if not improved:
step = [s * 0.5 for s in step]
if max(step) < 1e-4:
break
return th, L
best, bestL = None, 1e18
for init in inits:
th, L = descend(init)
# basin hopping: random log-space kicks, re-descend, keep best
for _ in range(12):
kick = [th[0] + rng.normal(0, 0.8), th[1] + rng.normal(0, 0.8),
th[2] + rng.normal(0, 1.5), th[3] + rng.normal(0, 1.5)]
kick[0] = min(max(kick[0], math.log(1e-8)), math.log(1.5))
kick[1] = min(max(kick[1], math.log(1e-8)), math.log(1.5))
kick[2] = min(max(kick[2], -13.0), 13.0)
kick[3] = min(max(kick[3], -13.0), 13.0)
th2, L2 = descend(kick)
if L2 < L:
th, L = th2, L2
if L < bestL:
bestL, best = L, list(th)
a = math.exp(best[0]); b = math.exp(best[1])
p0 = 1.0 / (1.0 + math.exp(-best[2]))
q1 = 1.0 / (1.0 + math.exp(-best[3]))
return {"a": a, "b": b, "p0": p0, "q1": q1, "f": a / (a + b),
"mean_burst": 1.0 / b, "mean_gap": 1.0 / a, "loss": bestL}
def main():
orig_p, corr_p, name = sys.argv[1], sys.argv[2], sys.argv[3]
outdir = sys.argv[4] if len(sys.argv) > 4 else "."
with open(orig_p, "rb") as f: orig = np.frombuffer(f.read(), dtype=np.uint8)
with open(corr_p, "rb") as f: corr = np.frombuffer(f.read(), dtype=np.uint8)
assert len(orig) == len(corr), "size mismatch"
xor = np.bitwise_xor(orig, corr)
bits = np.unpackbits(xor).astype(np.uint8)
obs = stats_of(bits)
if obs["ber"] == 0.0:
print(f"FIT name={name} NO ERRORS (ber=0)")
return 0
par = fit(obs)
ber_m, lags_m, mr1_m, mr0_m = model_moments(par["a"], par["b"], par["p0"], par["q1"])
res = {"name": name, "observed": obs, "fitted": par,
"model_moments": {"ber": ber_m, "lag1": lags_m[1], "lag2": lags_m[2],
"lag4": lags_m[4], "lag8": lags_m[8],
"lag64": lags_m[64], "lag256": lags_m[256]},
"model_meanrun1": mr1_m,
"model_meanrun0": mr0_m}
os.makedirs(outdir, exist_ok=True)
with open(os.path.join(outdir, name + ".json"), "w") as f:
json.dump(res, f, indent=1)
print(f"FIT name={name} nbits={obs['nbits']} ber={obs['ber']:.6g} "
f"lag1={obs['lag1']:.6g} lag2={obs['lag2']:.6g} lag4={obs['lag4']:.6g} lag8={obs['lag8']:.6g} "
f"lag64={obs['lag64']:.6g} lag256={obs['lag256']:.6g} "
f"meanrun1={obs['meanrun1']:.3f} meanrun0={obs['meanrun0']:.1f} maxrun1={obs['maxrun1']} "
f"win32_Pgt2={obs['win32_pgt2']:.4f} win32_Pgt4={obs['win32_pgt4']:.4f}")
print(f" PARAMS a={par['a']:.6g} b={par['b']:.6g} p0={par['p0']:.6g} q1={par['q1']:.6g} "
f"f={par['f']:.6g} mean_burst={par['mean_burst']:.2f}bits mean_gap={par['mean_gap']:.1f}bits loss={par['loss']:.4g}")
print(f" MODEL ber={ber_m:.6g} lag1={lags_m[1]:.6g} lag2={lags_m[2]:.6g} lag4={lags_m[4]:.6g} lag8={lags_m[8]:.6g} "
f"lag64={lags_m[64]:.6g} lag256={lags_m[256]:.6g} "
f"meanrun1={res['model_meanrun1']:.3f} meanrun0={res['model_meanrun0']:.1f}")
print(f"FITPARAMS {name} {par['a']:.10g} {par['b']:.10g} {par['p0']:.10g} {par['q1']:.10g}")
return 0
if __name__ == "__main__":
sys.exit(main())
-64
View File
@@ -1,64 +0,0 @@
== refits on mixed ==
FIT name=mixed-iid001 nbits=8521880 ber=0.00100553 lag1=8.21415e-07 lag2=1.05611e-06 lag4=1.05611e-06 lag8=9.38761e-07 lag64=1.64284e-06 lag256=1.29083e-06 meanrun1=1.001 meanrun0=994.1 maxrun1=2 win32_Pgt2=0.0000 win32_Pgt4=0.0000
PARAMS a=0.0585053 b=1.20175 p0=0.000817164 q1=0.00487893 f=0.0464235 mean_burst=0.83bits mean_gap=17.1bits loss=4.308e-06
MODEL ber=0.00100573 lag1=8.21412e-07 lag2=1.06095e-06 lag4=1.01483e-06 lag8=1.0115e-06 lag64=1.01148e-06 lag256=1.01148e-06 meanrun1=1.001 meanrun0=994.1
FITPARAMS mixed-iid001 0.0585052727 1.201746422 0.0008171640089 0.004878927115
FIT name=mixed-iid01 nbits=8521880 ber=0.0100156 lag1=9.62229e-05 lag2=0.000103968 lag4=0.000102677 lag8=0.00010033 lag64=0.000102091 lag256=0.000106083 meanrun1=1.010 meanrun0=99.8 maxrun1=3 win32_Pgt2=0.0040 win32_Pgt4=0.0000
PARAMS a=1.18006 b=0.673144 p0=0.0129101 q1=0.00836433 f=0.636768 mean_burst=1.49bits mean_gap=0.8bits loss=1.482e-06
MODEL ber=0.0100155 lag1=9.62322e-05 lag2=0.000103789 lag4=0.000102843 lag8=0.000101652 lag64=0.00010031 lag256=0.00010031 meanrun1=1.010 meanrun0=99.8
FITPARAMS mixed-iid01 1.180061061 0.6731436851 0.01291008027 0.008364325469
FIT name=mixed-run1ff nbits=8521880 ber=0.000763212 lag1=0.000667928 lag2=0.000572644 lag4=0.000382075 lag8=9.38761e-07 lag64=0 lag256=0 meanrun1=8.010 meanrun0=10484.6 maxrun1=16 win32_Pgt2=0.0030 win32_Pgt4=0.0030
PARAMS a=9.36908e-05 b=0.128379 p0=2.26032e-06 q1=0.999998 f=0.000729266 mean_burst=7.79bits mean_gap=10673.4bits loss=0.01776
MODEL ber=0.000731523 lag1=0.000635641 lag2=0.000554047 lag4=0.000420961 lag8=0.000243092 lag64=6.44912e-07 lag256=5.35126e-07 meanrun1=7.629 meanrun0=10421.9
FITPARAMS mixed-run1ff 9.369077412e-05 0.1283790246 2.260324298e-06 0.9999977397
FIT name=mixed-run4ff nbits=8521880 ber=0.000762273 lag1=0.000738452 lag2=0.000714631 lag4=0.000666989 lag8=0.000571705 lag64=0 lag256=1.87758e-06 meanrun1=32.000 meanrun0=41988.2 maxrun1=32 win32_Pgt2=0.0013 win32_Pgt4=0.0013
PARAMS a=2.15267e-05 b=0.0284308 p0=2.26032e-06 q1=0.999998 f=0.000756587 mean_burst=35.17bits mean_gap=46454.0bits loss=0.0001637
MODEL ber=0.000758844 lag1=0.000735073 lag2=0.000714175 lag4=0.000674146 lag8=0.000600697 lag64=0.000119763 lag256=1.04287e-06 meanrun1=31.924 meanrun0=42037.0
FITPARAMS mixed-run4ff 2.152665196e-05 0.02843079736 2.260324298e-06 0.9999977397
FIT name=mixed-run8ff nbits=8521880 ber=0.000766028 lag1=0.000754059 lag2=0.00074209 lag4=0.000718152 lag8=0.000670275 lag64=0 lag256=0 meanrun1=64.000 meanrun0=84168.7 maxrun1=64 win32_Pgt2=0.0010 win32_Pgt4=0.0010
PARAMS a=9.6457e-06 b=0.0126705 p0=2.26032e-06 q1=0.999998 f=0.000760692 mean_burst=78.92bits mean_gap=103673.1bits loss=8.43e-05
MODEL ber=0.000762949 lag1=0.000751051 lag2=0.000741535 lag4=0.000722863 lag8=0.000686919 lag64=0.000336457 lag256=2.95614e-05 meanrun1=64.121 meanrun0=83979.4
FITPARAMS mixed-run8ff 9.645702662e-06 0.01267051492 2.260324298e-06 0.9999977397
FIT name=mixed-run4rand nbits=8521880 ber=0.000371749 lag1=0.000175783 lag2=0.000169329 lag4=0.00015736 lag8=0.00013659 lag64=0 lag256=0 meanrun1=1.897 meanrun0=5068.7 maxrun1=9 win32_Pgt2=0.0013 win32_Pgt4=0.0011
PARAMS a=1.05584e-05 b=0.0358585 p0=0.000140958 q1=0.78668 f=0.000294359 mean_burst=27.89bits mean_gap=94711.2bits loss=1.382e-05
MODEL ber=0.000372483 lag1=0.000175659 lag2=0.000169363 lag4=0.000157441 lag8=0.000136057 lag64=1.77137e-05 lag256=1.54556e-07 meanrun1=1.892 meanrun0=5078.8
FITPARAMS mixed-run4rand 1.055840847e-05 0.03585853877 0.0001409578009 0.7866796477
FIT name=mixed-mix nbits=8521880 ber=0.00125207 lag1=0.000730825 lag2=0.000707004 lag4=0.000659362 lag8=0.000564195 lag64=7.04075e-07 lag256=7.04091e-07 meanrun1=2.402 meanrun0=1916.4 maxrun1=32 win32_Pgt2=0.0014 win32_Pgt4=0.0014
PARAMS a=6.7066e-05 b=0.0338925 p0=2.98933e-05 q1=0.619058 f=0.00197488 mean_burst=29.51bits mean_gap=14910.7bits loss=1.137e-06
MODEL ber=0.0012524 lag1=0.000731191 lag2=0.000706413 lag4=0.000659353 lag8=0.000574451 lag64=8.4325e-05 lag256=1.67737e-06 meanrun1=2.403 meanrun0=1916.2
FITPARAMS mixed-mix 6.706604581e-05 0.03389249481 2.989328833e-05 0.6190579161
FIT name=mixed-run512ff nbits=8521880 ber=0.00096129 lag1=0.000961056 lag2=0.000960821 lag4=0.000960352 lag8=0.000959414 lag64=0.000946277 lag256=0.000901237 meanrun1=4096.000 meanrun0=433776.0 maxrun1=4096 win32_Pgt2=0.0010 win32_Pgt4=0.0010
PARAMS a=9.04667e-08 b=9.40932e-05 p0=2.26032e-06 q1=0.999998 f=0.000960535 mean_burst=10627.76bits mean_gap=11053792.9bits loss=0.003604
MODEL ber=0.000962791 lag1=0.00096044 lag2=0.00096035 lag4=0.000960169 lag8=0.000959808 lag64=0.000954764 lag256=0.000937669 meanrun1=409.577 meanrun0=424996.0
FITPARAMS mixed-run512ff 9.046668457e-08 9.409317165e-05 2.260324298e-06 0.9999977397
== refits on big ==
FIT name=big-mix nbits=419449016 ber=0.00126099 lag1=0.000738187 lag2=0.000714368 lag4=0.000666827 lag8=0.000571662 lag64=1.65694e-06 lag256=1.62833e-06 meanrun1=2.412 meanrun0=1910.3 maxrun1=64 win32_Pgt2=0.0013 win32_Pgt4=0.0013
PARAMS a=2.68381e-05 b=0.0339261 p0=0.000484692 q1=0.983476 f=0.000790451 mean_burst=29.48bits mean_gap=37260.4bits loss=2.629e-06
MODEL ber=0.0012617 lag1=0.000738867 lag2=0.000713835 lag4=0.00066629 lag8=0.000580511 lag64=8.52526e-05 lag256=1.70209e-06 meanrun1=2.413 meanrun0=1910.2
FITPARAMS big-mix 2.683814296e-05 0.03392609764 0.0004846915355 0.9834763956
FIT name=big-run4ff nbits=419449016 ber=0.000762524 lag1=0.000738688 lag2=0.000714852 lag4=0.00066718 lag8=0.000571836 lag64=6.67542e-07 lag256=8.20124e-07 meanrun1=31.990 meanrun0=41918.1 maxrun1=64 win32_Pgt2=0.0013 win32_Pgt4=0.0013
PARAMS a=2.15566e-05 b=0.0284564 p0=2.26032e-06 q1=0.999998 f=0.000756958 mean_burst=35.14bits mean_gap=46389.4bits loss=0.0001666
MODEL ber=0.000759215 lag1=0.000735415 lag2=0.000714488 lag4=0.000674405 lag8=0.000600865 lag64=0.000119621 lag256=1.04051e-06 meanrun1=31.899 meanrun0=41984.1
FITPARAMS big-run4ff 2.15566409e-05 0.02845642285 2.260324298e-06 0.9999977397
== gilsim validation: simulate fitted params, compare vs real ==
VALIDATE big-mix: real win32_Pgt2=0.0013 win32_Pgt4=0.0013 win64_Pgt2=0.0021 win64_Pgt4=0.0021 meanrun1=2.41 meanrun0=1910
sim: GILSIM a=2.68381e-05 b=0.0339261 p0=0.000484692 q1=0.983476 nbits=20000000 ber=0.00128245 | lag1=0.00075961 lag2=0.000733909 lag4=0.000685259 lag8=0.000599008 lag64=9.58012e-05 lag256=4.30006e-06 meanrun1=2.453 meanrun0=1909.959 maxrun1=161 | win32 hist: 0.9830 0.0153 0.0002 0.0001 0.0001 0.0001 0.0001 0.0001 0.0001 0.0011 P(>2)=0.0015 P(>4)=0.0013 | win64 hist: 0.9670 0.0301 0.0005 0.0001 0.0001 0.0001 0.0001 0.0001 0.0001 0.0017 P(>2)=0.0023 P(>4)=0.0021
VALIDATE big-run4ff: real win32_Pgt2=0.0013 win32_Pgt4=0.0013 win64_Pgt2=0.0021 win64_Pgt4=0.0021 meanrun1=31.99 meanrun0=41918
sim: GILSIM a=2.15566e-05 b=0.0284564 p0=2.26032e-06 q1=0.999998 nbits=20000000 ber=0.0007562 | lag1=0.000732059 lag2=0.000710509 lag4=0.000669359 lag8=0.000595408 lag64=0.000115501 lag256=5.70007e-06 meanrun1=31.313 meanrun0=41291.066 maxrun1=204 | win32 hist: 0.9985 0.0001 0.0001 0.0001 0.0000 0.0001 0.0000 0.0001 0.0001 0.0010 P(>2)=0.0013 P(>4)=0.0012 | win64 hist: 0.9977 0.0002 0.0001 0.0001 0.0001 0.0001 0.0001 0.0001 0.0001 0.0015 P(>2)=0.0020 P(>4)=0.0018
VALIDATE mixed-iid001: real win32_Pgt2=0.0000 win32_Pgt4=0.0000 win64_Pgt2=0.0000 win64_Pgt4=0.0000 meanrun1=1.00 meanrun0=994
sim: GILSIM a=0.0585053 b=1.20175 p0=0.000817164 q1=0.00487893 nbits=20000000 ber=0.0010471 | lag1=8.0001e-07 lag2=1.30002e-06 lag4=1.15001e-06 lag8=9.00012e-07 lag64=1.25002e-06 lag256=1.55002e-06 meanrun1=1.001 meanrun0=954.702 maxrun1=2 | win32 hist: 0.9670 0.0324 0.0005 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 P(>2)=0.0000 P(>4)=0.0000 | win64 hist: 0.9351 0.0628 0.0020 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 P(>2)=0.0001 P(>4)=0.0000
VALIDATE mixed-iid01: real win32_Pgt2=0.0040 win32_Pgt4=0.0000 win64_Pgt2=0.0268 win64_Pgt4=0.0006 meanrun1=1.01 meanrun0=100
sim: GILSIM a=1.18006 b=0.673144 p0=0.0129101 q1=0.00836433 nbits=20000000 ber=0.010177 | lag1=0.000102601 lag2=0.000106901 lag4=0.000104451 lag8=0.000106851 lag64=0.000104701 lag256=0.000104301 meanrun1=1.010 meanrun0=98.251 maxrun1=3 | win32 hist: 0.7210 0.2368 0.0380 0.0038 0.0003 0.0000 0.0000 0.0000 0.0000 0.0000 P(>2)=0.0042 P(>4)=0.0000 | win64 hist: 0.5198 0.3416 0.1108 0.0236 0.0037 0.0005 0.0000 0.0000 0.0000 0.0000 P(>2)=0.0278 P(>4)=0.0005
VALIDATE mixed-mix: real win32_Pgt2=0.0014 win32_Pgt4=0.0014 win64_Pgt2=0.0021 win64_Pgt4=0.0021 meanrun1=2.40 meanrun0=1916
sim: GILSIM a=6.7066e-05 b=0.0338925 p0=2.98933e-05 q1=0.619058 nbits=20000000 ber=0.00121415 | lag1=0.000709259 lag2=0.000686959 lag4=0.000638358 lag8=0.000549257 lag64=8.1901e-05 lag256=3.20004e-06 meanrun1=2.405 meanrun0=1977.990 maxrun1=19 | win32 hist: 0.9952 0.0012 0.0003 0.0003 0.0003 0.0002 0.0002 0.0002 0.0002 0.0019 P(>2)=0.0033 P(>4)=0.0027 | win64 hist: 0.9923 0.0022 0.0004 0.0004 0.0004 0.0003 0.0003 0.0003 0.0002 0.0032 P(>2)=0.0051 P(>4)=0.0043
VALIDATE mixed-run1ff: real win32_Pgt2=0.0030 win32_Pgt4=0.0030 win64_Pgt2=0.0061 win64_Pgt4=0.0061 meanrun1=8.01 meanrun0=10485
sim: GILSIM a=9.36908e-05 b=0.128379 p0=2.26032e-06 q1=0.999998 nbits=20000000 ber=0.00071435 | lag1=0.000620158 lag2=0.000538857 lag4=0.000406555 lag8=0.000235053 lag64=1.50002e-06 lag256=6.00008e-07 meanrun1=7.583 meanrun0=10602.500 maxrun1=58 | win32 hist: 0.9964 0.0006 0.0005 0.0004 0.0004 0.0003 0.0002 0.0002 0.0002 0.0009 P(>2)=0.0026 P(>4)=0.0018 | win64 hist: 0.9934 0.0010 0.0008 0.0007 0.0006 0.0005 0.0004 0.0003 0.0003 0.0019 P(>2)=0.0048 P(>4)=0.0035
VALIDATE mixed-run4ff: real win32_Pgt2=0.0013 win32_Pgt4=0.0013 win64_Pgt2=0.0020 win64_Pgt4=0.0020 meanrun1=32.00 meanrun0=41988
sim: GILSIM a=2.15267e-05 b=0.0284308 p0=2.26032e-06 q1=0.999998 nbits=20000000 ber=0.0007562 | lag1=0.000732059 lag2=0.000710509 lag4=0.000669359 lag8=0.000595408 lag64=0.000115501 lag256=5.70007e-06 meanrun1=31.313 meanrun0=41291.066 maxrun1=204 | win32 hist: 0.9985 0.0001 0.0001 0.0001 0.0000 0.0001 0.0000 0.0001 0.0001 0.0010 P(>2)=0.0013 P(>4)=0.0012 | win64 hist: 0.9977 0.0002 0.0001 0.0001 0.0001 0.0001 0.0001 0.0001 0.0001 0.0015 P(>2)=0.0020 P(>4)=0.0018
VALIDATE mixed-run4rand: real win32_Pgt2=0.0013 win32_Pgt4=0.0011 win64_Pgt2=0.0020 win64_Pgt4=0.0019 meanrun1=1.90 meanrun0=5069
sim: GILSIM a=1.05584e-05 b=0.0358585 p0=0.000140958 q1=0.78668 nbits=20000000 ber=0.00038895 | lag1=0.000187002 lag2=0.000180702 lag4=0.000169902 lag8=0.000147052 lag64=2.47003e-05 lag256=0 meanrun1=1.926 meanrun0=4948.570 maxrun1=28 | win32 hist: 0.9949 0.0046 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0004 P(>2)=0.0005 P(>4)=0.0005 | win64 hist: 0.9900 0.0091 0.0001 0.0000 0.0000 0.0001 0.0000 0.0001 0.0000 0.0006 P(>2)=0.0008 P(>4)=0.0008
VALIDATE mixed-run512ff: real win32_Pgt2=0.0010 win32_Pgt4=0.0010 win64_Pgt2=0.0010 win64_Pgt4=0.0010 meanrun1=4096.00 meanrun0=433776
sim: GILSIM a=9.04667e-08 b=9.40932e-05 p0=2.26032e-06 q1=0.999998 nbits=20000000 ber=0.00087405 | lag1=0.000871911 lag2=0.000871861 lag4=0.000871761 lag8=0.000871561 lag64=0.000868761 lag256=0.000859161 meanrun1=406.535 meanrun0=454148.159 maxrun1=17439 | win32 hist: 0.9991 0.0001 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0009 P(>2)=0.0009 P(>4)=0.0009 | win64 hist: 0.9990 0.0001 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0009 P(>2)=0.0009 P(>4)=0.0009
VALIDATE mixed-run8ff: real win32_Pgt2=0.0010 win32_Pgt4=0.0010 win64_Pgt2=0.0014 win64_Pgt4=0.0014 meanrun1=64.00 meanrun0=84169
sim: GILSIM a=9.6457e-06 b=0.0126705 p0=2.26032e-06 q1=0.999998 nbits=20000000 ber=0.00077645 | lag1=0.00076496 lag2=0.00075561 lag4=0.000737259 lag8=0.000701759 lag64=0.000328304 lag256=2.45003e-05 meanrun1=67.517 meanrun0=86512.861 maxrun1=506 | win32 hist: 0.9989 0.0001 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0009 P(>2)=0.0010 P(>4)=0.0010 | win64 hist: 0.9985 0.0002 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0012 P(>2)=0.0013 P(>4)=0.0013
== DONE ==
-67
View File
@@ -1,67 +0,0 @@
{
"name": "big-mix",
"observed": {
"nbits": 419449016,
"ber": 0.001260989964987783,
"lag1": 0.0007381874528898345,
"lag2": 0.0007143681114959064,
"lag4": 0.0006668271756472751,
"lag8": 0.0005716618597891641,
"lag64": 1.6569358361396026e-06,
"lag256": 1.628327617418633e-06,
"meanrun1": 2.4119814491378957,
"meanrun0": 1910.344806829375,
"maxrun1": 64,
"nrun1": 219289,
"nrun0": 219288,
"win32_hist": [
0.9828395057866774,
0.015707921882429986,
0.00012206490175568238,
6.866150723757133e-07,
0.0,
0.0,
0.0,
1.3732301447514266e-06,
0.0003713824635916636,
0.0009570651203281471
],
"win32_pgt2": 0.0013305074291369379,
"win32_pgt4": 0.001329820814064562,
"win64_hist": [
0.9665282755737432,
0.030880286364281365,
0.0004958887012140881,
3.967109609712705e-06,
1.5258113883510403e-07,
0.0,
0.0,
9.154868330106242e-07,
0.00036466892181589864,
0.0017258452613638617
],
"win64_pgt2": 0.0020955493607613188,
"win64_pgt4": 0.002091429670012771
},
"fitted": {
"a": 2.6838142963847655e-05,
"b": 0.033926097644145316,
"p0": 0.0004846915354771534,
"q1": 0.9834763956343967,
"f": 0.0007904513215625152,
"mean_burst": 29.475833338956733,
"mean_gap": 37260.40215774433,
"loss": 2.629422505822106e-06
},
"model_moments": {
"ber": 0.0012616986270671334,
"lag1": 0.0007388672026052199,
"lag2": 0.0007138345410356919,
"lag4": 0.0006662901572506559,
"lag8": 0.0005805107339201686,
"lag64": 8.525261409488412e-05,
"lag256": 1.7020861625171235e-06
},
"model_meanrun1": 2.413203506972913,
"model_meanrun0": 1910.2491829002286
}
-67
View File
@@ -1,67 +0,0 @@
{
"name": "big-run4ff",
"observed": {
"nbits": 419449016,
"ber": 0.0007625241395249811,
"lag1": 0.0007386881096859888,
"lag2": 0.0007148520797333427,
"lag4": 0.0006671800194870884,
"lag8": 0.0005718358976307318,
"lag64": 6.675424951353794e-07,
"lag256": 8.201240122869835e-07,
"meanrun1": 31.99039807961592,
"meanrun0": 41918.10343102931,
"maxrun1": 64,
"nrun1": 9998,
"nrun0": 9997,
"win32_hist": [
0.9986652965898652,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0003844281499668022,
0.0009502752601679873
],
"win32_pgt2": 0.0013347034101347894,
"win32_pgt4": 0.0013347034101347894,
"win64_hist": [
0.9979042980580999,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.00038389414530912174,
0.0017118077965910322
],
"win64_pgt2": 0.002095701941900154,
"win64_pgt4": 0.002095701941900154
},
"fitted": {
"a": 2.155664090060564e-05,
"b": 0.02845642285470762,
"p0": 2.2603242979035746e-06,
"q1": 0.999997739675702,
"f": 0.0007569582281611668,
"mean_burst": 35.141451373062075,
"mean_gap": 46389.41682105512,
"loss": 0.0001666206188536461
},
"model_moments": {
"ber": 0.0007592151305169191,
"lag1": 0.0007354146826562025,
"lag2": 0.0007144879733269741,
"lag4": 0.0006744054344028338,
"lag8": 0.000600865304168514,
"lag64": 0.00011962071728338087,
"lag256": 1.0405136355379172e-06
},
"model_meanrun1": 31.89919513111459,
"model_meanrun0": 41984.11688373142
}
-67
View File
@@ -1,67 +0,0 @@
{
"name": "mixed-iid001",
"observed": {
"nbits": 8521880,
"ber": 0.001005529296352448,
"lag1": 8.214150893247839e-07,
"lag2": 1.0561052387748334e-06,
"lag4": 1.056105486632286e-06,
"lag8": 9.387608731978138e-07,
"lag64": 1.6428423237488348e-06,
"lag256": 1.290833765958226e-06,
"meanrun1": 1.0008175659892549,
"meanrun0": 994.1158743137483,
"maxrun1": 2,
"nrun1": 8562,
"nrun0": 8561,
"win32_hist": [
0.9682810880634454,
0.031264550820854047,
0.00045060606515763703,
3.7550505429803087e-06,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0
],
"win32_pgt2": 3.7550505429803087e-06,
"win32_pgt4": 0.0,
"win64_hist": [
0.9375535094702375,
0.06056896525827238,
0.0018474848671463117,
3.004040434384247e-05,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0
],
"win64_pgt2": 3.004040434384247e-05,
"win64_pgt4": 0.0
},
"fitted": {
"a": 0.05850527270021062,
"b": 1.2017464218341767,
"p0": 0.0008171640088546061,
"q1": 0.004878927114991506,
"f": 0.04642348266932978,
"mean_burst": 0.8321223028679716,
"mean_gap": 17.092476521289676,
"loss": 4.307714541787823e-06
},
"model_moments": {
"ber": 0.0010057251980192755,
"lag1": 8.214121070341747e-07,
"lag2": 1.0609494911727455e-06,
"lag4": 1.014833574319034e-06,
"lag8": 1.0114985438285112e-06,
"lag64": 1.0114831739309108e-06,
"lag256": 1.0114831739309106e-06
},
"model_meanrun1": 1.000817403734118,
"model_meanrun0": 994.1193264538296
}
-67
View File
@@ -1,67 +0,0 @@
{
"name": "mixed-iid01",
"observed": {
"nbits": 8521880,
"ber": 0.010015630353865579,
"lag1": 9.62229104637604e-05,
"lag2": 0.00010396769350605582,
"lag4": 0.00010267692231147226,
"lag8": 0.00010033006832301635,
"lag64": 0.0001020909158329633,
"lag256": 0.00010608306585693055,
"meanrun1": 1.0097004684616477,
"meanrun0": 99.80182418284416,
"maxrun1": 3,
"nrun1": 84532,
"nrun0": 84531,
"win32_hist": [
0.7246233684305391,
0.23460053772323775,
0.0367656998663202,
0.0037024798353785843,
0.00028538384126650346,
1.8775252714901542e-05,
3.7550505429803087e-06,
0.0,
0.0,
0.0
],
"win32_pgt2": 0.00401039397990297,
"win32_pgt4": 2.2530303257881852e-05,
"win64_hist": [
0.5252264295477417,
0.3399672559592652,
0.1080102738182856,
0.022763116391546632,
0.0034696667017138053,
0.000548237379275125,
7.5101010859606174e-06,
7.5101010859606174e-06,
0.0,
0.0
],
"win64_pgt2": 0.02679604067470748,
"win64_pgt4": 0.0005632575814470463
},
"fitted": {
"a": 1.1800610613534341,
"b": 0.6731436850878685,
"p0": 0.012910080270658987,
"q1": 0.00836432546949663,
"f": 0.6367677741056395,
"mean_burst": 1.485566933409567,
"mean_gap": 0.8474137760745035,
"loss": 1.4818566642231621e-06
},
"model_moments": {
"ber": 0.010015490104292809,
"lag1": 9.623219694241193e-05,
"lag2": 0.00010378927881247619,
"lag4": 0.00010284278146015555,
"lag8": 0.00010165219977749386,
"lag64": 0.00010031022686506647,
"lag256": 0.00010031004202918414
},
"model_meanrun1": 1.0097015520557342,
"model_meanrun0": 99.80429172651172
}
-67
View File
@@ -1,67 +0,0 @@
{
"name": "mixed-mix",
"observed": {
"nbits": 8521880,
"ber": 0.0012520711392321883,
"lag1": 0.0007308247394735363,
"lag2": 0.0007070037848464858,
"lag4": 0.0006593618588207573,
"lag8": 0.0005641952847918861,
"lag64": 7.040752816066435e-07,
"lag256": 7.040911450681232e-07,
"meanrun1": 2.4020711391265195,
"meanrun0": 1916.3764917811304,
"maxrun1": 32,
"nrun1": 4442,
"nrun0": 4441,
"win32_hist": [
0.9828581942712948,
0.015673580966399807,
0.00011640656683238956,
0.0,
0.0,
0.0,
0.0,
0.0,
0.00037550505429803085,
0.0009763131411748802
],
"win32_pgt2": 0.0013518181954729112,
"win32_pgt4": 0.0013518181954729112,
"win64_hist": [
0.9665875602685612,
0.030768884149180647,
0.0005106868738453219,
0.0,
0.0,
0.0,
0.0,
0.0,
0.00037550505429803085,
0.0017573636541147843
],
"win64_pgt2": 0.0021328687084128154,
"win64_pgt4": 0.0021328687084128154
},
"fitted": {
"a": 6.706604580792872e-05,
"b": 0.03389249481168578,
"p0": 2.989328832733482e-05,
"q1": 0.6190579161016859,
"f": 0.001974879654344221,
"mean_burst": 29.50505725695974,
"mean_gap": 14910.67481246639,
"loss": 1.1369599101782e-06
},
"model_moments": {
"ber": 0.001252399136050367,
"lag1": 0.0007311906942014816,
"lag2": 0.0007064130450166362,
"lag4": 0.0006593534860352715,
"lag8": 0.0005744505087356371,
"lag64": 8.432504925485657e-05,
"lag256": 1.6773718444255355e-06
},
"model_meanrun1": 2.4028757700234578,
"model_meanrun0": 1916.2153193856327
}
-67
View File
@@ -1,67 +0,0 @@
{
"name": "mixed-run1ff",
"observed": {
"nbits": 8521880,
"ber": 0.0007632118734363779,
"lag1": 0.00066792781263381,
"lag2": 0.0005726437294690208,
"lag4": 0.00038207549605274706,
"lag8": 9.387608731978138e-07,
"lag64": 0.0,
"lag256": 0.0,
"meanrun1": 8.009852216748769,
"meanrun0": 10484.577065351417,
"maxrun1": 16,
"nrun1": 812,
"nrun0": 811,
"win32_hist": [
0.996954654009643,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0030378358892710696,
7.5101010859606174e-06
],
"win32_pgt2": 0.0030453459903570304,
"win32_pgt4": 0.0030453459903570304,
"win64_hist": [
0.9939168181203719,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.006060651576370218,
2.2530303257881852e-05
],
"win64_pgt2": 0.0060831818796280995,
"win64_pgt4": 0.0060831818796280995
},
"fitted": {
"a": 9.369077412437533e-05,
"b": 0.12837902456582617,
"p0": 2.2603242979035746e-06,
"q1": 0.999997739675702,
"f": 0.0007292659291621646,
"mean_burst": 7.789434476402735,
"mean_gap": 10673.40951492717,
"loss": 0.01776471965757438
},
"model_moments": {
"ber": 0.0007315229567050695,
"lag1": 0.0006356410353477708,
"lag2": 0.0005540472546243688,
"lag4": 0.00042096069205268795,
"lag8": 0.0002430917109731464,
"lag64": 6.449121990305979e-07,
"lag256": 5.351258361868904e-07
},
"model_meanrun1": 7.629414871434304,
"model_meanrun0": 10421.865382938828
}
-67
View File
@@ -1,67 +0,0 @@
{
"name": "mixed-run4ff",
"observed": {
"nbits": 8521880,
"ber": 0.0007622731134444513,
"lag1": 0.0007384521653029807,
"lag2": 0.0007146312115709707,
"lag4": 0.0006669892873353238,
"lag8": 0.0005717053717774687,
"lag64": 0.0,
"lag256": 1.8775763868483284e-06,
"meanrun1": 32.0,
"meanrun0": 41988.19801980198,
"maxrun1": 32,
"nrun1": 203,
"nrun0": 202,
"win32_hist": [
0.9986819772594139,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.00034170959941120805,
0.0009763131411748802
],
"win32_pgt2": 0.0013180227405860882,
"win32_pgt4": 0.0013180227405860882,
"win64_hist": [
0.9979722727067907,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0002928939423524641,
0.0017348333508569026
],
"win64_pgt2": 0.0020277272932093665,
"win64_pgt4": 0.0020277272932093665
},
"fitted": {
"a": 2.152665195658477e-05,
"b": 0.028430797362069684,
"p0": 2.2603242979035746e-06,
"q1": 0.999997739675702,
"f": 0.0007565867711183341,
"mean_burst": 35.17312537052259,
"mean_gap": 46454.04227358778,
"loss": 0.00016373123392498306
},
"model_moments": {
"ber": 0.0007588436751533132,
"lag1": 0.0007350731852691523,
"lag2": 0.0007141750289200491,
"lag4": 0.0006741456017854607,
"lag8": 0.0006006971541993568,
"lag64": 0.0001197630430364126,
"lag256": 1.042868720000177e-06
},
"model_meanrun1": 31.923770980376677,
"model_meanrun0": 42037.045142711824
}
-67
View File
@@ -1,67 +0,0 @@
{
"name": "mixed-run4rand",
"observed": {
"nbits": 8521880,
"ber": 0.000371748956802959,
"lag1": 0.00017578282911550374,
"lag2": 0.00016932887328356496,
"lag4": 0.00015735971750821062,
"lag8": 0.0001365897070502819,
"lag64": 0.0,
"lag256": 0.0,
"meanrun1": 1.897005988023952,
"meanrun0": 5068.696824445776,
"maxrun1": 9,
"nrun1": 1670,
"nrun0": 1669,
"win32_hist": [
0.998666957057242,
1.8775252714901542e-05,
3.379545488682277e-05,
8.261111194556679e-05,
0.00012391666791835017,
0.00014269192063325173,
9.387626357450771e-05,
5.632575814470463e-05,
9.763131411748802e-05,
0.0006834191988224161
],
"win32_pgt2": 0.0012804722351562852,
"win32_pgt4": 0.0010739444552923683,
"win64_hist": [
0.9979572525046188,
7.5101010859606174e-06,
2.2530303257881852e-05,
5.257070760172432e-05,
8.261111194556679e-05,
0.00014269192063325173,
0.00010514141520344864,
6.759090977364555e-05,
9.763131411748802e-05,
0.0014644697117623202
],
"win64_pgt2": 0.0020127070910374452,
"win64_pgt4": 0.0018775252714901543
},
"fitted": {
"a": 1.055840847396487e-05,
"b": 0.03585853877080668,
"p0": 0.00014095780086130884,
"q1": 0.7866796477104622,
"f": 0.00029435947108431295,
"mean_burst": 27.887360564009505,
"mean_gap": 94711.2438835663,
"loss": 1.3818290724243916e-05
},
"model_moments": {
"ber": 0.0003724829136104474,
"lag1": 0.0001756586345660457,
"lag2": 0.00016936289453725175,
"lag4": 0.00015744078196279973,
"lag8": 0.00013605717806184015,
"lag64": 1.7713711785283903e-05,
"lag256": 1.5455626296293095e-07
},
"model_meanrun1": 1.8924642600947559,
"model_meanrun0": 5078.7815504249
}
-67
View File
@@ -1,67 +0,0 @@
{
"name": "mixed-run512ff",
"observed": {
"nbits": 8521880,
"ber": 0.000961290231732904,
"lag1": 0.0009610556545099971,
"lag2": 0.0009608210772320373,
"lag4": 0.0009603519225109588,
"lag8": 0.0009594136124081657,
"lag64": 0.0009462771784793288,
"lag256": 0.0009012366656871977,
"meanrun1": 4096.0,
"meanrun0": 433776.0,
"maxrun1": 4096,
"nrun1": 2,
"nrun0": 1,
"win32_hist": [
0.9990349520104541,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0009650479895459392
],
"win32_pgt2": 0.0009650479895459392,
"win32_pgt4": 0.0009650479895459392,
"win64_hist": [
0.999031196959911,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0009688030400889196
],
"win64_pgt2": 0.0009688030400889196,
"win64_pgt4": 0.0009688030400889196
},
"fitted": {
"a": 9.046668457161914e-08,
"b": 9.409317165223474e-05,
"p0": 2.2603242979035746e-06,
"q1": 0.999997739675702,
"f": 0.0009605350373926395,
"mean_burst": 10627.763762666722,
"mean_gap": 11053792.948589122,
"loss": 0.0036036248483439655
},
"model_moments": {
"ber": 0.0009627910194491751,
"lag1": 0.0009604403212893348,
"lag2": 0.0009603499508305524,
"lag4": 0.0009601692354464418,
"lag8": 0.0009598079067895944,
"lag64": 0.0009547635733977261,
"lag256": 0.0009376693201438884
},
"model_meanrun1": 409.576625318235,
"model_meanrun0": 424995.9548394009
}
-67
View File
@@ -1,67 +0,0 @@
{
"name": "mixed-run8ff",
"observed": {
"nbits": 8521880,
"ber": 0.0007660281534121578,
"lag1": 0.0007540590520001516,
"lag2": 0.0007420899477791163,
"lag4": 0.0007181517309099546,
"lag8": 0.0006702752634632391,
"lag64": 0.0,
"lag256": 0.0,
"meanrun1": 64.0,
"meanrun0": 84168.71287128713,
"maxrun1": 64,
"nrun1": 102,
"nrun0": 101,
"win32_hist": [
0.9989711161512234,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0001839974766060351,
0.0008448863721705694
],
"win32_pgt2": 0.0010288838487766045,
"win32_pgt4": 0.0010288838487766045,
"win64_hist": [
0.9985805908947535,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.00018024242606305482,
0.0012391666791835019
],
"win64_pgt2": 0.0014194091052465566,
"win64_pgt4": 0.0014194091052465566
},
"fitted": {
"a": 9.645702661667365e-06,
"b": 0.012670514922182442,
"p0": 2.2603242979035746e-06,
"q1": 0.999997739675702,
"f": 0.0007606924665266966,
"mean_burst": 78.92339073365412,
"mean_gap": 103673.11071842008,
"loss": 8.42976490421747e-05
},
"model_moments": {
"ber": 0.0007629493520012695,
"lag1": 0.0007510507547072412,
"lag2": 0.0007415346915165715,
"lag4": 0.0007228630307103117,
"lag8": 0.0006869194037815606,
"lag64": 0.0003364573298610019,
"lag256": 2.9561389274006815e-05
},
"model_meanrun1": 64.1209491461808,
"model_meanrun0": 83979.39908004981
}
-88
View File
@@ -1,88 +0,0 @@
/* gilsim.c - simulate a Gilbert 2-state burst channel and print the
* same error-pattern statistics fit.py computes on real damage, so a
* fitted model can be validated by direct comparison.
* Usage: gilsim <a> <b> <p0> <q1> <nbits> <seed>
* a = P(G->B), b = P(B->G), p0 = flip prob in G, q1 = flip prob in B.
* Prints: BER, lag-1/2/4/8 P(11), mean 1-run, mean 0-run, window
* weight histogram for w=32 and w=64 (weights 0..8, 9+), P(w>2),
* P(w>4), max 1-run. Same definitions as fit.py.
*/
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
static uint64_t rng_s;
static void rng_seed(uint64_t s){ rng_s = s ? s : 0x9E3779B97F4A7C15ULL; }
static uint64_t rng_next(void){
uint64_t x = rng_s; x ^= x >> 12; x ^= x << 25; x ^= x >> 27;
rng_s = x; return x * 0x2545F4914F6CDD1DULL;
}
static double rng_uniform(void){ return (rng_next() >> 11) * (1.0 / 9007199254740992.0); }
int main(int argc, char **argv){
if(argc < 7){ fprintf(stderr, "usage: gilsim <a> <b> <p0> <q1> <nbits> <seed>\n"); return 1; }
double a = atof(argv[1]), b = atof(argv[2]), p0 = atof(argv[3]), q1 = atof(argv[4]);
long nbits = atol(argv[5]);
rng_seed(strtoull(argv[6], NULL, 0));
double f = a / (a + b);
int state = (rng_uniform() < f) ? 1 : 0;
uint8_t *x = malloc(nbits ? nbits : 1);
long ones = 0;
for(long i = 0; i < nbits; i++){
double fp = state ? q1 : p0;
int bit = (rng_uniform() < fp) ? 1 : 0;
x[i] = (uint8_t)bit; ones += bit;
double u = rng_uniform();
state = state ? ((u < b) ? 0 : 1) : ((u < a) ? 1 : 0);
}
/* lag-k joint P(11) */
double j1 = 0, j2 = 0, j4 = 0, j8 = 0, j64 = 0, j256 = 0;
for(long i = 0; i + 256 < nbits; i++){
if(x[i]){
if(x[i+1]) j1++;
if(x[i+2]) j2++;
if(x[i+4]) j4++;
if(x[i+8]) j8++;
if(x[i+64]) j64++;
if(x[i+256]) j256++;
}
}
/* run lengths */
long nruns1 = 0, sumrun1 = 0, maxrun1 = 0, nruns0 = 0, sumrun0 = 0, cur = 1;
for(long i = 1; i < nbits; i++){
if(x[i] == x[i-1]) cur++;
else {
if(x[i-1]){ nruns1++; sumrun1 += cur; if(cur > maxrun1) maxrun1 = cur; }
else { nruns0++; sumrun0 += cur; }
cur = 1;
}
}
if(x[nbits-1]){ nruns1++; sumrun1 += cur; if(cur > maxrun1) maxrun1 = cur; }
else { nruns0++; sumrun0 += cur; }
printf("GILSIM a=%.6g b=%.6g p0=%.6g q1=%.6g nbits=%ld ber=%.6g\n",
a, b, p0, q1, nbits, (double)ones / (double)nbits);
printf(" lag1=%.6g lag2=%.6g lag4=%.6g lag8=%.6g lag64=%.6g lag256=%.6g meanrun1=%.3f meanrun0=%.3f maxrun1=%ld\n",
j1 / (double)(nbits - 256), j2 / (double)(nbits - 256),
j4 / (double)(nbits - 256), j8 / (double)(nbits - 256),
j64 / (double)(nbits - 256), j256 / (double)(nbits - 256),
nruns1 ? (double)sumrun1 / nruns1 : 0.0,
nruns0 ? (double)sumrun0 / nruns0 : 0.0, maxrun1);
for(int W = 32; W <= 64; W *= 2){
long nw = nbits / W;
long hist[10] = {0};
for(long w = 0; w < nw; w++){
int s = 0;
for(int i = 0; i < W; i++) s += x[w * W + i];
hist[s <= 8 ? s : 9]++;
}
long gt2 = 0, gt4 = 0;
for(int i = 3; i < 10; i++) gt2 += hist[i];
for(int i = 5; i < 10; i++) gt4 += hist[i];
printf(" win%d hist:", W);
for(int i = 0; i < 10; i++) printf(" %.4f", (double)hist[i] / (double)nw);
printf(" P(>2)=%.4f P(>4)=%.4f\n", (double)gt2 / nw, (double)gt4 / nw);
}
return 0;
}
-7
View File
@@ -1,7 +0,0 @@
# libRaptorQ encode K=101 T=1024 R=10: 0.012 s (8.35 MB/s)
# overhead-curve K=101 T=1024 sent=111 trials=500
recv K+0: 495/500 = 0.9900 mean-decode 0.0121 s (8.54 MB/s)
recv K+1: 500/500 = 1.0000 mean-decode 0.0123 s (8.41 MB/s)
recv K+2: 500/500 = 1.0000 mean-decode 0.0138 s (7.50 MB/s)
recv K+3: 500/500 = 1.0000 mean-decode 0.0155 s (6.69 MB/s)
recv K+5: 500/500 = 1.0000 mean-decode 0.0174 s (5.95 MB/s)
-451
View File
@@ -1,451 +0,0 @@
#!/usr/bin/env python3
"""mk_p3.py - build p3.c (Milestone 2.1: GRAND-MO model selection) from p2.c.
Copies randfec/p2.c -> randfec/p3.c and applies a list of asserted
string replacements (each must match exactly once, else abort).
Also generates randfec/fit_params.h from randfec/m2/fits2/*.json
(big-file fits preferred: big-run4ff -> FIT_RUN_*, big-mix -> FIT_MIX_*).
Run on hot_house from /root/lzply.
Usage: python3 randfec/m2/mk_p3.py
"""
import json, glob, os, sys
ROOT = "/root/lzply/randfec"
SRC = os.path.join(ROOT, "p2.c")
DST = os.path.join(ROOT, "p3.c")
def gen_fit_params():
def load(name):
p = f"/root/lzply/randfec/m2/fits2/{name}.json"
if not os.path.exists(p):
p = f"/root/lzply/randfec/m2/fits/{name}.json"
return json.load(open(p))
run = load("big-run4ff") if os.path.exists("/root/lzply/randfec/m2/fits2/big-run4ff.json") else load("mixed-run4ff")
mix = load("big-mix") if os.path.exists("/root/lzply/randfec/m2/fits2/big-mix.json") else load("mixed-mix")
hdr = ["/* fit_params.h - GENERATED by randfec/m2/mk_p3.py from fits2 json files.",
" * Gilbert models fitted to REAL lzply damage (see randfec/m2/fit.py).",
f" * FIT_RUN: {run['name']} (nbits={run['observed']['nbits']}, ber={run['observed']['ber']:.6g}).",
f" * FIT_MIX: {mix['name']} (nbits={mix['observed']['nbits']}, ber={mix['observed']['ber']:.6g}).",
" * a=P(G->B), b=P(B->G), p0=flip prob in G, q1=flip prob in B.",
" * Do not hand-edit: regenerate with mk_p3.py after refitting. */",
"#ifndef FIT_PARAMS_H", "#define FIT_PARAMS_H"]
for tag, d in (("FIT_RUN", run), ("FIT_MIX", mix)):
f = d["fitted"]
for k in ("a", "b", "p0", "q1", "f", "mean_burst", "mean_gap"):
hdr.append(f"#define {tag}_{k.upper()} {f[k]!r}")
hdr.append("#endif /* FIT_PARAMS_H */")
hdr.append("")
open(os.path.join(ROOT, "fit_params.h"), "w").write("\n".join(hdr))
print("wrote fit_params.h from", run["name"], "and", mix["name"])
REPLACEMENTS = []
def R(old, new):
REPLACEMENTS.append((old, new))
# 1. include fit_params.h
R('#include "../bch.h"',
'#include "../bch.h"\n#include "fit_params.h"')
# 2. mixture-LL helpers + grand_first, inserted before the guess-scan comment
R("""/* Decode by guess-list scan: success iff first guess with syndrome
* syn(e) equals e. Returns scan index, or -1 if not found (exhausted). */""",
"""/* --- Milestone 2.1: mixture ordering + two-pass arbitration --- */
/* iid log-likelihood of a pattern (weight w, n bits, flip prob p). */
static double pattern_ll_iid(uint64_t pat, int n, double p){
int w = popcnt64(pat);
return w * log(p) + (n - w) * log(1.0 - p);
}
/* Mixture LL: log( wb*exp(LLb) + (1-wb)*exp(LLi) ), logsumexp form.
* wb = prior weight on the burst component, p_iid = iid flip prob. */
static double pattern_ll_mix(uint64_t pat, int n, const gmodel_t *m, double p_iid, double wb){
double lb = pattern_ll(pat, n, m);
double li = pattern_ll_iid(pat, n, p_iid);
double a = log(wb) + lb, b = log(1.0 - wb) + li;
double mx = fmax(a, b);
return mx + log(exp(a - mx) + exp(b - mx));
}
/* GRAND-MO list, scored by mixture LL instead of pure burst LL.
* Same guess universe as GRAND-MO (bursts <= Lmax + weight <= W). */
static void glist_grandmix(glist_t *L, const code_t *c, int W, int Lmax,
const gmodel_t *m, double p_iid, double wb, size_t budget){
glist_t tmp; memset(&tmp, 0, sizeof tmp);
glist_bursts(&tmp, c, Lmax);
glist_t w; memset(&w, 0, sizeof w);
glist_grand(&w, c, W);
for(size_t i = 0; i < w.n; i++) glist_add(&tmp, c, w.pat[i]);
free(w.pat); free(w.syn);
scored_t *sc = malloc(tmp.n * sizeof *sc);
for(size_t i = 0; i < tmp.n; i++){
sc[i].pat = tmp.pat[i]; sc[i].syn = tmp.syn[i];
sc[i].ll = pattern_ll_mix(tmp.pat[i], c->n, m, p_iid, wb);
}
free(tmp.pat); free(tmp.syn);
qsort(sc, tmp.n, sizeof *sc, cmp_scored);
memset(L, 0, sizeof *L);
for(size_t i = 0; i < tmp.n && L->n < budget; i++){
if(L->n > 0 && sc[i].pat == L->pat[L->n - 1]) continue; /* dedupe */
if(L->n == L->cap){
L->cap = L->cap ? L->cap * 2 : 1024;
L->pat = realloc(L->pat, L->cap * sizeof *L->pat);
L->syn = realloc(L->syn, L->cap * sizeof *L->syn);
}
L->pat[L->n] = sc[i].pat; L->syn[L->n] = sc[i].syn; L->n++;
}
free(sc);
}
/* First guess whose syndrome matches syn(e): returns 1 and *pat if the
* first match is the true error, 0 and *pat if it is a different pattern
* (miscorrection), -1 if no guess matches (exhausted). */
static int grand_first(const glist_t *L, const code_t *c, uint64_t e, uint64_t *pat){
uint64_t s = code_syn(c, e);
for(size_t i = 0; i < L->n; i++)
if(L->syn[i] == s){ *pat = L->pat[i]; return (L->pat[i] == e) ? 1 : 0; }
return -1;
}
/* Decode by guess-list scan: success iff first guess with syndrome
* syn(e) equals e. Returns scan index, or -1 if not found (exhausted). */""")
# 3. Gilbert constructors + fitted-shape rescaling, before the models section
R("""/* ---------------- models ---------------- */
typedef struct { char name[32]; chan_t ch; } model_t;""",
"""/* Gilbert channel from explicit (a, b, p0, q1). */
static chan_t chan_gilbert(double a, double b, double p0, double q1){
chan_t ch; ch.kind = 1;
ch.gm.a = a; ch.gm.b = b; ch.gm.p0 = p0; ch.gm.q1 = q1;
ch.gm.f = a / (a + b);
ch.p = (1.0 - ch.gm.f) * p0 + ch.gm.f * q1;
return ch;
}
/* Fitted burst shape (b, p0, q1) rescaled to a target BER by moving f
* (via a). Keeps mean burst length 1/b and in-burst density q1; only
* the burst frequency changes. Used for the ordering model of the
* 'fitscaled' schemes and the mixture burst component. */
static chan_t chan_fit_scaled(double ber, double b, double p0, double q1){
double f = (ber - p0) / (q1 - p0);
chan_t ch; ch.kind = 1;
ch.gm.b = b; ch.gm.q1 = q1; ch.gm.p0 = p0; ch.gm.f = f;
ch.gm.a = f * b / (1.0 - f); ch.p = ber;
return ch;
}
/* ---------------- models ---------------- */
typedef struct { char name[32]; chan_t ch; } model_t;""")
# 4. fitted models in all_models (insert before "return i;")
R(""" snprintf(m[i].name, sizeof m[i].name, "mix-L16-BER0.01"); m[i].ch = chan_burst(16, 0.01, 0.002, 0.95); i++;
return i;""",
""" snprintf(m[i].name, sizeof m[i].name, "mix-L16-BER0.01"); m[i].ch = chan_burst(16, 0.01, 0.002, 0.95); i++;
snprintf(m[i].name, sizeof m[i].name, "burst-FITRUN-BER0.01"); m[i].ch = chan_fit_scaled(0.01, FIT_RUN_B, FIT_RUN_P0, FIT_RUN_Q1); i++;
snprintf(m[i].name, sizeof m[i].name, "burst-FITRUN-BER0.03"); m[i].ch = chan_fit_scaled(0.03, FIT_RUN_B, FIT_RUN_P0, FIT_RUN_Q1); i++;
snprintf(m[i].name, sizeof m[i].name, "burst-FITMIX-BER0.01"); m[i].ch = chan_fit_scaled(0.01, FIT_MIX_B, FIT_MIX_P0, FIT_MIX_Q1); i++;
snprintf(m[i].name, sizeof m[i].name, "burst-FITMIX-BER0.03"); m[i].ch = chan_fit_scaled(0.03, FIT_MIX_B, FIT_MIX_P0, FIT_MIX_Q1); i++;
return i;""")
# 5. scheme_t: 2-pass fields
R(""" long repaired, miscorr, exhausted;
double scan_sum;
long scan_trials;
} scheme_t;""",
""" long repaired, miscorr, exhausted;
double scan_sum;
long scan_trials;
int is_2pass;
glist_t gl2; /* second guess list (2-pass: GRAND + GRAND-MO) */
const gmodel_t *mix_model; double mix_p, mix_w; /* arbitration mixture */
long agree, disagree, arb_ok, arb_bad, single_rep, single_misc;
} scheme_t;""")
# 6. constructors for the new schemes, before scheme_bm
R("""static void scheme_bm(scheme_t *s, const char *name, uint16_t poly_id, int D, int n){""",
"""static void scheme_grandmix(scheme_t *s, const char *name, const code_t *c,
int W, int Lmax, const gmodel_t *m, size_t budget){
memset(s, 0, sizeof *s);
snprintf(s->name, sizeof s->name, "%s", name);
s->code = *c; s->has_code = 1; s->is_bm = 0;
glist_grandmix(&s->gl, c, W, Lmax, m, 0.01, 0.5, budget);
}
static void scheme_2pass(scheme_t *s, const char *name, const code_t *c,
int W, int Lmax, const gmodel_t *m, size_t budget){
memset(s, 0, sizeof *s);
snprintf(s->name, sizeof s->name, "%s", name);
s->code = *c; s->has_code = 1; s->is_bm = 0; s->is_2pass = 1;
glist_grand(&s->gl, c, W); /* list 1: iid GRAND */
glist_grandmo(&s->gl2, c, W, Lmax, m, budget); /* list 2: GRAND-MO */
s->mix_model = m; s->mix_p = 0.01; s->mix_w = 0.5;
}
static void scheme_bm(scheme_t *s, const char *name, uint16_t poly_id, int D, int n){""")
# 7. 2-pass branch at the top of scheme_trial
R("""static void scheme_trial(scheme_t *s, uint64_t msg, uint64_t e){
if(s->is_bm){""",
"""static void scheme_trial(scheme_t *s, uint64_t msg, uint64_t e){
if(s->is_2pass){
/* Two-pass arbitration. The decoder only sees the two candidate
* patterns and their mixture LLs -- never the true error. */
uint64_t mask = (s->code.n >= 64) ? ~0ULL : ((1ULL << s->code.n) - 1);
uint64_t ee = e & mask, p1 = 0, p2 = 0;
int r1 = grand_first(&s->gl, &s->code, ee, &p1);
int r2 = grand_first(&s->gl2, &s->code, ee, &p2);
if(r1 < 0 && r2 < 0){ s->exhausted++; return; }
if(r1 < 0 || r2 < 0){
/* only one list hit: accept its candidate */
uint64_t p = (r1 >= 0) ? p1 : p2;
if(p == ee){ s->repaired++; s->single_rep++; }
else { s->miscorr++; s->single_misc++; }
return;
}
if(p1 == p2){
s->agree++;
if(p1 == ee) s->repaired++; else s->miscorr++;
return;
}
s->disagree++;
double l1 = pattern_ll_mix(p1, s->code.n, s->mix_model, s->mix_p, s->mix_w);
double l2 = pattern_ll_mix(p2, s->code.n, s->mix_model, s->mix_p, s->mix_w);
uint64_t pick = (l1 >= l2) ? p1 : p2;
if(pick == ee){ s->repaired++; s->arb_ok++; }
else { s->miscorr++; s->arb_bad++; }
return;
}
if(s->is_bm){""")
# 8. scheme_report: extra 2-pass counters. (The blob printfs share the
# tail of this format string, so anchor on the n=%d k=%d r=%d part,
# which only scheme_report has -- blob uses literal n=768 k=384 r=384.)
R("n=%d k=%d r=%d trials=%ld repaired=%ld rate=%.4f miscorr=%ld exhausted=%ld mean_scan=%.0f list=%zu secs=%.1f\\n",
"n=%d k=%d r=%d trials=%ld repaired=%ld rate=%.4f miscorr=%ld exhausted=%ld mean_scan=%.0f list=%zu agree=%ld disagree=%ld arb_ok=%ld arb_bad=%ld single_rep=%ld single_misc=%ld secs=%.1f\\n")
R(""" s->scan_trials ? s->scan_sum / s->scan_trials : -1.0,
s->gl.n, secs);""",
""" s->scan_trials ? s->scan_sum / s->scan_trials : -1.0,
s->is_2pass ? s->gl.n + s->gl2.n : s->gl.n,
s->agree, s->disagree, s->arb_ok, s->arb_bad, s->single_rep, s->single_misc, secs);""")
# 9. run_group_model: reset new counters
R(""" for(int i = 0; i < nsch; i++){
sch[i].repaired = sch[i].miscorr = sch[i].exhausted = 0;
sch[i].scan_sum = 0; sch[i].scan_trials = 0;
}""",
""" for(int i = 0; i < nsch; i++){
sch[i].repaired = sch[i].miscorr = sch[i].exhausted = 0;
sch[i].scan_sum = 0; sch[i].scan_trials = 0;
sch[i].agree = sch[i].disagree = sch[i].arb_ok = sch[i].arb_bad = 0;
sch[i].single_rep = sch[i].single_misc = 0;
}""")
# 10. build_group: ordering models available to every group
R("""static void build_group(const char *group, const model_t *mo, scheme_t *sch, int *nsch, int *max_n, int *kmax){
gmodel_t lm = list_model_for(&mo->ch);""",
"""static void build_group(const char *group, const model_t *mo, scheme_t *sch, int *nsch, int *max_n, int *kmax){
gmodel_t lm = list_model_for(&mo->ch);
/* Milestone 2.1 ordering models (fixed across test models, except
* 'scaled' which rescales the fitted burst frequency to the test BER):
* fix8 = generic L8 burst prior; fit = fitted RUN params, native;
* fitscaled = fitted RUN shape at the test BER; fitmix = fitted MIX
* params, native. */
chan_t b8 = chan_burst(8, 0.01, 0.0, 0.95);
gmodel_t fix8 = b8.gm;
gmodel_t fitm = chan_gilbert(FIT_RUN_A, FIT_RUN_B, FIT_RUN_P0, FIT_RUN_Q1).gm;
gmodel_t fitsm = chan_fit_scaled(mo->ch.p, FIT_RUN_B, FIT_RUN_P0, FIT_RUN_Q1).gm;
gmodel_t fitmixm = chan_gilbert(FIT_MIX_A, FIT_MIX_B, FIT_MIX_P0, FIT_MIX_Q1).gm;""")
# 11. per-group new schemes. g1 (24,16,8) crc-0x1f9
R(""" scheme_grandmo(&sch[(*nsch)++], "rlc-grandmo", &rlc, 4, 12, &lm, 1000000);
*max_n = 24; *kmax = 16;""",
""" scheme_grandmo(&sch[(*nsch)++], "rlc-grandmo", &rlc, 4, 12, &lm, 1000000);
scheme_grandmo(&sch[(*nsch)++], "crc-0x1f9-grandmo-fix8", &crc, 4, 12, &fix8, 1000000);
scheme_grandmo(&sch[(*nsch)++], "crc-0x1f9-grandmo-fit", &crc, 4, 12, &fitm, 1000000);
scheme_grandmo(&sch[(*nsch)++], "crc-0x1f9-grandmo-fitscaled", &crc, 4, 12, &fitsm, 1000000);
scheme_grandmo(&sch[(*nsch)++], "crc-0x1f9-grandmo-fitmix", &crc, 4, 12, &fitmixm, 1000000);
scheme_grandmix(&sch[(*nsch)++], "crc-0x1f9-grandmix", &crc, 4, 12, &fitsm, 1000000);
scheme_2pass(&sch[(*nsch)++], "crc-0x1f9-grand2pass", &crc, 4, 12, &fitsm, 1000000);
*max_n = 24; *kmax = 16;""")
# g2 (32,16,16) crc-0x109b1
R(""" scheme_grand(&sch[(*nsch)++], "ebch-m8t2-grand", &ebch, 4);
*max_n = 33; *kmax = 16;""",
""" scheme_grand(&sch[(*nsch)++], "ebch-m8t2-grand", &ebch, 4);
scheme_grandmo(&sch[(*nsch)++], "crc-0x109b1-grandmo-fix8", &crc, 4, 12, &fix8, 1000000);
scheme_grandmo(&sch[(*nsch)++], "crc-0x109b1-grandmo-fit", &crc, 4, 12, &fitm, 1000000);
scheme_grandmo(&sch[(*nsch)++], "crc-0x109b1-grandmo-fitscaled", &crc, 4, 12, &fitsm, 1000000);
scheme_grandmo(&sch[(*nsch)++], "crc-0x109b1-grandmo-fitmix", &crc, 4, 12, &fitmixm, 1000000);
scheme_grandmix(&sch[(*nsch)++], "crc-0x109b1-grandmix", &crc, 4, 12, &fitsm, 1000000);
scheme_2pass(&sch[(*nsch)++], "crc-0x109b1-grand2pass", &crc, 4, 12, &fitsm, 1000000);
*max_n = 33; *kmax = 16;""")
# g4 (64,48,16) crc-0x14669
R(""" scheme_grandmo(&sch[(*nsch)++], "rlc-grandmo", &rlc, 4, 12, &lm, 1000000);
*max_n = 64; *kmax = 48;""",
""" scheme_grandmo(&sch[(*nsch)++], "rlc-grandmo", &rlc, 4, 12, &lm, 1000000);
scheme_grandmo(&sch[(*nsch)++], "crc-0x14669-grandmo-fix8", &crc, 4, 12, &fix8, 1000000);
scheme_grandmo(&sch[(*nsch)++], "crc-0x14669-grandmo-fit", &crc, 4, 12, &fitm, 1000000);
scheme_grandmo(&sch[(*nsch)++], "crc-0x14669-grandmo-fitscaled", &crc, 4, 12, &fitsm, 1000000);
scheme_grandmo(&sch[(*nsch)++], "crc-0x14669-grandmo-fitmix", &crc, 4, 12, &fitmixm, 1000000);
scheme_grandmix(&sch[(*nsch)++], "crc-0x14669-grandmix", &crc, 4, 12, &fitsm, 1000000);
scheme_2pass(&sch[(*nsch)++], "crc-0x14669-grand2pass", &crc, 4, 12, &fitsm, 1000000);
*max_n = 64; *kmax = 48;""")
# g5 (24,12,12) crc-0x1343
R(""" scheme_grandmo(&sch[(*nsch)++], "rlc-grandmo", &rlc, 4, 12, &lm, 1000000);
*max_n = 24; *kmax = 12;""",
""" scheme_grandmo(&sch[(*nsch)++], "rlc-grandmo", &rlc, 4, 12, &lm, 1000000);
scheme_grandmo(&sch[(*nsch)++], "crc-0x1343-grandmo-fix8", &crc, 4, 12, &fix8, 1000000);
scheme_grandmo(&sch[(*nsch)++], "crc-0x1343-grandmo-fit", &crc, 4, 12, &fitm, 1000000);
scheme_grandmo(&sch[(*nsch)++], "crc-0x1343-grandmo-fitscaled", &crc, 4, 12, &fitsm, 1000000);
scheme_grandmo(&sch[(*nsch)++], "crc-0x1343-grandmo-fitmix", &crc, 4, 12, &fitmixm, 1000000);
scheme_grandmix(&sch[(*nsch)++], "crc-0x1343-grandmix", &crc, 4, 12, &fitsm, 1000000);
scheme_2pass(&sch[(*nsch)++], "crc-0x1343-grand2pass", &crc, 4, 12, &fitsm, 1000000);
*max_n = 24; *kmax = 12;""")
# 12. cmd_matrix: bigger scheme/model arrays, p3 header, free gl2
R(""" printf("# p2 matrix: guess budget 1M, GRAND W=4, GRAND-MO bursts<=12 + W<=4\\n");""",
""" printf("# p3 matrix: guess budget 1M, GRAND W=4, GRAND-MO bursts<=12 + W<=4; new: grandmo-fix8/fit/fitscaled/fitmix, grandmix (w=0.5, iid p=0.01), grand2pass\\n");""")
R(""" model_t models[8]; int nmod = all_models(models);""",
""" model_t models[16]; int nmod = all_models(models);""")
R(""" scheme_t sch[8]; int nsch, max_n, kmax;""",
""" scheme_t sch[16]; int nsch, max_n, kmax;""")
R(""" for(int i = 0; i < nsch; i++){ free(sch[i].gl.pat); free(sch[i].gl.syn); }""",
""" for(int i = 0; i < nsch; i++){ free(sch[i].gl.pat); free(sch[i].gl.syn); free(sch[i].gl2.pat); free(sch[i].gl2.syn); }""")
# 13. syndev subcommand, inserted before cmd_matrix
R("""static int cmd_matrix(int argc, char **argv){""",
"""/* ---------------- syndev: can the syndrome tell burst from iid? ------
* For each group/model pair: draw half the trials from iid scat and half
* from a burst channel at the SAME BER, label = burst?, feature =
* popcount(syndrome of the error). Reports AUC of syndrome weight as a
* burstiness classifier (Mann-Whitney with tie-averaged ranks), mean
* syndrome weight per class, and P(burst | syndrome weight).
* If AUC ~= 0.5, no hard pre-decode model selection from the syndrome
* is possible and the mixture / two-pass decoders are the way. */
typedef struct { int feat, label; } fl_t;
static int cmp_fl(const void *a, const void *b){
int x = ((const fl_t*)a)->feat, y = ((const fl_t*)b)->feat;
return (x > y) - (x < y);
}
static int cmd_syndev(int argc, char **argv){
const char *want_g = (argc > 0) ? argv[0] : "all";
long trials = (argc > 1) ? atol(argv[1]) : 20000;
const char *groups[] = {"g2", "g4"};
double bers[] = {0.01, 0.03};
code_t codes[2];
code_cyclic(&codes[0], "crc-0x109b1", 0x109b1ULL, 16, 32);
code_cyclic(&codes[1], "crc-0x14669", 0x14669ULL, 16, 64);
for(int gi = 0; gi < 2; gi++){
if(strcmp(want_g, "all") && strcmp(want_g, groups[gi])) continue;
const code_t *c = &codes[gi];
for(int bi = 0; bi < 2; bi++){
double ber = bers[bi];
chan_t chb = chan_burst(8, ber, 0.0, 0.95);
fl_t *fl = malloc(trials * sizeof *fl);
long half = trials / 2;
rng_seed(0x5EEDULL + gi * 100 + bi);
for(long t = 0; t < trials; t++){
chan_t ch; ch.kind = 0; ch.p = ber;
int label = 0;
if(t >= half){ ch = chb; label = 1; }
uint64_t e = chan_draw(&ch, c->n);
fl[t].feat = popcnt64(code_syn(c, e));
fl[t].label = label;
}
/* AUC by Mann-Whitney with tie-averaged ranks */
qsort(fl, trials, sizeof *fl, cmp_fl);
double rank_sum = 0; long npos = half, nneg = trials - half;
long i = 0;
double mean_pos = 0, mean_neg = 0;
for(long t = 0; t < trials; t++){
if(fl[t].label) mean_pos += fl[t].feat; else mean_neg += fl[t].feat;
}
while(i < trials){
long j = i;
while(j < trials && fl[j].feat == fl[i].feat) j++;
double avg_rank = (double)(i + 1 + j) / 2.0; /* 1-based */
for(long k = i; k < j; k++)
if(fl[k].label) rank_sum += avg_rank;
i = j;
}
double auc = (rank_sum - (double)npos * (npos + 1) / 2.0) / ((double)npos * nneg);
printf("SYNDEV group=%s ber=%.2f n=%d trials=%ld auc=%.4f mean_syn_burst=%.2f mean_syn_iid=%.2f\\n",
groups[gi], ber, c->n, trials, auc, mean_pos / npos, mean_neg / nneg);
/* P(burst | syndrome weight) table */
int maxw = 0;
for(long t = 0; t < trials; t++) if(fl[t].feat > maxw) maxw = fl[t].feat;
printf("SYNDEV group=%s ber=%.2f P(burst|synw):", groups[gi], ber);
for(int w = 0; w <= maxw && w <= 16; w++){
long tot = 0, pos = 0;
for(long t = 0; t < trials; t++)
if(fl[t].feat == w){ tot++; if(fl[t].label) pos++; }
if(tot >= 20) printf(" w%d=%.2f(n=%ld)", w, (double)pos / tot, tot);
}
printf("\\n");
fflush(stdout);
free(fl);
}
}
return 0;
}
static int cmd_matrix(int argc, char **argv){""")
# 14. main dispatch + usage
R(""" fprintf(stderr, "usage: p2 selftest | dmin g=.. r=.. n=.. | matrix [group] [model] [trials]\\n");""",
""" fprintf(stderr, "usage: p3 selftest | dmin g=.. r=.. n=.. | matrix [group] [model] [trials] | syndev [group] [trials]\\n");""")
R(""" if(!strcmp(argv[1], "matrix")) return cmd_matrix(argc - 2, argv + 2);""",
""" if(!strcmp(argv[1], "matrix")) return cmd_matrix(argc - 2, argv + 2);
if(!strcmp(argv[1], "syndev")) return cmd_syndev(argc - 2, argv + 2);""")
# 15. syndev: conditional AUC over damaged blocks only (syndrome != 0).
# The unconditional AUC conflates "clean block" with "burst": burst
# channels leave most blocks clean, so syndrome weight is dominated by
# the clean/damaged distinction, not burst/iid. The conditional AUC
# answers the question a decoder actually faces: given this block IS
# damaged, does the syndrome say burst or iid?
R(""" printf("SYNDEV group=%s ber=%.2f n=%d trials=%ld auc=%.4f mean_syn_burst=%.2f mean_syn_iid=%.2f\\n",
groups[gi], ber, c->n, trials, auc, mean_pos / npos, mean_neg / nneg);""",
""" /* conditional AUC: only damaged blocks (syndrome != 0) */
long nsub = 0, npos_sub = 0;
for(long t = 0; t < trials; t++)
if(fl[t].feat > 0){ nsub++; if(fl[t].label) npos_sub++; }
long nneg_sub = nsub - npos_sub;
double rank_sub = 0; long idx = 0, i2 = 0;
while(i2 < trials){
if(fl[i2].feat == 0){ i2++; continue; }
long j2 = i2;
while(j2 < trials && fl[j2].feat == fl[i2].feat) j2++;
long cnt = 0, cpos = 0;
for(long k = i2; k < j2; k++)
if(fl[k].feat > 0){ cnt++; if(fl[k].label) cpos++; }
double avg = (double)(idx + 1 + idx + cnt) / 2.0;
rank_sub += cpos * avg;
idx += cnt; i2 = j2;
}
double auc_sub = (nsub > 0 && npos_sub > 0 && nneg_sub > 0)
? (rank_sub - (double)npos_sub * (npos_sub + 1) / 2.0) / ((double)npos_sub * nneg_sub) : -1.0;
printf("SYNDEV-COND group=%s ber=%.2f n=%d damaged=%ld (burst %ld, %.3f of burst trials; iid %.3f) auc_cond=%.4f\\n",
groups[gi], ber, c->n, nsub, npos_sub,
(double)npos_sub / (double)half, (double)nneg_sub / (double)(trials - half), auc_sub);
printf("SYNDEV group=%s ber=%.2f n=%d trials=%ld auc=%.4f mean_syn_burst=%.2f mean_syn_iid=%.2f\\n",
groups[gi], ber, c->n, trials, auc, mean_pos / npos, mean_neg / nneg);""")
def main():
gen_fit_params()
src = open(SRC).read()
for idx, (old, new) in enumerate(REPLACEMENTS):
n = src.count(old)
if n != 1:
print(f"REPLACEMENT {idx} FAILED: count={n} for anchor: {old[:90]!r}")
sys.exit(1)
src = src.replace(old, new)
open(DST, "w").write(src)
print(f"wrote {DST}: {len(REPLACEMENTS)} replacements applied")
# Makefile: append p3 target
mk = os.path.join(ROOT, "Makefile")
mtxt = open(mk).read()
if "p3:" not in mtxt:
mtxt += """
p3: p3.c ../bch.c ../bch.h ../bch_polys.h fit_params.h
\tgcc -O2 -std=c11 -Wall -Wextra -march=native -D_POSIX_C_SOURCE=200809L -o p3 p3.c ../bch.c -lm
"""
open(mk, "w").write(mtxt)
print("appended p3 target to Makefile")
if __name__ == "__main__":
main()
-22
View File
@@ -1,22 +0,0 @@
# encode K=100 T=1024 R=10: 0.001 s (72.96 MB/s)
# overhead-curve K=100 T=1024 sent=110 trials=2000 seed=1234
Encoder: due to unclear reasons the process can not continue
Encoder: due to unclear reasons the process can not continue
Encoder: due to unclear reasons the process can not continue
Encoder: due to unclear reasons the process can not continue
Encoder: due to unclear reasons the process can not continue
Encoder: due to unclear reasons the process can not continue
Encoder: due to unclear reasons the process can not continue
recv K+0: 1993/2000 = 0.9965
recv K+1: 2000/2000 = 1.0000
recv K+2: 2000/2000 = 1.0000
recv K+3: 2000/2000 = 1.0000
recv K+5: 2000/2000 = 1.0000
# encode K=256 T=1024 R=26: 0.004 s (65.55 MB/s)
# overhead-curve K=256 T=1024 sent=282 trials=500 seed=99
Encoder: due to unclear reasons the process can not continue
recv K+0: 499/500 = 0.9980
recv K+1: 500/500 = 1.0000
recv K+2: 500/500 = 1.0000
recv K+3: 500/500 = 1.0000
recv K+5: 500/500 = 1.0000
-30
View File
@@ -1,30 +0,0 @@
#!/bin/bash
# run_fit1.sh - Milestone 2.1, experiment A: real damage + Gilbert fit.
# Builds damage.c/gilsim.c, applies calibrated damage scenarios to real
# lzply archives, fits a Gilbert model to each XOR error stream.
set -u
cd /root/lzply/randfec/m2 || exit 1
gcc -O2 -std=c11 -Wall -Wextra -o damage damage.c -lm || exit 1
gcc -O2 -std=c11 -Wall -Wextra -o gilsim gilsim.c -lm || exit 1
mkdir -p dmg fits
M=mixed-e4.lzply
echo "== damage on $M =="
./damage $M dmg/mixed-iid001.lzply iid 0.001 11
./damage $M dmg/mixed-iid01.lzply iid 0.01 12
./damage $M dmg/mixed-run1ff.lzply runs 1 800 ff 15
./damage $M dmg/mixed-run4ff.lzply runs 4 200 ff 13
./damage $M dmg/mixed-run8ff.lzply runs 8 100 ff 14
./damage $M dmg/mixed-run4rand.lzply runs 4 200 rand 18
./damage $M dmg/mixed-mix.lzply mix 0.0005 4 200 ff 16
./damage $M dmg/mixed-run512ff.lzply runs 512 2 ff 17
echo "== fits on $M =="
for n in iid001 iid01 run1ff run4ff run8ff run4rand mix run512ff; do
python3 fit.py $M dmg/mixed-$n.lzply mixed-$n fits/ 2>&1
done
echo "== damage + fit on big-e4.lzply (50MB, tight stats) =="
./damage big-e4.lzply dmg/big-mix.lzply mix 0.0005 4 200 ff 16
./damage big-e4.lzply dmg/big-run4ff.lzply runs 4 200 ff 13
python3 fit.py big-e4.lzply dmg/big-mix.lzply big-mix fits/ 2>&1
python3 fit.py big-e4.lzply dmg/big-run4ff.lzply big-run4ff fits/ 2>&1
echo "== DONE =="
ls -la fits/
-35
View File
@@ -1,35 +0,0 @@
#!/bin/bash
# run_fit2.sh - refit all scenarios with the fixed fitter (correct
# meanrun0, lag64/256 + mean runs in the loss, basin hopping), then
# validate the headline fits by simulating the fitted Gilbert model
# with gilsim and comparing the window-weight histograms (which were
# NOT in the fit loss) against the real damage.
set -u
cd /root/lzply/randfec/m2 || exit 1
gcc -O2 -std=c11 -Wall -Wextra -o gilsim gilsim.c -lm || exit 1
rm -rf fits2; mkdir -p fits2
echo "== refits on mixed =="
for n in iid001 iid01 run1ff run4ff run8ff run4rand mix run512ff; do
python3 fit.py mixed-e4.lzply dmg/mixed-$n.lzply mixed-$n fits2/ 2>&1
done
echo "== refits on big =="
python3 fit.py big-e4.lzply dmg/big-mix.lzply big-mix fits2/ 2>&1
python3 fit.py big-e4.lzply dmg/big-run4ff.lzply big-run4ff fits2/ 2>&1
echo "== gilsim validation: simulate fitted params, compare vs real =="
# reads FITPARAMS lines from fits2 and runs gilsim with those params
python3 - <<'PYEOF'
import json, subprocess, glob, os
for jf in sorted(glob.glob("fits2/*.json")):
d = json.load(open(jf))
p = d["fitted"]; obs = d["observed"]
nbits = 20000000
out = subprocess.run(["./gilsim", repr(p["a"]), repr(p["b"]), repr(p["p0"]),
repr(p["q1"]), str(nbits), "99"],
capture_output=True, text=True).stdout
print(f"VALIDATE {d['name']}: real win32_Pgt2={obs['win32_pgt2']:.4f} "
f"win32_Pgt4={obs['win32_pgt4']:.4f} win64_Pgt2={obs['win64_pgt2']:.4f} "
f"win64_Pgt4={obs['win64_pgt4']:.4f} meanrun1={obs['meanrun1']:.2f} "
f"meanrun0={obs['meanrun0']:.0f}")
print(" sim: " + " | ".join(l.strip() for l in out.strip().split("\n")))
PYEOF
echo "== DONE =="
-15
View File
@@ -1,15 +0,0 @@
#!/bin/bash
# run_p3.sh - Milestone 2.1, experiment B+C: p3 model-selection matrix
# (groups g1/g2/g4/g5 x all 10 models x 10,000 trials) + syndev test.
# Blob excluded: GRAND is infeasible at n=768 and blob schemes are
# unchanged from Milestone 1.
set -u
cd /root/lzply/randfec || exit 1
./p3 syndev all 20000 > results/p3-syndev.log 2>&1
for g in g1 g2 g4 g5; do
echo "== group $g =="
./p3 matrix $g all 10000 > results/p3-matrix-$g.log 2>&1
echo "== group $g done, rc=$? =="
done
echo "== DONE =="
grep -h "^CELL" results/p3-matrix-*.log | wc -l
-80
View File
@@ -1,80 +0,0 @@
#!/usr/bin/env bash
# run_p4.sh — M2.2 RaptorQ file-recovery matrix driver (hot_house).
# Runs the p4 cell grid in parallel (24 workers), one log per cell under
# randfec/results/p4-cells/. Then summarize_p4.py builds the tables.
# Log: randfec/results/p4-driver.log
set -u
cd /root/lzply/randfec
mkdir -p results/p4-cells
CELLS=results/p4-cells/cells.txt
: > "$CELLS"
S=1000
add() { echo "$1" >> "$CELLS"; S=$((S+1)); }
# Leg A: iid symbol loss, K=100, real decode, 5000 trials
for R in 0 2 5 10; do
for E in 0.001 0.005 0.01 0.02 0.05 0.10; do
add "./p4 100 1024 $R $E 0 5000 $S iid --real"
done
done
# Leg A-real-src: real archive bytes as source (2 cells)
add "./p4 100 1024 10 0.02 0 2000 $S iid --real --srcfile m2/mixed-e4.lzply"
add "./p4 100 1024 10 0.02 4 2000 $S gilbert --real --srcfile m2/mixed-e4.lzply"
# Leg B: Gilbert burst symbol loss, K=100, real decode, 5000 trials
for R in 0 2 5 10; do
for B in 4 16; do
for E in 0.005 0.01 0.02 0.05; do
add "./p4 100 1024 $R $E $B 5000 $S gilbert --real"
done
done
done
# Leg C: BCH-block failures, real decode
for R in 0 20 51 102; do
for Q in 0.001 0.005 0.01 0.02 0.05; do
add "./p4 1024 1024 $R $Q 0 2000 $S block --real"
done
done
for R in 0 82 205 410; do
for Q in 0.001 0.005 0.01 0.02 0.05; do
add "./p4 4096 1024 $R $Q 0 1000 $S block --real"
done
done
# Leg C: model-only at large K
for R in 0 328 819 1638; do
for Q in 0.001 0.005 0.01 0.02 0.05; do
add "./p4 16384 1024 $R $Q 0 2000 $S block"
done
done
for R in 0 1024 2560 5120; do
for Q in 0.001 0.005 0.01 0.02 0.05; do
add "./p4 51200 1024 $R $Q 0 2000 $S block"
done
done
# Leg C spots: real decode at K=16384, 50 trials
for R in 819 1638; do
for Q in 0.005 0.01 0.02; do
add "./p4 16384 1024 $R $Q 0 50 $S block --real"
done
done
# Leg C-burst: block failures in bursts of 2 blocks
for R in 205 410; do
for Q in 0.005 0.01 0.02; do
add "./p4 4096 1024 $R $Q 2 1000 $S blockburst --real"
done
done
for R in 819 1638; do
for Q in 0.005 0.01 0.02; do
add "./p4 16384 1024 $R $Q 2 2000 $S blockburst"
done
done
echo "cells: $(wc -l < "$CELLS")"
date -u
awk '{print NR" "$0}' "$CELLS" > results/p4-cells/cells_n.txt
# each line: <n> <cmd...>; run with per-cell log
xargs -a results/p4-cells/cells_n.txt -P 24 -L 1 sh -c \
'n=$1; shift; "$@" > results/p4-cells/cell-$n.log 2>&1' sh
echo "xargs done"
date -u
grep -c '^cell' results/p4-cells/cell-*.log | grep -v ':1' || true
echo "cells done: $(grep -h '^cell' results/p4-cells/cell-*.log | wc -l) / $(wc -l < "$CELLS")"
-85
View File
@@ -1,85 +0,0 @@
+ date -u
Thu Dec 3 03:34:09 AM UTC 2026
+ echo '== apt Eigen3 =='
== apt Eigen3 ==
+ apt-get update -qq
+ tail -3
+ apt-get install -y libeigen3-dev
+ tail -5
[!] Scanning application launchers
Removing duplicate or broken launchers...
[i] 671 launcher(s) processed, 206 launcher(s) for uninstalled packages
[!] Launchers have been successfully updated!
--------------------------------------------------
+ ls /usr/include/eigen3
+ head -3
Eigen
signature_of_eigen3_matrix_library
unsupported
+ echo '== foxsen build+tests =='
== foxsen build+tests ==
+ cd /root/raptorq/foxsen
+ make clean
+ make -j24 tests
+ tail -30
OK
test_bandwidth_decode_small ...
Encode+Decode throughput:
K=8 T=4 lost=1 overhead=4 iters=500 encode+decode: 0.706956 MB/s (0.0215838s)
K=8 T=64 lost=1 overhead=4 iters=500 encode+decode: 7.55781 MB/s (0.0323031s)
K=8 T=256 lost=2 overhead=4 iters=500 encode+decode: 14.5237 MB/s (0.067239s)
K=8 T=1024 lost=2 overhead=4 iters=200 encode+decode: 20.1242 MB/s (0.0776429s)
OK
test_bandwidth_decode_medium ... K=50 T=64 lost=5 overhead=10 iters=100 encode+decode: 9.00654 MB/s (0.0338838s)
K=50 T=256 lost=5 overhead=10 iters=100 encode+decode: 22.208 MB/s (0.0549669s)
K=50 T=1024 lost=5 overhead=10 iters=50 encode+decode: 35.574 MB/s (0.068629s)
OK
test_bandwidth_decode_large ... K=100 T=256 lost=10 overhead=15 iters=50 encode+decode: 22.1523 MB/s (0.055105s)
K=100 T=1024 lost=10 overhead=15 iters=20 encode+decode: 38.9774 MB/s (0.0501091s)
K=256 T=1024 lost=25 overhead=30 iters=10 encode+decode: 33.3195 MB/s (0.075031s)
OK
test_bandwidth_stream_small ...
Stream throughput (split data into FEC blocks):
stream 64KB (K=8 T=64 blocks=128 loss=1/8) encode: 15.6448 MB/s decode: 7.33578 MB/s
stream 64KB (K=8 T=256 blocks=32 loss=1/8) encode: 29.594 MB/s decode: 14.4911 MB/s
OK
test_bandwidth_stream_medium ... stream 256KB (K=50 T=256 blocks=21 loss=5/50) encode: 43.8356 MB/s decode: 21.9626 MB/s
stream 256KB (K=50 T=1024 blocks=6 loss=5/50) encode: 68.0851 MB/s decode: 34.827 MB/s
OK
test_bandwidth_stream_large ... stream 1024KB (K=100 T=1024 blocks=11 loss=10/100) encode: 75.7881 MB/s decode: 38.9886 MB/s
stream 1024KB (K=256 T=1024 blocks=4 loss=25/256) encode: 64.2097 MB/s decode: 32.9143 MB/s
OK
================================
54 tests: 54 passed, 0 failed
+ echo '== libRaptorQ cmake configure =='
== libRaptorQ cmake configure ==
+ cd /root/raptorq/libRaptorQ
+ mkdir -p build
+ cd build
+ cmake .. -DCMAKE_BUILD_TYPE=Release -DPROFILING=OFF -DLTO=OFF
+ tail -15
-- Found git in /usr/bin/git
-- Found eigen3 in /usr/include/eigen3
CMake Error at cmake/FindRQ_LZ4.cmake:61 (MESSAGE):
Could not find "lz4" library. Please install the "lz4" library or at least
run:
cd /root/raptorq/libRaptorQ
git submodule init
git submodule update
Call Stack (most recent call first):
CMakeLists.txt:193 (find_package)
-- Configuring incomplete, errors occurred!
+ echo '== libRaptorQ build =='
== libRaptorQ build ==
+ make -j24
+ tail -15
make: *** No targets specified and no makefile found. Stop.
+ echo DONE
DONE
+ date -u
Thu Dec 3 03:35:00 AM UTC 2026
-72
View File
@@ -1,72 +0,0 @@
#!/usr/bin/env python3
"""summarize_p3.py - compact table from p3 matrix CELL lines.
Usage: summarize_p3.py results/p3-matrix-*.log
Per group x model: repair rates of the key schemes, the best specialist
(max of CRC-GRAND / CRC-GRAND-MO-oracle) and the regret of grandmix and
grand2pass vs that specialist, plus 2-pass arbitration accuracy.
"""
import sys, re
CELL = re.compile(
r"CELL group=(\S+) model=(\S+) scheme=(\S+)\s+n=\d+ k=\d+ r=\d+ trials=(\d+) "
r"repaired=(\d+) rate=([\d.]+) miscorr=(\d+) exhausted=(\d+) mean_scan=([\d.\-]+) "
r"list=(\d+) agree=(\d+) disagree=(\d+) arb_ok=(\d+) arb_bad=(\d+) "
r"single_rep=(\d+) single_misc=(\d+) secs=([\d.]+)")
MODELS = ["scat-p0.01", "scat-p0.03", "burst-L8-BER0.01", "burst-L32-BER0.01",
"burst-L8-BER0.03", "mix-L16-BER0.01",
"burst-FITRUN-BER0.01", "burst-FITRUN-BER0.03",
"burst-FITMIX-BER0.01", "burst-FITMIX-BER0.03"]
# (column label, suffix to match; crc- preferred when several match)
COLS = [("bm", "-bm"), ("grand", "-grand"), ("grandmo", "-grandmo"),
("gmo-fix8", "-grandmo-fix8"), ("gmo-fit", "-grandmo-fit"),
("gmo-fitscaled", "-grandmo-fitscaled"), ("gmo-fitmix", "-grandmo-fitmix"),
("grandmix", "-grandmix"), ("grand2pass", "-grand2pass")]
def pick(cell, suffix):
cands = [(s, v) for s, v in cell.items() if s.endswith(suffix)]
if not cands:
return None
for s, v in cands: # prefer the CRC scheme (same code as the GRAND-MO family)
if s.startswith("crc-"):
return v
return cands[0][1]
def main():
data = {}
for path in sys.argv[1:]:
for line in open(path):
m = CELL.search(line)
if not m:
continue
g, mo, sch = m.group(1), m.group(2), m.group(3)
data.setdefault((g, mo), {})[sch] = (
float(m.group(6)), int(m.group(7)), int(m.group(8)),
int(m.group(11)), int(m.group(12)), int(m.group(13)),
int(m.group(14)), int(m.group(15)), int(m.group(16)))
for g in sorted({gg for gg, _ in data}):
print(f"### group {g}")
print("model | " + " | ".join(f"{c[0]:>13}" for c in COLS) +
" | best-spec | mix-regr | 2p-regr | arb-acc")
for mo in MODELS:
cell = data.get((g, mo))
if not cell:
continue
vals = {label: pick(cell, suf) for label, suf in COLS}
spec = max([v[0] for v in (vals["grand"], vals["grandmo"]) if v] or [float("nan")])
def r(v):
return f"{v[0] * 100:13.2f}" if v else " nan"
mixreg = f"{(spec - vals['grandmix'][0]) * 100:8.2f}" if vals["grandmix"] else " nan"
p2reg = f"{(spec - vals['grand2pass'][0]) * 100:8.2f}" if vals["grand2pass"] else " nan"
arb = "-"
p2 = vals["grand2pass"]
if p2:
d = p2[4] + p2[5]
arb = f"{p2[4]}/{d}={100.0 * p2[4] / d:.0f}%" if d else "-"
print(f"{mo:>22} | " + " | ".join(r(vals[label]) for label, _ in COLS) +
f" | {spec * 100:9.2f} | {mixreg} | {p2reg} | {arb}")
print()
if __name__ == "__main__":
main()
-135
View File
@@ -1,135 +0,0 @@
#!/usr/bin/env python3
# summarize_p4.py — parse randfec/results/p4-cells/cell-*.log into tables.
# Usage: summarize_p4.py [results dir, default results/p4-cells]
# Prints rates (%) with Wilson 95% CI half-widths, grouped by leg.
import glob, math, os, re, sys
from collections import defaultdict
d = sys.argv[1] if len(sys.argv) > 1 else "results/p4-cells"
pat = re.compile(r"cell K=(\d+) T=(\d+) R=(\d+) e=([\d.e+-]+) burst=([\d.e+-]+) "
r"mode=(\S+) trials=(\d+) seed=\d+ bch=(\d+) rs=(\d+) rqmod=(\d+) "
r"rqreal=(-?\d+) rq_only=(\d+) rs_only=(\d+) agree=(-?\d+)")
def wilson(k, n):
if n == 0: return 0.0, 0.0
z = 1.96; p = k / n; den = 1 + z*z/n
c = p + z*z/(2*n); h = z*math.sqrt(p*(1-p)/n + z*z/(4*n*n))
return 100*(c-h)/den, 100*(c+h)/den
cells = []
for f in sorted(glob.glob(os.path.join(d, "cell-*.log"))):
with open(f) as fh:
for line in fh:
m = pat.search(line)
if m:
K, T, R = int(m.group(1)), int(m.group(2)), int(m.group(3))
e, burst = float(m.group(4)), float(m.group(5))
mode, n = m.group(6), int(m.group(7))
bch, rs, rqmod = int(m.group(8)), int(m.group(9)), int(m.group(10))
rqreal = int(m.group(11)); rqo, rso = int(m.group(12)), int(m.group(13))
agree = int(m.group(14))
cells.append(dict(K=K, T=T, R=R, e=e, burst=burst, mode=mode, n=n,
bch=bch, rs=rs, rqmod=rqmod, rqreal=rqreal,
rq_only=rqo, rs_only=rso, agree=agree, f=f))
print(f"cells parsed: {len(cells)}")
def fmt(k, n):
lo, hi = wilson(k, n)
return f"{100*k/n:6.2f} [{lo:5.2f},{hi:5.2f}]"
def table(title, rows, cols, get):
# rows: list of row labels with key fn; cols: list of (label, R)
print(f"\n## {title}")
print("row | " + " | ".join(f"{c:>22}" for c in cols))
for rl, rk in rows:
vals = []
for cl, R in cols:
c = get(rk, R)
vals.append(fmt(c[0], c[1]) if c else " " * 22)
print(f"{rl} | " + " | ".join(vals))
# Leg A: K=100 iid
A = [c for c in cells if c["K"] == 100 and c["mode"] == "iid" and "mixed" not in c["f"]]
# (srcfile cells are in the same K/mode; they share cell files only if the
# command line differs — they do, but the log line has no srcfile marker;
# identify them by trials=2000)
A = [c for c in A if c["n"] == 5000]
if A:
Rs = sorted(set(c["R"] for c in A))
es = sorted(set(c["e"] for c in A))
print("\n## Leg A — iid symbol loss, K=100 T=1024, REAL foxsen decode, 5000 trials/cell")
print("rate% [Wilson95 lo,hi]; columns = overhead R (symbols)")
for scheme, key in [("rqreal", "rqreal"), ("rs(MDS)", "rs"), ("rqmod(K+2)", "rqmod"), ("bch-alone", "bch")]:
print(f"\n### {scheme}")
print("e | " + " | ".join(f"R={R:<18}" for R in Rs))
for e in es:
vals = []
for R in Rs:
cc = [c for c in A if c["e"] == e and c["R"] == R]
vals.append(fmt(cc[0][key], cc[0]["n"]) if cc and cc[0][key] >= 0 else " " * 22)
print(f"{e:<5} | " + " | ".join(vals))
# Leg A real-src
As = [c for c in cells if c["K"] == 100 and c["n"] == 2000]
if As:
print("\n## Leg A-real-src — real archive bytes as source, K=100 R=10, 2000 trials")
for c in As:
print(f"mode={c['mode']} e={c['e']} burst={c['burst']}: "
f"rqreal={fmt(c['rqreal'], c['n'])} rs={fmt(c['rs'], c['n'])} "
f"bch={fmt(c['bch'], c['n'])}")
# Leg B: K=100 gilbert
B = [c for c in cells if c["K"] == 100 and c["mode"] == "gilbert" and c["n"] == 5000]
if B:
Rs = sorted(set(c["R"] for c in B))
print("\n## Leg B — Gilbert burst symbol loss, K=100, REAL decode, 5000 trials/cell")
for scheme, key in [("rqreal", "rqreal"), ("rs(MDS)", "rs"), ("rqmod(K+2)", "rqmod"), ("bch-alone", "bch")]:
print(f"\n### {scheme}")
print("burst e | " + " | ".join(f"R={R:<18}" for R in Rs))
for burst in sorted(set(c["burst"] for c in B)):
for e in sorted(set(c["e"] for c in B if c["burst"] == burst)):
vals = []
for R in Rs:
cc = [c for c in B if c["e"] == e and c["burst"] == burst and c["R"] == R]
vals.append(fmt(cc[0][key], cc[0]["n"]) if cc and cc[0][key] >= 0 else " " * 22)
print(f"{burst:>5.0f} {e:<5} | " + " | ".join(vals))
# Leg C: block / blockburst
C = [c for c in cells if c["mode"] in ("block", "blockburst")]
if C:
print("\n## Leg C — BCH-block failures (1 block = 512 symbols @T=1024)")
for mode in ("block", "blockburst"):
CC = [c for c in C if c["mode"] == mode]
if not CC: continue
for K in sorted(set(c["K"] for c in CC)):
KK = [c for c in CC if c["K"] == K]
Rs = sorted(set(c["R"] for c in KK))
print(f"\n### {mode} K={K} ({K//512} source blocks/file; R% = "
+ ", ".join(f"{R}={100*R/K:.0f}%" for R in Rs) + ")")
for scheme, key in [("rqreal", "rqreal"), ("rqmod(K+2)", "rqmod"),
("rs(MDS)", "rs"), ("bch-alone", "bch")]:
print(f"-- {scheme}")
print("q | " + " | ".join(f"R={R:<18}" for R in Rs))
for q in sorted(set(c["e"] for c in KK)):
vals = []
for R in Rs:
cc = [c for c in KK if c["e"] == q and c["R"] == R]
# prefer the largest-trials cell when duplicates (spots vs main)
cc = sorted(cc, key=lambda c: -c["n"])
v = cc[0] if cc else None
vals.append(fmt(v[key], v["n"]) if v and v[key] >= 0 else " " * 22)
print(f"{q:<5} | " + " | ".join(vals))
# Model-vs-real agreement (all --real cells)
R = [c for c in cells if c["rqreal"] >= 0]
if R:
tot_agree = sum(c["agree"] for c in R); tot_n = sum(c["n"] for c in R)
tot_rqo = sum(c["rq_only"] for c in R); tot_rso = sum(c["rs_only"] for c in R)
print(f"\n## Model-vs-real: rqmod==rqreal on {tot_agree}/{tot_n} trials "
f"({100*tot_agree/tot_n:.2f}%); real-beats-RS {tot_rqo} trials, "
f"RS-beats-real {tot_rso} trials (paired, same masks)")
# burst-only agreement
Rb = [c for c in R if c["mode"] in ("gilbert", "blockburst")]
if Rb:
a = sum(c["agree"] for c in Rb); n = sum(c["n"] for c in Rb)
print(f" bursty modes only: agree {a}/{n} ({100*a/n:.2f}%)")
-756
View File
@@ -1,756 +0,0 @@
/* p2.c - Phase 2: decoder-centric FEC comparison for lzply.
*
* Phase 1 searched CODES by d_min and found only random CRC wins.
* Phase 2 asks the decoder question: at the same (n,k,r), on the same
* damage, how much does the DECODER matter? Schemes compared on
* identical (message, error) trial streams:
* bch-bm : real lzply BCH (../bch.c) + Berlekamp-Massey decode
* bch-grand : the SAME BCH generator poly, decoded by hard GRAND
* (weight-ordered noise guesses = ML within budget)
* crc-grand : Phase-1 searched CRC poly + GRAND
* crc-grandmo : searched CRC poly + GRAND-MO (guesses ordered by
* Markov burst-model likelihood, Viterbi-scored)
* rlc-grandmo : random parity-check matrix + GRAND-MO
* ebch-grand : extended BCH g(x)*(x+1), +1 parity bit, +GRAND
* Damage models: iid scattered bit flips; Gilbert 2-state burst
* channel (mean burst L, overall BER, optional background p0).
* Metric: block repair rate = fraction of trials where the decoder
* returns exactly the transmitted codeword, plus mean guess-scan
* position and budget-exhaustion count. No integration change here.
*
* Layout: codeword bit i (0 = LSB) is coefficient of x^i; data in
* the high k bits, parity in the low r bits; n <= 64 (blob mode uses
* 640-bit streams sliced into 32-bit blocks, plus one 640-bit BCH).
* The BM path maps p2 bit positions onto bch.c stored bytes by pure
* reversal (stored bit s <-> p2 bit n-1-s); both are the same set of
* multiples of g(x), so the comparison is exact.
*/
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <time.h>
#include <math.h>
#include "../bch.h"
/* ---------------- PRNG: xorshift64* ---------------- */
static uint64_t rng_s;
static void rng_seed(uint64_t s){ rng_s = s ? s : 0x9E3779B97F4A7C15ULL; }
static uint64_t rng_next(void){
uint64_t x = rng_s; x ^= x >> 12; x ^= x << 25; x ^= x >> 27;
rng_s = x; return x * 0x2545F4914F6CDD1DULL;
}
static double rng_uniform(void){ return (rng_next() >> 11) * (1.0 / 9007199254740992.0); }
static int popcnt64(uint64_t x){ return __builtin_popcountll(x); }
/* ---------------- polynomial arithmetic over GF(2) ---------------- */
static uint64_t poly_mod(uint64_t v, int deg_v, uint64_t g, int r){
for(int i = deg_v - 1; i >= r; i--)
if((v >> i) & 1ULL) v ^= (g << (i - r));
return v & ((r >= 64) ? ~0ULL : ((1ULL << r) - 1));
}
/* ---------------- code abstraction (syndrome function only) ---------------- */
typedef struct {
char name[64];
int n, k, r;
int is_rlc;
uint64_t g; /* cyclic generator (0 for RLC) */
uint64_t s[64]; /* single-bit syndromes (cyclic) */
uint64_t hrow[64]; /* parity-check rows as masks over n bits (RLC) */
} code_t;
static uint64_t code_syn(const code_t *c, uint64_t e){
if(c->is_rlc){
uint64_t s = 0;
for(int j = 0; j < c->r; j++)
s |= (uint64_t)(__builtin_parityll(e & c->hrow[j])) << j;
return s;
}
uint64_t s = 0;
while(e){ int i = __builtin_ctzll(e); e &= e - 1; s ^= c->s[i]; }
return s;
}
static void code_cyclic(code_t *c, const char *name, uint64_t g, int r, int n){
memset(c, 0, sizeof *c);
snprintf(c->name, sizeof c->name, "%s", name);
c->g = g; c->r = r; c->n = n; c->k = n - r; c->is_rlc = 0;
for(int i = 0; i < n; i++){
if(i < r) c->s[i] = 1ULL << i;
else { int j = i - r; c->s[i] = poly_mod((1ULL << j) << r, j + r + 1, g, r); }
}
}
/* Random parity-check matrix, r rows over n bits, full rank r. */
static int code_rlc(code_t *c, const char *name, int n, int r, uint64_t seed){
memset(c, 0, sizeof *c);
snprintf(c->name, sizeof c->name, "%s", name);
c->n = n; c->k = n - r; c->r = r; c->is_rlc = 1; c->g = 0;
uint64_t mask = (n >= 64) ? ~0ULL : ((1ULL << n) - 1);
for(int attempt = 0; attempt < 200; attempt++){
rng_seed(seed + (uint64_t)attempt * 0x100000001B3ULL);
for(int j = 0; j < r; j++) c->hrow[j] = rng_next() & mask;
/* rank check by elimination on rows */
uint64_t rows[64]; memcpy(rows, c->hrow, sizeof rows);
int rank = 0;
for(int col = n - 1; col >= 0 && rank < r; col--){
int piv = -1;
for(int i = rank; i < r; i++) if((rows[i] >> col) & 1ULL){ piv = i; break; }
if(piv < 0) continue;
uint64_t t = rows[rank]; rows[rank] = rows[piv]; rows[piv] = t;
for(int i = 0; i < r; i++)
if(i != rank && ((rows[i] >> col) & 1ULL)) rows[i] ^= rows[rank];
rank++;
}
if(rank == r) return 1;
}
return 0;
}
/* Exact d_min by Gray-code enumeration (k <= 24), cross-check vs Phase 1. */
static int dmin_exact(const code_t *c, uint64_t *admin){
int k = c->k;
uint64_t basis[64];
for(int i = 0; i < k; i++){
uint64_t m = 1ULL << i;
uint64_t cw = (m << c->r);
/* parity of unit message: syndrome of the data part */
uint64_t par = code_syn(c, cw ^ (m << c->r)); /* not used; compute directly */
(void)par;
/* codeword = data bits + parity bits: parity = syn of data-only error */
uint64_t e = m << c->r; /* error vector = data bits only */
uint64_t syn;
if(c->is_rlc){
/* parity bits p satisfy H.(m,p)=0; solve via syndrome: syn(e) = H.e
* gives the parity bits directly when H is in [A|I] form -- not
* guaranteed here, so build codeword via generator instead. */
syn = 0; (void)syn;
basis[i] = 0; /* RLC exact dmin not supported this way */
} else {
uint64_t p = 0;
/* parity = poly remainder of the message */
p = poly_mod(m << c->r, k + c->r, c->g, c->r);
basis[i] = (m << c->r) | p;
}
(void)e;
}
if(c->is_rlc) return -1;
uint64_t total = 1ULL << k, prev = 0, cw = 0, cnt = 0;
int best = c->n + 1;
for(uint64_t m = 1; m < total; m++){
uint64_t g = m ^ (m >> 1);
int bit = __builtin_ctzll(g ^ prev);
prev = g; cw ^= basis[bit];
int w = popcnt64(cw);
if(w < best){ best = w; cnt = 1; }
else if(w == best) cnt++;
}
if(admin) *admin = cnt;
return best;
}
/* ---------------- guess lists ---------------- */
typedef struct { uint64_t *pat, *syn; size_t n, cap; } glist_t;
static void glist_add(glist_t *L, const code_t *c, uint64_t p){
if(L->n == L->cap){
L->cap = L->cap ? L->cap * 2 : 1024;
L->pat = realloc(L->pat, L->cap * sizeof *L->pat);
L->syn = realloc(L->syn, L->cap * sizeof *L->syn);
if(!L->pat || !L->syn){ fprintf(stderr, "oom\n"); exit(1); }
}
L->pat[L->n] = p;
L->syn[L->n] = code_syn(c, p);
L->n++;
}
static void comb_rec(glist_t *L, const code_t *c, int n, int w, int start, int depth, uint64_t cur){
if(depth == w){ glist_add(L, c, cur); return; }
for(int i = start; i <= n - (w - depth); i++)
comb_rec(L, c, n, w, i + 1, depth + 1, cur | (1ULL << i));
}
/* GRAND list: all patterns of weight 0..W, weight order. */
static void glist_grand(glist_t *L, const code_t *c, int W){
memset(L, 0, sizeof *L);
for(int w = 0; w <= W; w++) comb_rec(L, c, c->n, w, 0, 0, 0);
}
/* Burst patterns of length 1..Lmax (first and last bit 1). */
static void glist_bursts(glist_t *L, const code_t *c, int Lmax){
int n = c->n;
for(int len = 1; len <= Lmax && len <= n; len++){
int nmid = len - 2;
uint64_t np = (len <= 2) ? 1 : (1ULL << nmid);
for(int s = 0; s + len <= n; s++){
for(uint64_t mid = 0; mid < np; mid++){
uint64_t e = (1ULL << s) | (1ULL << (s + len - 1));
for(int j = 0; j < nmid; j++)
if((mid >> j) & 1) e |= 1ULL << (s + 1 + j);
glist_add(L, c, e);
}
}
}
}
/* Viterbi log-likelihood of a noise pattern under the Gilbert model.
* States G/B; transitions a (G->B), b (B->G); emissions p0 (flip in G),
* q1 (flip in B); steady-state start f = P(B). */
typedef struct { double a, b, p0, q1, f; } gmodel_t;
static double pattern_ll(uint64_t pat, int n, const gmodel_t *m){
const double NEG = -1e100;
double lg0 = log(1.0 - m->f), lb0 = log(m->f);
double lgG = log(1.0 - m->a), lgB = log(m->a);
double lbG = log(m->b), lbB = log(1.0 - m->b);
double eG1 = log(m->p0), eG0 = log(1.0 - m->p0);
double eB1 = log(m->q1), eB0 = log(1.0 - m->q1);
double vG = lg0, vB = lb0;
for(int i = 0; i < n; i++){
int bit = (pat >> i) & 1ULL;
double nG = fmax(vG + lgG, vB + lbG) + (bit ? eG1 : eG0);
double nB = fmax(vG + lgB, vB + lbB) + (bit ? eB1 : eB0);
vG = nG; vB = nB;
}
double r = fmax(vG, vB);
return (r < NEG/2) ? NEG : r;
}
typedef struct { uint64_t pat, syn; double ll; } scored_t;
static int cmp_scored(const void *a, const void *b){
double x = ((const scored_t*)a)->ll, y = ((const scored_t*)b)->ll;
if(x != y) return (x < y) - (x > y); /* descending LL */
uint64_t pa = ((const scored_t*)a)->pat, pb = ((const scored_t*)b)->pat;
return (pa > pb) - (pa < pb);
}
/* GRAND-MO list: union of bursts (<=Lmax) and weight<=W patterns,
* scored by Markov LL, deduped, truncated to budget. */
static void glist_grandmo(glist_t *L, const code_t *c, int W, int Lmax,
const gmodel_t *m, size_t budget){
glist_t tmp; memset(&tmp, 0, sizeof tmp);
glist_bursts(&tmp, c, Lmax);
glist_t w; memset(&w, 0, sizeof w);
glist_grand(&w, c, W);
for(size_t i = 0; i < w.n; i++) glist_add(&tmp, c, w.pat[i]);
free(w.pat); free(w.syn);
scored_t *sc = malloc(tmp.n * sizeof *sc);
for(size_t i = 0; i < tmp.n; i++){
sc[i].pat = tmp.pat[i]; sc[i].syn = tmp.syn[i];
sc[i].ll = pattern_ll(tmp.pat[i], c->n, m);
}
free(tmp.pat); free(tmp.syn);
qsort(sc, tmp.n, sizeof *sc, cmp_scored);
memset(L, 0, sizeof *L);
for(size_t i = 0; i < tmp.n && L->n < budget; i++){
if(L->n > 0 && sc[i].pat == L->pat[L->n - 1]) continue; /* dedupe */
if(L->n == L->cap){
L->cap = L->cap ? L->cap * 2 : 1024;
L->pat = realloc(L->pat, L->cap * sizeof *L->pat);
L->syn = realloc(L->syn, L->cap * sizeof *L->syn);
}
L->pat[L->n] = sc[i].pat; L->syn[L->n] = sc[i].syn; L->n++;
}
free(sc);
}
/* Decode by guess-list scan: success iff first guess with syndrome
* syn(e) equals e. Returns scan index, or -1 if not found (exhausted). */
static long grand_scan(const glist_t *L, const code_t *c, uint64_t e){
uint64_t s = code_syn(c, e);
for(size_t i = 0; i < L->n; i++)
if(L->syn[i] == s) return (L->pat[i] == e) ? (long)i : -2L;
return -1;
}
/* ---------------- damage channels ---------------- */
typedef struct { int kind; double p; gmodel_t gm; } chan_t; /* kind 0 scat, 1 gilbert */
static uint64_t chan_draw(const chan_t *ch, int n){
uint64_t e = 0;
if(ch->kind == 0){
for(int i = 0; i < n; i++)
if(rng_uniform() < ch->p) e |= 1ULL << i;
return e;
}
int state = (rng_uniform() < ch->gm.f) ? 1 : 0;
for(int i = 0; i < n; i++){
double fp = state ? ch->gm.q1 : ch->gm.p0;
if(rng_uniform() < fp) e |= 1ULL << i;
double u = rng_uniform();
state = state ? ((u < ch->gm.b) ? 0 : 1) : ((u < ch->gm.a) ? 1 : 0);
}
return e;
}
/* Gilbert params from (mean burst L, overall BER, background p0, q1). */
static chan_t chan_burst(double L, double ber, double p0, double q1){
chan_t ch; ch.kind = 1;
double f = (ber - p0) / (q1 - p0);
double b = 1.0 / L;
ch.gm.b = b; ch.gm.a = f * b / (1.0 - f);
ch.gm.p0 = p0; ch.gm.q1 = q1; ch.gm.f = f;
ch.p = ber;
return ch;
}
/* ---------------- BM baseline via real lzply bch.c ---------------- */
/* p2 bit i <-> bch.c stored bit (n-1-i); stored bit s = byte s/8, bit 7-(s%8). */
static void msg_to_data(uint64_t msg, int k, int D, uint8_t *data){
memset(data, 0, D);
for(int j = 0; j < k; j++){
if((msg >> j) & 1ULL){
int s = k - 1 - j;
data[s / 8] |= (uint8_t)(1u << (7 - (s % 8)));
}
}
}
/* One BM trial: encode msg (D bytes), flip bits per p2 error mask e
* (n bits), decode with real bch_decode_block. Returns 1 repaired,
* 0 uncorrectable, -1 miscorrected (decode "succeeded" wrong). */
static int bm_trial(uint64_t msg, uint64_t e, const bch_poly_t *poly, int D, int n){
uint8_t data[64], enc[128], cor[128], dec[64];
msg_to_data(msg, 8 * D, D, data);
size_t slen = bch_block_stored_len(D, poly);
if(bch_encode_block(data, D, poly, enc) != 0) return 0;
memcpy(cor, enc, slen);
for(int i = 0; i < n; i++){
if((e >> i) & 1ULL){
int s = n - 1 - i;
cor[s / 8] ^= (uint8_t)(1u << (7 - (s % 8)));
}
}
int corr = 0;
int rc = bch_decode_block(cor, slen, D, poly, dec, &corr);
if(rc != 0) return 0;
return (memcmp(dec, data, D) == 0) ? 1 : -1;
}
/* ---------------- schemes ---------------- */
typedef struct {
char name[48];
code_t code; /* syndrome code for guess-list schemes */
int has_code;
glist_t gl; /* guess list (grand / grandmo) */
int is_bm;
const bch_poly_t *poly; int D; int n; /* BM params */
long repaired, miscorr, exhausted;
double scan_sum;
long scan_trials;
} scheme_t;
static void scheme_grand(scheme_t *s, const char *name, const code_t *c, int W){
memset(s, 0, sizeof *s);
snprintf(s->name, sizeof s->name, "%s", name);
s->code = *c; s->has_code = 1; s->is_bm = 0;
glist_grand(&s->gl, c, W);
}
static void scheme_grandmo(scheme_t *s, const char *name, const code_t *c,
int W, int Lmax, const gmodel_t *m, size_t budget){
memset(s, 0, sizeof *s);
snprintf(s->name, sizeof s->name, "%s", name);
s->code = *c; s->has_code = 1; s->is_bm = 0;
glist_grandmo(&s->gl, c, W, Lmax, m, budget);
}
static void scheme_bm(scheme_t *s, const char *name, uint16_t poly_id, int D, int n){
memset(s, 0, sizeof *s);
snprintf(s->name, sizeof s->name, "%s", name);
s->is_bm = 1; s->poly = bch_poly_by_id(poly_id); s->D = D; s->n = n;
if(!s->poly){ fprintf(stderr, "no bch poly id 0x%04x\n", poly_id); exit(1); }
}
/* One trial of one scheme on (msg, e). e is drawn over max_n bits;
* each scheme masks to its own n. */
static void scheme_trial(scheme_t *s, uint64_t msg, uint64_t e){
if(s->is_bm){
uint64_t mask = (s->n >= 64) ? ~0ULL : ((1ULL << s->n) - 1);
int r = bm_trial(msg, e & mask, s->poly, s->D, s->n);
if(r == 1) s->repaired++;
else if(r == -1) s->miscorr++;
return;
}
uint64_t mask = (s->code.n >= 64) ? ~0ULL : ((1ULL << s->code.n) - 1);
uint64_t ee = e & mask;
long sc = grand_scan(&s->gl, &s->code, ee);
if(sc >= 0){ s->repaired++; s->scan_sum += sc; s->scan_trials++; }
else if(sc == -1) s->exhausted++;
else s->miscorr++; /* a lighter pattern shares the syndrome: ML miscorrects */
}
static void scheme_report(const char *group, const char *model, scheme_t *s, long trials, double secs){
printf("CELL group=%s model=%s scheme=%-16s n=%d k=%d r=%d trials=%ld repaired=%ld rate=%.4f miscorr=%ld exhausted=%ld mean_scan=%.0f list=%zu secs=%.1f\n",
group, model, s->name,
s->is_bm ? s->n : s->code.n,
s->is_bm ? 8 * s->D : s->code.k,
s->is_bm ? (s->n - 8 * s->D) : s->code.r,
trials, s->repaired, (double)s->repaired / trials,
s->miscorr, s->exhausted,
s->scan_trials ? s->scan_sum / s->scan_trials : -1.0,
s->gl.n, secs);
fflush(stdout);
}
/* ---------------- models ---------------- */
typedef struct { char name[32]; chan_t ch; } model_t;
static int all_models(model_t *m){
int i = 0;
snprintf(m[i].name, sizeof m[i].name, "scat-p0.01"); m[i].ch.kind = 0; m[i].ch.p = 0.01; i++;
snprintf(m[i].name, sizeof m[i].name, "scat-p0.03"); m[i].ch.kind = 0; m[i].ch.p = 0.03; i++;
snprintf(m[i].name, sizeof m[i].name, "burst-L8-BER0.01"); m[i].ch = chan_burst(8, 0.01, 0.0, 0.95); i++;
snprintf(m[i].name, sizeof m[i].name, "burst-L32-BER0.01"); m[i].ch = chan_burst(32, 0.01, 0.0, 0.95); i++;
snprintf(m[i].name, sizeof m[i].name, "burst-L8-BER0.03"); m[i].ch = chan_burst(8, 0.03, 0.0, 0.95); i++;
snprintf(m[i].name, sizeof m[i].name, "mix-L16-BER0.01"); m[i].ch = chan_burst(16, 0.01, 0.002, 0.95); i++;
return i;
}
/* GRAND-MO model for list ordering: use the burst model itself when the
* channel is bursty, else the L8 burst model as a generic burst prior. */
static gmodel_t list_model_for(const chan_t *ch){
if(ch->kind == 1) return ch->gm;
chan_t b = chan_burst(8, 0.01, 0.0, 0.95);
return b.gm;
}
/* Run one group x one model. schemes[] built by caller for this model
* (GRAND-MO lists depend on the model). trials drawn with seed. */
static void run_group_model(const char *group, const model_t *mo,
scheme_t *sch, int nsch, int max_n,
int kmax, long trials, uint64_t seed){
for(int i = 0; i < nsch; i++){
sch[i].repaired = sch[i].miscorr = sch[i].exhausted = 0;
sch[i].scan_sum = 0; sch[i].scan_trials = 0;
}
uint64_t kmask = (kmax >= 64) ? ~0ULL : ((1ULL << kmax) - 1);
rng_seed(seed);
clock_t t0 = clock();
for(long t = 0; t < trials; t++){
uint64_t msg = rng_next() & kmask;
uint64_t e = chan_draw(&mo->ch, max_n);
for(int i = 0; i < nsch; i++) scheme_trial(&sch[i], msg, e);
}
clock_t t1 = clock();
double secs = (double)(t1 - t0) / CLOCKS_PER_SEC;
for(int i = 0; i < nsch; i++) scheme_report(group, mo->name, &sch[i], trials, secs);
}
/* ---------------- blob mode: 384 data bits, 384 parity bits ----------------
* A: one BCH block D=48 t=32 (m=12, r=384, n=768) + BM.
* B: 24 x CRC(32,16,16) 0x109b1 + GRAND-MO per block.
* C: 24 x RLC(32,16) + GRAND-MO per block.
* D: 24 x BCH m8t2 (32,16,16) + BM per block.
* Damage drawn over the 768-bit stored stream; blob repaired iff every
* block repaired (A: the single block). */
static void run_blob(const model_t *mo, long trials, uint64_t seed){
const bch_poly_t *big = bch_poly_for_data(48, 32);
if(!big){ fprintf(stderr, "no big poly\n"); exit(1); }
printf("# blob: big poly id=0x%04x m=%d t=%d r=%d n=%d\n",
big->id, big->m, big->t, big->r, 8 * 48 + big->r);
code_t crc; code_cyclic(&crc, "crc-0x109b1", 0x109b1ULL, 16, 32);
code_t rlc; if(!code_rlc(&rlc, "rlc32", 32, 16, 0xC0FFEEULL)){ fprintf(stderr, "rlc fail\n"); exit(1); }
code_t bch; code_cyclic(&bch, "bch-m8t2", 0x1cbe3ULL, 16, 32);
gmodel_t lm = list_model_for(&mo->ch);
scheme_t sb, sr, sd;
scheme_grandmo(&sb, "crc-blocks-grandmo", &crc, 4, 12, &lm, 1000000);
scheme_grandmo(&sr, "rlc-blocks-grandmo", &rlc, 4, 12, &lm, 1000000);
scheme_bm(&sd, "bch-blocks-bm", 0x0004, 2, 32);
/* per-block error slices come from the 640-bit stream; simulate the
* stream as 10 uint64 words. */
long repA = 0, misA = 0, repB = 0, misB = 0, repC = 0, misC = 0, repD = 0, misD = 0;
long exB = 0, exC = 0;
double scanB = 0, scanC = 0; long nscanB = 0, nscanC = 0;
rng_seed(seed);
clock_t t0 = clock();
for(long t = 0; t < trials; t++){
/* random 48-byte message */
uint8_t data[48];
for(int i = 0; i < 48; i += 8){ uint64_t v = rng_next(); memcpy(data + i, &v, 8); }
/* error stream: draw 640 bits through the channel state machine.
* chan_draw works on <=64-bit words; draw per 64-bit word, carrying
* the Gilbert state across words via a fresh draw per word is wrong
* for bursts spanning words -- so draw bit by bit here. */
uint64_t ew[12] = {0};
if(mo->ch.kind == 0){
for(int w = 0; w < 12; w++)
for(int i = 0; i < 64; i++)
if(rng_uniform() < mo->ch.p) ew[w] |= 1ULL << i;
} else {
int state = (rng_uniform() < mo->ch.gm.f) ? 1 : 0;
for(int w = 0; w < 12; w++)
for(int i = 0; i < 64; i++){
double fp = state ? mo->ch.gm.q1 : mo->ch.gm.p0;
if(rng_uniform() < fp) ew[w] |= 1ULL << i;
double u = rng_uniform();
state = state ? ((u < mo->ch.gm.b) ? 0 : 1) : ((u < mo->ch.gm.a) ? 1 : 0);
}
}
/* A: one big BCH block over the 640-bit stream. p2 stream bit i
* (i=0..639) <-> stored bit (639-i). Build the 640-bit error mask
* in p2 order, then map into bytes for bm_trial via n=640. */
uint8_t enc[128], cor[128], dec[64];
size_t slen = bch_block_stored_len(48, big);
if(bch_encode_block(data, 48, big, enc) != 0){ fprintf(stderr, "blob enc fail\n"); exit(1); }
memcpy(cor, enc, slen);
for(int w = 0; w < 12; w++)
for(int i = 0; i < 64; i++){
if((ew[w] >> i) & 1ULL){
int p2 = w * 64 + i; /* p2 stream position */
int s = 767 - p2; /* stored bit */
cor[s / 8] ^= (uint8_t)(1u << (7 - (s % 8)));
}
}
int rc = bch_decode_block(cor, slen, 48, big, dec, NULL);
if(rc == 0 && memcmp(dec, data, 48) == 0) repA++;
else if(rc == 0) misA++;
/* B/C/D: 20 blocks of 32 stored bits. Block j covers stream
* bits [32j, 32j+32) in p2 order; block-local bit i = stream
* bit 32j+i. */
int okB = 1, okC = 1, okD = 1;
for(int j = 0; j < 24 && (okB || okC || okD); j++){
uint64_t eb = 0;
for(int i = 0; i < 32; i++){
int p2 = 32 * j + i;
if((ew[p2 / 64] >> (p2 % 64)) & 1ULL) eb |= 1ULL << i;
}
uint64_t msg = 0;
for(int b = 0; b < 16; b++){ /* data bits of block j, from data[] */
int bit = 16 * j + b; /* p2 data-bit index across the blob */
if((data[bit / 8] >> (7 - (bit % 8))) & 1u) msg |= 1ULL << b;
}
if(okB){
long scr = grand_scan(&sb.gl, &sb.code, eb);
if(scr >= 0){ scanB += scr; nscanB++; }
else if(scr == -1){ exB++; okB = 0; }
else { misB++; okB = 0; }
}
if(okC){
long scr = grand_scan(&sr.gl, &sr.code, eb);
if(scr >= 0){ scanC += scr; nscanC++; }
else if(scr == -1){ exC++; okC = 0; }
else { misC++; okC = 0; }
}
if(okD){
int r = bm_trial(msg, eb, bch_poly_by_id(0x0004), 2, 32);
if(r != 1){ if(r == -1) misD++; okD = 0; }
}
}
if(okB) repB++;
if(okC) repC++;
if(okD) repD++;
}
clock_t t1 = clock();
double secs = (double)(t1 - t0) / CLOCKS_PER_SEC;
printf("CELL group=blob model=%s scheme=%-16s n=768 k=384 r=384 trials=%ld repaired=%ld rate=%.4f miscorr=%ld exhausted=0 mean_scan=-1 list=0 secs=%.1f\n",
mo->name, "bch-big-bm", trials, repA, (double)repA / trials, misA, secs);
printf("CELL group=blob model=%s scheme=%-16s n=768 k=384 r=384 trials=%ld repaired=%ld rate=%.4f miscorr=%ld exhausted=%ld mean_scan=%.0f list=%zu secs=%.1f\n",
mo->name, "crc-blocks-grandmo", trials, repB, (double)repB / trials, misB, exB,
nscanB ? scanB / nscanB : -1.0, sb.gl.n, secs);
printf("CELL group=blob model=%s scheme=%-16s n=768 k=384 r=384 trials=%ld repaired=%ld rate=%.4f miscorr=%ld exhausted=%ld mean_scan=%.0f list=%zu secs=%.1f\n",
mo->name, "rlc-blocks-grandmo", trials, repC, (double)repC / trials, misC, exC,
nscanC ? scanC / nscanC : -1.0, sr.gl.n, secs);
printf("CELL group=blob model=%s scheme=%-16s n=768 k=384 r=384 trials=%ld repaired=%ld rate=%.4f miscorr=%ld exhausted=0 mean_scan=-1 list=0 secs=%.1f\n",
mo->name, "bch-blocks-bm", trials, repD, (double)repD / trials, misD, secs);
fflush(stdout);
free(sb.gl.pat); free(sb.gl.syn);
free(sr.gl.pat); free(sr.gl.syn);
}
/* ---------------- selftest ---------------- */
static int fails = 0;
#define CHECK(cond, ...) do{ if(!(cond)){ printf("SELFTEST FAIL " __VA_ARGS__); printf("\n"); fails++; } }while(0)
static int cmd_selftest(void){
/* 1. GRAND == brute-force nearest codeword on Hamming(7,4). */
code_t ham; code_cyclic(&ham, "hamming74", 0xbULL, 3, 7);
glist_t gl; glist_grand(&gl, &ham, 3);
/* all 16 codewords by brute force */
uint64_t cw[16];
for(int m = 0; m < 16; m++){
uint64_t par = poly_mod((uint64_t)m << 3, 4 + 3, 0xbULL, 3);
cw[m] = ((uint64_t)m << 3) | par;
}
for(uint64_t y = 0; y < 128; y++){
int bestd = 99, bestm = -1, nbest = 0;
for(int m = 0; m < 16; m++){
int d = popcnt64(y ^ cw[m]);
if(d < bestd){ bestd = d; bestm = m; nbest = 1; }
else if(d == bestd) nbest++;
}
/* GRAND decode of y: find first guess g with syn(y^g)==0, i.e.
* syn(g)==syn(y); decoded word = y^g. */
uint64_t s = code_syn(&ham, y);
uint64_t dec = y; int found = 0;
for(size_t i = 0; i < gl.n; i++){
if(gl.syn[i] == s){ dec = y ^ gl.pat[i]; found = 1; break; }
}
if(nbest == 1){
CHECK(found && dec == cw[bestm], "hamming74 y=0x%llx grand!=brute", (unsigned long long)y);
}
}
printf("SELFTEST ok GRAND == brute-force ML on Hamming(7,4) (128 words)\n");
free(gl.pat); free(gl.syn);
/* 2. d_min cross-check vs Phase 1 (exact Gray enumeration). */
code_t c1; code_cyclic(&c1, "crc-0x109b1", 0x109b1ULL, 16, 32);
uint64_t ad; int d = dmin_exact(&c1, &ad);
CHECK(d == 7, "0x109b1 dmin=%d want 7", d);
printf("SELFTEST ok 0x109b1 dmin=7 (admin=%llu)\n", (unsigned long long)ad);
code_t c2; code_cyclic(&c2, "crc-0x1343", 0x1343ULL, 12, 24);
d = dmin_exact(&c2, &ad);
CHECK(d == 6, "0x1343 dmin=%d want 6", d);
printf("SELFTEST ok 0x1343 dmin=6\n");
code_t c3; code_cyclic(&c3, "crc-0x14669", 0x14669ULL, 16, 64);
/* k=48: Gray enumeration infeasible; verify via syndrome certify t=2
* using the guess-list machinery: all weight<=2 syndromes distinct. */
glist_t w2; glist_grand(&w2, &c3, 2);
int ok = 1;
for(size_t i = 1; i < w2.n && ok; i++){ /* skip i=0: the zero pattern */
if(w2.syn[i] == 0) ok = 0;
for(size_t j = i + 1; j < w2.n; j++)
if(w2.syn[i] == w2.syn[j]){ ok = 0; break; }
}
CHECK(ok, "0x14669 weight<=2 syndrome collision (dmin<5)");
printf("SELFTEST ok 0x14669 dmin>=5 by syndrome certification\n");
free(w2.pat); free(w2.syn);
/* 3. BM mapping: p2 bits -> bch.c stored bytes, round trip + 1-bit fix. */
const bch_poly_t *poly = bch_poly_by_id(0x0004); /* m8t2 */
rng_seed(42);
for(int trial = 0; trial < 200; trial++){
uint64_t msg = rng_next() & 0xFFFF;
int r = bm_trial(msg, 0, poly, 2, 32);
CHECK(r == 1, "bm clean trial %d rc=%d", trial, r);
uint64_t e = 1ULL << (rng_next() % 32);
r = bm_trial(msg, e, poly, 2, 32);
CHECK(r == 1, "bm 1-bit trial %d rc=%d", trial, r);
}
printf("SELFTEST ok BM mapping round-trip + 1-bit correction (200 trials)\n");
/* 4. GRAND-MO list contains every burst of length <= 6 (count check). */
code_t c4; code_cyclic(&c4, "crc32", 0x109b1ULL, 16, 32);
chan_t b = chan_burst(8, 0.01, 0.0, 0.95);
glist_t gm; glist_grandmo(&gm, &c4, 4, 12, &b.gm, 1000000);
size_t nb = 0;
for(size_t i = 0; i < gm.n; i++){
uint64_t p = gm.pat[i];
if(!p) continue; /* zero pattern: span undefined */
int lo = __builtin_ctzll(p), hi = 63 - __builtin_clzll(p);
if(hi - lo + 1 <= 6) nb++;
}
size_t want = 0;
for(int L = 1; L <= 6; L++) want += (size_t)(32 - L + 1) * (L <= 2 ? 1 : (1u << (L - 2)));
CHECK(nb == want, "grandmo burst<=6 count %zu want %zu", nb, want);
printf("SELFTEST ok GRAND-MO list holds all %zu bursts of length <= 6\n", want);
free(gm.pat); free(gm.syn);
/* 5. RLC rank + syndrome linearity. */
code_t rl; CHECK(code_rlc(&rl, "rlc", 32, 16, 0x1234), "rlc build");
rng_seed(7);
for(int t = 0; t < 100; t++){
uint64_t e1 = rng_next() & 0xFFFFFFFFULL, e2 = rng_next() & 0xFFFFFFFFULL;
CHECK(code_syn(&rl, e1 ^ e2) == (code_syn(&rl, e1) ^ code_syn(&rl, e2)),
"rlc syndrome linearity");
}
printf("SELFTEST ok RLC rank + syndrome linearity\n");
printf(fails ? "SELFTEST %d FAILURES\n" : "SELFTEST ALL PASS (0 failures)\n", fails);
return fails ? 1 : 0;
}
/* ---------------- matrix driver ---------------- */
static void build_group(const char *group, const model_t *mo, scheme_t *sch, int *nsch, int *max_n, int *kmax){
gmodel_t lm = list_model_for(&mo->ch);
*nsch = 0;
if(!strcmp(group, "g1")){
code_t bch, crc, rlc;
code_cyclic(&bch, "bch-m8t1", 0x12bULL, 8, 24);
code_cyclic(&crc, "crc-0x1f9", 0x1f9ULL, 8, 24);
if(!code_rlc(&rlc, "rlc24", 24, 8, 0xBEEFULL)){ fprintf(stderr, "rlc fail\n"); exit(1); }
scheme_bm(&sch[(*nsch)++], "bch-m8t1-bm", 0x0003, 2, 24);
scheme_grand(&sch[(*nsch)++], "bch-m8t1-grand", &bch, 4);
scheme_grand(&sch[(*nsch)++], "crc-0x1f9-grand", &crc, 4);
scheme_grandmo(&sch[(*nsch)++], "crc-0x1f9-grandmo", &crc, 4, 12, &lm, 1000000);
scheme_grandmo(&sch[(*nsch)++], "rlc-grandmo", &rlc, 4, 12, &lm, 1000000);
*max_n = 24; *kmax = 16;
} else if(!strcmp(group, "g2")){
code_t bch, crc, rlc, ebch;
code_cyclic(&bch, "bch-m8t2", 0x1cbe3ULL, 16, 32);
code_cyclic(&crc, "crc-0x109b1", 0x109b1ULL, 16, 32);
if(!code_rlc(&rlc, "rlc32", 32, 16, 0xC0FFEEULL)){ fprintf(stderr, "rlc fail\n"); exit(1); }
uint64_t ge = 0x1cbe3ULL ^ (0x1cbe3ULL << 1); /* g(x)*(x+1) */
code_cyclic(&ebch, "ebch-m8t2", ge, 17, 33);
scheme_bm(&sch[(*nsch)++], "bch-m8t2-bm", 0x0004, 2, 32);
scheme_grand(&sch[(*nsch)++], "bch-m8t2-grand", &bch, 4);
scheme_grand(&sch[(*nsch)++], "crc-0x109b1-grand", &crc, 4);
scheme_grandmo(&sch[(*nsch)++], "crc-0x109b1-grandmo", &crc, 4, 12, &lm, 1000000);
scheme_grandmo(&sch[(*nsch)++], "rlc-grandmo", &rlc, 4, 12, &lm, 1000000);
scheme_grand(&sch[(*nsch)++], "ebch-m8t2-grand", &ebch, 4);
*max_n = 33; *kmax = 16;
} else if(!strcmp(group, "g3")){
code_t bch;
code_cyclic(&bch, "bch-m7t2", 0x68edULL, 14, 30);
scheme_bm(&sch[(*nsch)++], "bch-m7t2-bm", 0x0002, 2, 30);
scheme_grand(&sch[(*nsch)++], "bch-m7t2-grand", &bch, 4);
*max_n = 30; *kmax = 16;
} else if(!strcmp(group, "g4")){
code_t bch, crc, rlc;
code_cyclic(&bch, "bch-m8t2", 0x1cbe3ULL, 16, 64);
code_cyclic(&crc, "crc-0x14669", 0x14669ULL, 16, 64);
if(!code_rlc(&rlc, "rlc64", 64, 16, 0xDEADBEEFULL)){ fprintf(stderr, "rlc fail\n"); exit(1); }
scheme_bm(&sch[(*nsch)++], "bch-m8t2-bm", 0x0004, 6, 64);
scheme_grand(&sch[(*nsch)++], "bch-m8t2-grand", &bch, 4);
scheme_grand(&sch[(*nsch)++], "crc-0x14669-grand", &crc, 4);
scheme_grandmo(&sch[(*nsch)++], "crc-0x14669-grandmo", &crc, 4, 12, &lm, 1000000);
scheme_grandmo(&sch[(*nsch)++], "rlc-grandmo", &rlc, 4, 12, &lm, 1000000);
*max_n = 64; *kmax = 48;
} else if(!strcmp(group, "g5")){
code_t crc, rlc;
code_cyclic(&crc, "crc-0x1343", 0x1343ULL, 12, 24);
if(!code_rlc(&rlc, "rlc24", 24, 12, 0xF00DULL)){ fprintf(stderr, "rlc fail\n"); exit(1); }
scheme_grand(&sch[(*nsch)++], "crc-0x1343-grand", &crc, 4);
scheme_grandmo(&sch[(*nsch)++], "crc-0x1343-grandmo", &crc, 4, 12, &lm, 1000000);
scheme_grandmo(&sch[(*nsch)++], "rlc-grandmo", &rlc, 4, 12, &lm, 1000000);
*max_n = 24; *kmax = 12;
} else { fprintf(stderr, "unknown group %s\n", group); exit(1); }
}
static int cmd_matrix(int argc, char **argv){
/* usage: matrix [group] [model] [trials] -- group=model=all runs all */
const char *groups[] = {"g1", "g2", "g3", "g4", "g5", "blob"};
long trials = 10000;
const char *want_g = (argc > 0) ? argv[0] : "all";
const char *want_m = (argc > 1) ? argv[1] : "all";
if(argc > 2) trials = atol(argv[2]);
model_t models[8]; int nmod = all_models(models);
printf("# p2 matrix: guess budget 1M, GRAND W=4, GRAND-MO bursts<=12 + W<=4\n");
printf("# trials=%ld per group-model; same (msg,error) stream per scheme\n", trials);
for(int gi = 0; gi < 6; gi++){
if(strcmp(want_g, "all") && strcmp(want_g, groups[gi])) continue;
for(int mi = 0; mi < nmod; mi++){
if(strcmp(want_m, "all") && strcmp(want_m, models[mi].name)) continue;
uint64_t seed = 0x12345ULL + (uint64_t)gi * 1000 + (uint64_t)mi * 17;
if(!strcmp(groups[gi], "blob")){
run_blob(&models[mi], trials / 2, seed);
continue;
}
scheme_t sch[8]; int nsch, max_n, kmax;
build_group(groups[gi], &models[mi], sch, &nsch, &max_n, &kmax);
run_group_model(groups[gi], &models[mi], sch, nsch, max_n, kmax, trials, seed);
for(int i = 0; i < nsch; i++){ free(sch[i].gl.pat); free(sch[i].gl.syn); }
}
}
return 0;
}
static int cmd_dmin(int argc, char **argv){
/* dmin g=0x109b1 r=16 n=32 */
uint64_t g = 0; int r = 0, n = 0;
for(int i = 0; i < argc; i++){
if(!strncmp(argv[i], "g=", 2)) g = strtoull(argv[i] + 2, NULL, 0);
if(!strncmp(argv[i], "r=", 2)) r = atoi(argv[i] + 2);
if(!strncmp(argv[i], "n=", 2)) n = atoi(argv[i] + 2);
}
if(!g || !r || !n || n - r > 24){ fprintf(stderr, "usage: dmin g=0x.. r=.. n=.. (k<=24)\n"); return 1; }
code_t c; code_cyclic(&c, "cmd", g, r, n);
uint64_t ad; int d = dmin_exact(&c, &ad);
printf("DMIN g=0x%llx r=%d n=%d k=%d dmin=%d admin=%llu\n",
(unsigned long long)g, r, n, n - r, d, (unsigned long long)ad);
return 0;
}
int main(int argc, char **argv){
if(argc < 2){
fprintf(stderr, "usage: p2 selftest | dmin g=.. r=.. n=.. | matrix [group] [model] [trials]\n");
return 1;
}
if(!strcmp(argv[1], "selftest")) return cmd_selftest();
if(!strcmp(argv[1], "dmin")) return cmd_dmin(argc - 2, argv + 2);
if(!strcmp(argv[1], "matrix")) return cmd_matrix(argc - 2, argv + 2);
fprintf(stderr, "unknown subcommand %s\n", argv[1]);
return 1;
}
-1018
View File
File diff suppressed because it is too large. Load diff
-214
View File
@@ -1,214 +0,0 @@
// rq_bench.cc — M2.2 RaptorQ validation bench (foxsen/raptorq, RFC 6330).
//
// Modes:
// roundtrip K T encode + decode with no loss, verify bytes.
// overhead K T R trials seed [datafile]
// send K+R symbols; receive exactly K+r for
// r in {0,1,2,3,5} (random subset), count real
// decode success (decode()==true AND every
// lost source symbol recovers byte-identical).
// timing K T R trials seed
// encode once + decode timing (lost = R/2 syms).
//
// Source data: splitmix64 PRNG bytes (seeded), or the first K*T bytes of
// datafile when given (roundtrip/overhead). Encoding is done ONCE per run;
// only the received subset varies per trial, so the decode-success curve
// is a pure function of the erasure pattern (as in p2/p3 discipline the
// same trace is what all schemes would see).
//
// Build (on hot_house):
// g++ -O2 -std=c++11 -I/root/raptorq/foxsen rq_bench.cc \
// /root/raptorq/foxsen/{Encoder,Decoder,Generators,Helper,StdAfx,Symbol}.cpp \
// -o rq_bench
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cstdint>
#include <string>
#include <vector>
#include <algorithm>
#include <chrono>
#include "Encoder.h"
#include "Decoder.h"
#include "Symbol.h"
static uint64_t sm_state;
static uint64_t sm_next() {
uint64_t z = (sm_state += 0x9e3779b97f4a7c15ULL);
z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ULL;
z = (z ^ (z >> 27)) * 0x94d049bb133111ebULL;
return z ^ (z >> 31);
}
static void fill_rand(char *p, size_t n) {
while (n >= 8) { uint64_t v = sm_next(); memcpy(p, &v, 8); p += 8; n -= 8; }
if (n) { uint64_t v = sm_next(); memcpy(p, &v, n); }
}
// random subset of size n from [0,total): Fisher-Yates prefix.
static std::vector<int> rand_subset(int total, int n) {
std::vector<int> idx(total);
for (int i = 0; i < total; i++) idx[i] = i;
for (int i = 0; i < n; i++) {
int j = i + (int)(sm_next() % (uint64_t)(total - i));
std::swap(idx[i], idx[j]);
}
idx.resize(n);
return idx;
}
// Decode the given received set; verify every lost source symbol.
// Returns 1 on full byte-identical recovery, 0 otherwise.
// lost[] lists source ESIs not received (may be empty -> trivially 1).
static int try_decode(int K, int T, char **src,
const std::vector<int> &recv_esi,
char **recv_data, Symbol **repairs,
const std::vector<int> &lost) {
int n = (int)recv_esi.size();
if (n < K) return 0;
int *esi = new int[n];
for (int i = 0; i < n; i++) esi[i] = recv_esi[i];
Decoder *dec = new Decoder();
if (!dec->init(K, T)) { delete dec; delete[] esi; return 0; }
bool ok = dec->decode(recv_data, n, esi);
int good = 0;
if (ok) {
good = 1;
for (int x : lost) {
Symbol *s = dec->recover(x);
if (!s || memcmp(s->data, src[x], (size_t)T) != 0) { good = 0; if (s) delete s; break; }
delete s;
}
}
delete dec;
delete[] esi;
(void)repairs;
return good;
}
int main(int argc, char **argv) {
if (argc < 2) {
fprintf(stderr, "usage: rq_bench roundtrip K T | overhead K T R trials seed [datafile] | timing K T R trials seed\n");
return 2;
}
std::string mode = argv[1];
int K = argc > 2 ? atoi(argv[2]) : 0;
int T = argc > 3 ? atoi(argv[3]) : 0;
if (K < 1 || T < 1 || (T % 4) != 0) { fprintf(stderr, "bad K/T (T must be %%4==0)\n"); return 2; }
// ---- source data ----
char **src = new char*[K];
for (int i = 0; i < K; i++) { src[i] = new char[T]; }
sm_state = 0x123456789abcdefULL;
const char *datafile = nullptr;
if (mode == "overhead" && argc > 8) datafile = argv[8];
if (datafile) {
FILE *f = fopen(datafile, "rb");
if (!f) { fprintf(stderr, "cannot open %s\n", datafile); return 2; }
size_t need = (size_t)K * (size_t)T, got = 0;
for (int i = 0; i < K && got < need; i++) {
size_t r = fread(src[i], 1, (size_t)T, f);
got += r;
if (r < (size_t)T) { // pad short file deterministically
fill_rand(src[i] + r, (size_t)T - r);
}
}
fclose(f);
fprintf(stderr, "# source: %s (%zu bytes used)\n", datafile, got);
} else {
for (int i = 0; i < K; i++) fill_rand(src[i], (size_t)T);
}
// ---- encode once ----
auto t0 = std::chrono::steady_clock::now();
int R = 10;
if (mode == "overhead") R = atoi(argv[4]);
if (mode == "timing") R = atoi(argv[4]);
Encoder *enc = new Encoder();
if (!enc->init(K, T)) { fprintf(stderr, "encoder init failed K=%d T=%d\n", K, T); return 1; }
Symbol **repairs = enc->encode(src, R);
auto t1 = std::chrono::steady_clock::now();
if (!repairs) { fprintf(stderr, "encode failed\n"); return 1; }
double enc_s = std::chrono::duration<double>(t1 - t0).count();
printf("# encode K=%d T=%d R=%d: %.3f s (%.2f MB/s)\n", K, T, R,
enc_s, (double)K * T / enc_s / 1e6);
if (mode == "roundtrip") {
// receive all K source symbols: trivial path (no decode needed),
// plus a decode with exactly K symbols incl. 1 repair, 1 source lost.
std::vector<int> esi; std::vector<char*> data;
for (int i = 1; i < K; i++) { esi.push_back(i); data.push_back(src[i]); }
esi.push_back(K); data.push_back((char*)repairs[0]->data);
std::vector<int> lost; lost.push_back(0);
int ok = try_decode(K, T, src, esi, data.data(), repairs, lost);
printf("roundtrip lost-src0+repair0: %s\n", ok ? "PASS" : "FAIL");
// full loss of all source, K repairs? only R available; use R=K? skip.
// verify repair symbols are deterministic: re-encode and compare.
Encoder *enc2 = new Encoder();
enc2->init(K, T);
Symbol **rep2 = enc2->encode(src, R);
int det = 1;
for (int i = 0; i < R && det; i++)
if (memcmp(rep2[i]->data, repairs[i]->data, (size_t)T) != 0) det = 0;
printf("roundtrip encode-deterministic: %s\n", det ? "PASS" : "FAIL");
return (ok && det) ? 0 : 1;
}
if (mode == "timing") {
int trials = atoi(argv[5]);
uint64_t seed = strtoull(argv[6], nullptr, 10);
sm_state = seed;
int lost_n = R / 2;
double dec_s = 0; int okc = 0;
for (int tr = 0; tr < trials; tr++) {
// lose lost_n source symbols, receive rest + all repairs
std::vector<int> lost = rand_subset(K, lost_n);
std::vector<char> islost(K, 0);
for (int x : lost) islost[x] = 1;
std::vector<int> esi; std::vector<char*> data;
for (int i = 0; i < K; i++) if (!islost[i]) { esi.push_back(i); data.push_back(src[i]); }
for (int i = 0; i < R; i++) { esi.push_back(K + i); data.push_back((char*)repairs[i]->data); }
auto a = std::chrono::steady_clock::now();
okc += try_decode(K, T, src, esi, data.data(), repairs, lost);
auto b = std::chrono::steady_clock::now();
dec_s += std::chrono::duration<double>(b - a).count();
}
printf("timing K=%d T=%d R=%d lost=%d trials=%d decode-ok=%d/%d "
"mean-decode %.4f s (%.2f MB/s)\n",
K, T, R, lost_n, trials, okc, trials,
dec_s / trials, (double)K * T / (dec_s / trials) / 1e6);
return 0;
}
if (mode == "overhead") {
int trials = atoi(argv[5]);
uint64_t seed = strtoull(argv[6], nullptr, 10);
sm_state = seed;
const int extras[] = {0, 1, 2, 3, 5};
printf("# overhead-curve K=%d T=%d sent=%d trials=%d seed=%llu\n",
K, T, K + R, trials, (unsigned long long)seed);
for (int e : extras) {
int recv_n = K + e;
if (recv_n > K + R) continue;
int okc = 0;
for (int tr = 0; tr < trials; tr++) {
std::vector<int> got = rand_subset(K + R, recv_n);
std::vector<char*> data; data.reserve(recv_n);
std::vector<char> islost(K, 0);
std::vector<int> lost;
for (int i = 0; i < K; i++) islost[i] = 1;
for (int id : got) {
if (id < K) { data.push_back(src[id]); islost[id] = 0; }
else data.push_back((char*)repairs[id - K]->data);
}
for (int i = 0; i < K; i++) if (islost[i]) lost.push_back(i);
okc += try_decode(K, T, src, got, data.data(), repairs, lost);
}
printf("recv K+%d: %d/%d = %.4f\n", e, okc, trials, (double)okc / trials);
fflush(stdout);
}
return 0;
}
fprintf(stderr, "unknown mode %s\n", mode.c_str());
return 2;
}
-149
View File
@@ -1,149 +0,0 @@
// lrq_bench.cc — M2.2 libRaptorQ cross-check bench (RAW API, RFC 6330).
//
// Same protocol as rq_bench overhead mode, but with the canonical
// libRaptorQ implementation, to cross-check foxsen's decode-success
// curve with an independent implementation:
// lrq_bench K T R trials seed
// K must be an exact RFC block size (e.g. 101, 1020); T multiple of 4.
// Sends K+R symbols; receives exactly K+e for e in {0,1,2,3,5} (random
// subset); success = decoder finishes with Error::NONE AND decoded
// bytes are byte-identical to the input. Reports mean decode time.
//
// Build (on hot_house):
// g++ -O2 -std=c++11 -DEIGEN_MPL2_ONLY -I/usr/include/eigen3 \
// -I/root/raptorq/libRaptorQ/src lrq_bench.cc -o lrq_bench \
// /root/raptorq/libRaptorQ/build/lib/libRaptorQ.1.a \
// /root/raptorq/libRaptorQ/build/librq_lz4_static.a -lpthread
#include "../src/RaptorQ/RaptorQ_v1_hdr.hpp"
#include <algorithm>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cstdint>
#include <vector>
namespace RaptorQ = RaptorQ__v1;
static uint64_t sm_state;
static uint64_t sm_next() {
uint64_t z = (sm_state += 0x9e3779b97f4a7c15ULL);
z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ULL;
z = (z ^ (z >> 27)) * 0x94d049bb133111ebULL;
return z ^ (z >> 31);
}
static std::vector<int> rand_subset(int total, int n) {
std::vector<int> idx(total);
for (int i = 0; i < total; i++) idx[i] = i;
for (int i = 0; i < n; i++) {
int j = i + (int)(sm_next() % (uint64_t)(total - i));
std::swap(idx[i], idx[j]);
}
idx.resize(n);
return idx;
}
int main(int argc, char **argv) {
if (argc < 6) {
fprintf(stderr, "usage: lrq_bench K T R trials seed\n");
return 2;
}
int K = atoi(argv[1]);
int T = atoi(argv[2]);
int R = atoi(argv[3]);
int trials = atoi(argv[4]);
sm_state = strtoull(argv[5], nullptr, 10);
size_t mysize = (size_t)K * (size_t)T;
RaptorQ::local_cache_size(5000000);
// pick exact block size K
RaptorQ::Block_Size block = RaptorQ::Block_Size::Block_10;
bool found = false;
for (auto blk : *RaptorQ::blocks) {
if (static_cast<uint16_t>(blk) == K) { block = blk; found = true; break; }
}
if (!found) { fprintf(stderr, "K=%d is not a valid RFC block size\n", K); return 2; }
// input: deterministic PRNG bytes
std::vector<uint8_t> input(mysize);
for (size_t i = 0; i < mysize; i += 8) {
uint64_t v = sm_next();
size_t n = mysize - i < 8 ? mysize - i : 8;
memcpy(&input[i], &v, n);
}
auto t0 = std::chrono::steady_clock::now();
RaptorQ::Encoder<typename std::vector<uint8_t>::iterator,
typename std::vector<uint8_t>::iterator> enc(block, (uint16_t)T);
if (enc.set_data(input.begin(), input.end()) != mysize) {
fprintf(stderr, "set_data failed\n"); return 1;
}
uint16_t syms = enc.symbols();
if (syms != K) { fprintf(stderr, "encoder symbols %u != K %d\n", syms, K); return 1; }
if (!enc.compute_sync()) { fprintf(stderr, "compute_sync failed\n"); return 1; }
auto t1 = std::chrono::steady_clock::now();
double enc_s = std::chrono::duration<double>(t1 - t0).count();
printf("# libRaptorQ encode K=%d T=%d R=%d: %.3f s (%.2f MB/s)\n",
K, T, R, enc_s, (double)mysize / enc_s / 1e6);
// collect all K+R symbols: (esi, bytes)
std::vector<std::pair<uint32_t, std::vector<uint8_t>>> all;
for (auto it = enc.begin_source(); it != enc.end_source(); ++it) {
std::vector<uint8_t> d(T, 0);
auto dit = d.begin();
auto w = (*it)(dit, d.end());
if (w != (uint16_t)T) { fprintf(stderr, "source sym short\n"); return 1; }
all.emplace_back((*it).id(), std::move(d));
}
auto rep_it = enc.begin_repair();
auto rep_end = enc.end_repair(enc.max_repair());
for (int i = 0; i < R && rep_it != rep_end; ++rep_it, ++i) {
std::vector<uint8_t> d(T, 0);
auto dit = d.begin();
auto w = (*rep_it)(dit, d.end());
if (w != (uint16_t)T) { fprintf(stderr, "repair sym short\n"); return 1; }
all.emplace_back((*rep_it).id(), std::move(d));
}
if ((int)all.size() != K + R) { fprintf(stderr, "collected %zu != K+R\n", all.size()); return 1; }
using Decoder_type = RaptorQ::Decoder<
typename std::vector<uint8_t>::iterator,
typename std::vector<uint8_t>::iterator>;
const int extras[] = {0, 1, 2, 3, 5};
printf("# overhead-curve K=%d T=%d sent=%d trials=%d\n", K, T, K + R, trials);
for (int e : extras) {
int recv_n = K + e;
if (recv_n > K + R) continue;
int okc = 0;
double dec_s = 0;
for (int tr = 0; tr < trials; tr++) {
std::vector<int> got = rand_subset(K + R, recv_n);
Decoder_type dec(block, (uint16_t)T, Decoder_type::Report::COMPLETE);
for (int gi : got) {
auto &sym = all[gi];
auto sit = sym.second.begin();
auto err = dec.add_symbol(sit, sym.second.end(), sym.first);
if (err != RaptorQ::Error::NONE && err != RaptorQ::Error::NOT_NEEDED) {
fprintf(stderr, "add_symbol err %d\n", (int)err); return 1;
}
}
dec.end_of_input(RaptorQ::Fill_With_Zeros::NO);
auto a = std::chrono::steady_clock::now();
auto res = dec.wait_sync();
auto b = std::chrono::steady_clock::now();
dec_s += std::chrono::duration<double>(b - a).count();
if (res.error != RaptorQ::Error::NONE) continue;
std::vector<uint8_t> out(mysize, 0);
auto oit = out.begin();
auto dout = dec.decode_bytes(oit, out.end(), 0, 0);
if (dout.written == mysize && memcmp(out.data(), input.data(), mysize) == 0)
okc++;
}
printf("recv K+%d: %d/%d = %.4f mean-decode %.4f s (%.2f MB/s)\n",
e, okc, trials, (double)okc / trials,
dec_s / trials, (double)mysize / (dec_s / trials) / 1e6);
fflush(stdout);
}
return 0;
}
-234
View File
@@ -1,234 +0,0 @@
// p4.cc — M2.2 RaptorQ file-recovery matrix (foxsen/raptorq, RFC 6330).
//
// One cell per invocation; the driver script runs the grid in parallel.
// p4 K T R e burst trials seed mode [--real] [--srcfile path]
//
// K,T file = K source symbols of T bytes.
// R repair symbols transmitted (overhead R/K).
// e erasure rate: iid symbol loss prob (mode iid/gilbert), or
// per-BLOCK failure prob q (mode block/blockburst).
// burst mean burst length in symbols (gilbert) or blocks (blockburst);
// 0 = iid (ignored for block mode).
// mode iid | gilbert | block | blockburst
// block: the K+R symbols are stored in ceil((K+R)/512) BCH blocks
// of 512 symbols (T=1024: one m=22/t=8 BCH block = 512 KiB); each
// block fails w.p. e and erases all its symbols. Repair symbols
// live on the same media, so they fail with the same block model.
// blockburst: block failures in Gilbert bursts (mean burst blocks).
// --real also run the REAL foxsen decode per trial (else model only).
// Real decode verifies byte-identical recovery of every lost
// source symbol. Encoding is done once per run.
// --srcfile use the first K*T bytes of a real file as source data.
//
// Schemes, all evaluated on the SAME erasure mask per trial (paired):
// bch BCH-alone (R=0 column): file recovers iff 0 source symbols lost.
// (A lost block is unrecoverable by inner BCH by construction:
// the mask marks symbols the inner layer could not deliver.)
// rs outer-RS MDS bound: recovers iff #lost symbols <= R.
// (Validated separately by rs_erase_test.c with a real GF(256)
// erasure codec; plain GF(256) RS caps at K+R<=255, so at large K
// this is the MDS bound a GF(2^16) RS would attain.)
// rqmod RaptorQ count model: recovers iff #received >= K+2 (RFC 6330
// rule of thumb; validated against real decodes in rq_bench /
// lrq_bench: 0 failures in 3000 trials at K+2 across both impls).
// rqreal real foxsen decode (--real only), byte-verified.
//
// Output: one line:
// cell K=.. T=.. R=.. e=.. burst=.. mode=.. trials=.. bch=.. rs=.. rqmod=..
// rqreal=..(-1 if not run) rq_only=.. rs_only=.. rqmod_agree=..
// where rq_only = trials where rqreal ok but rs not (and vice versa),
// rqmod_agree = trials where rqmod prediction == rqreal outcome.
//
// Build (on hot_house):
// g++ -O2 -std=c++11 -I/root/raptorq/foxsen p4.cc \
// /root/raptorq/foxsen/{Encoder,Decoder,Generators,Helper,StdAfx,Symbol}.cpp \
// -o p4
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cstdint>
#include <cmath>
#include <string>
#include <vector>
#include "Encoder.h"
#include "Decoder.h"
#include "Symbol.h"
static uint64_t sm_state;
static uint64_t sm_next() {
uint64_t z = (sm_state += 0x9e3779b97f4a7c15ULL);
z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ULL;
z = (z ^ (z >> 27)) * 0x94d049bb133111ebULL;
return z ^ (z >> 31);
}
static double sm_unif() { return (sm_next() >> 11) * (1.0 / 9007199254740992.0); }
static void fill_rand(char *p, size_t n) {
while (n >= 8) { uint64_t v = sm_next(); memcpy(p, &v, 8); p += 8; n -= 8; }
if (n) { uint64_t v = sm_next(); memcpy(p, &v, n); }
}
static int try_decode(int K, int T, char **src,
const std::vector<int> &recv_esi,
char **recv_data, const std::vector<int> &lost) {
int n = (int)recv_esi.size();
if (n < K) return 0;
int *esi = new int[n];
for (int i = 0; i < n; i++) esi[i] = recv_esi[i];
Decoder *dec = new Decoder();
if (!dec->init(K, T)) { delete dec; delete[] esi; return 0; }
bool ok = dec->decode(recv_data, n, esi);
int good = 0;
if (ok) {
good = 1;
for (int x : lost) {
Symbol *s = dec->recover(x);
if (!s || memcmp(s->data, src[x], (size_t)T) != 0) { good = 0; if (s) delete s; break; }
delete s;
}
}
delete dec;
delete[] esi;
return good;
}
int main(int argc, char **argv) {
if (argc < 9) {
fprintf(stderr, "usage: p4 K T R e burst trials seed mode [--real] [--srcfile path]\n");
return 2;
}
int K = atoi(argv[1]);
int T = atoi(argv[2]);
int R = atoi(argv[3]);
double e = atof(argv[4]);
double burst = atof(argv[5]);
int trials = atoi(argv[6]);
uint64_t seed = strtoull(argv[7], nullptr, 10);
std::string mode = argv[8];
bool real = false;
const char *srcfile = nullptr;
for (int i = 9; i < argc; i++) {
if (!strcmp(argv[i], "--real")) real = true;
else if (!strcmp(argv[i], "--srcfile") && i + 1 < argc) srcfile = argv[++i];
}
if (K < 1 || T < 1 || (T % 4) != 0 || R < 0 || e < 0 || e > 1 || trials < 1) {
fprintf(stderr, "bad args\n"); return 2;
}
int N = K + R;
const int BLK = 512; // symbols per m=22 BCH block at T=1024
int nblocks = (N + BLK - 1) / BLK;
sm_state = seed ? seed : 0x9E3779B97F4A7C15ULL;
// ---- source + encode (only needed for --real) ----
char **src = nullptr;
Symbol **repairs = nullptr;
Encoder *enc = nullptr;
if (real) {
src = new char*[K];
for (int i = 0; i < K; i++) src[i] = new char[T];
if (srcfile) {
FILE *f = fopen(srcfile, "rb");
if (!f) { fprintf(stderr, "cannot open %s\n", srcfile); return 2; }
size_t need = (size_t)K * (size_t)T, got = 0;
for (int i = 0; i < K && got < need; i++) {
size_t r = fread(src[i], 1, (size_t)T, f);
got += r;
if (r < (size_t)T) fill_rand(src[i] + r, (size_t)T - r);
}
fclose(f);
} else {
for (int i = 0; i < K; i++) fill_rand(src[i], (size_t)T);
}
enc = new Encoder();
if (!enc->init(K, T)) { fprintf(stderr, "encoder init failed\n"); return 1; }
repairs = enc->encode(src, R);
if (R > 0 && !repairs) { fprintf(stderr, "encode failed\n"); return 1; }
}
long bch_ok = 0, rs_ok = 0, rqmod_ok = 0, rqreal_ok = 0;
long rq_only = 0, rs_only = 0, agree = 0;
std::vector<char> lost(N);
std::vector<int> recv_esi; recv_esi.reserve(N);
std::vector<char*> recv_data; recv_data.reserve(N);
std::vector<int> lost_src; lost_src.reserve(K);
double b_gil = 0, a_gil = 0; // Gilbert params (per symbol or per block)
if ((mode == "gilbert" || mode == "blockburst") && burst > 0) {
b_gil = 1.0 / burst;
a_gil = e * b_gil / (1.0 - e);
if (a_gil > 1) a_gil = 1;
}
for (int tr = 0; tr < trials; tr++) {
// ---- generate mask over all N transmitted symbols ----
std::fill(lost.begin(), lost.end(), 0);
if (mode == "iid") {
for (int i = 0; i < N; i++) lost[i] = sm_unif() < e;
} else if (mode == "gilbert") {
int state = (sm_unif() < e) ? 1 : 0; // start from stationary
for (int i = 0; i < N; i++) {
lost[i] = state;
if (state) { if (sm_unif() < b_gil) state = 0; }
else { if (sm_unif() < a_gil) state = 1; }
}
} else if (mode == "block") {
for (int b = 0; b < nblocks; b++) {
if (sm_unif() < e) {
int lo = b * BLK, hi = lo + BLK < N ? lo + BLK : N;
for (int i = lo; i < hi; i++) lost[i] = 1;
}
}
} else if (mode == "blockburst") {
int state = (sm_unif() < e) ? 1 : 0;
for (int b = 0; b < nblocks; b++) {
if (state) {
int lo = b * BLK, hi = lo + BLK < N ? lo + BLK : N;
for (int i = lo; i < hi; i++) lost[i] = 1;
}
if (state) { if (sm_unif() < b_gil) state = 0; }
else { if (sm_unif() < a_gil) state = 1; }
}
} else { fprintf(stderr, "unknown mode %s\n", mode.c_str()); return 2; }
int n_lost = 0, n_lost_src = 0;
for (int i = 0; i < N; i++) n_lost += lost[i];
for (int i = 0; i < K; i++) n_lost_src += lost[i];
int n_recv = N - n_lost;
int bch = (n_lost_src == 0) ? 1 : 0;
int rs = (n_lost <= R) ? 1 : 0;
// RaptorQ needs K+2 received symbols to decode *when something is
// missing*; if all K source symbols arrived, recovery is trivial.
int rqmod = (n_lost_src == 0 || n_recv >= K + 2) ? 1 : 0;
if (R == 0) rqmod = bch;
bch_ok += bch; rs_ok += rs; rqmod_ok += rqmod;
if (real) {
recv_esi.clear(); recv_data.clear(); lost_src.clear();
for (int i = 0; i < K; i++) {
if (!lost[i]) { recv_esi.push_back(i); recv_data.push_back(src[i]); }
else lost_src.push_back(i);
}
for (int i = 0; i < R; i++) {
if (!lost[K + i]) { recv_esi.push_back(K + i); recv_data.push_back((char*)repairs[i]->data); }
}
int rqr = 0;
if (R == 0) rqr = bch;
else if (n_lost_src == 0) rqr = 1; // all source present: trivial
else if ((int)recv_esi.size() >= K) rqr = try_decode(K, T, src, recv_esi, recv_data.data(), lost_src);
else rqr = 0;
rqreal_ok += rqr;
if (rqr && !rs) rq_only++;
if (!rqr && rs) rs_only++;
if (rqr == rqmod) agree++;
}
}
printf("cell K=%d T=%d R=%d e=%.4g burst=%.4g mode=%s trials=%d seed=%llu "
"bch=%ld rs=%ld rqmod=%ld rqreal=%ld rq_only=%ld rs_only=%ld agree=%ld\n",
K, T, R, e, burst, mode.c_str(), trials, (unsigned long long)seed,
bch_ok, rs_ok, rqmod_ok, real ? rqreal_ok : -1,
rq_only, rs_only, real ? agree : -1);
fflush(stdout);
return 0;
}
-1083
View File
File diff suppressed because it is too large. Load diff
-2
View File
@@ -1,2 +0,0 @@
# cuda_dmin mode=cpu n=128 r=24 t=2 (dmin>=5) ncand=2000 seed=0x1111
CPU ncand=2000 pass=1911 (95.550%) secs=1.00 cands_per_sec=2005.7
-2
View File
@@ -1,2 +0,0 @@
# cuda_dmin mode=cpu n=64 r=16 t=2 (dmin>=5) ncand=20000 seed=0x5555
CPU ncand=20000 pass=8184 (40.920%) secs=2.17 cands_per_sec=9220.7
-2
View File
@@ -1,2 +0,0 @@
# cuda_dmin mode=cpu n=64 r=32 t=3 (dmin>=7) ncand=2000 seed=0x3333
CPU ncand=2000 pass=1989 (99.450%) secs=5.44 cands_per_sec=367.5
-2
View File
@@ -1,2 +0,0 @@
# cuda_dmin mode=cpu n=96 r=24 t=2 (dmin>=5) ncand=2000 seed=0x2222
CPU ncand=2000 pass=1963 (98.150%) secs=0.53 cands_per_sec=3804.9
-2
View File
@@ -1,2 +0,0 @@
# cuda_dmin mode=cpu n=96 r=32 t=3 (dmin>=7) ncand=500 seed=0x4444
CPU ncand=500 pass=484 (96.800%) secs=5.66 cands_per_sec=88.4
-5
View File
@@ -1,5 +0,0 @@
# cuda_dmin mode=sweep n=128 r=16 t=2 (dmin>=5) ncand=1000000 seed=0x6666
# gpu: NVIDIA GeForce RTX 3080 Ti 80 SMs, 11928 MB
# pool: 128 blocks x 2^21 slots = 2.15 GB
GPU ncand=1000000 pass=9688 (0.9688%) secs=8.110 cands_per_sec=123297.6
# survivors written to results/cuda-sweep-128r16t2.txt
Loaded 100 of 385 files, more files were not shown because too many files have changed in this diff. Show more