Compare commits
40
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
88d1e3b183 | ||
|
|
c6e06a0d48 | ||
|
|
cd338d4fc0 | ||
|
|
da291f0f9a | ||
|
|
a2ecebb5e6 | ||
|
|
2d98c4aad3 | ||
|
|
902d10d0e7 | ||
|
|
38edbb9ac1 | ||
|
|
5362ad35b0 | ||
|
|
2dac37b40c | ||
|
|
fe512e6df2 | ||
|
|
e00f9af438 | ||
|
|
b47d472fe3 | ||
|
|
f32323eff8 | ||
|
|
368644a392 | ||
|
|
8e40d15470 | ||
|
|
6af210579a | ||
|
|
8b501a01d0 | ||
|
|
6ea6cf9ab0 | ||
|
|
c6a13f189c | ||
|
|
fddd00c784 | ||
|
|
0f2cb105fc | ||
|
|
e53455bf07 | ||
|
|
828208cb1e | ||
|
|
f60ca9fd73 | ||
|
|
bf8efab2b7 | ||
|
|
1239bd9c64 | ||
|
|
2932575441 | ||
|
|
4c32b542ba | ||
|
|
c07d986cd9 | ||
|
|
0022cd76e0 | ||
|
|
40d4d996d6 | ||
|
|
acedd368df | ||
|
|
8d268167f8 | ||
|
|
5c65f3cd89 | ||
|
|
fe90ef37b2 | ||
|
|
73e333f6f3 | ||
|
|
911b3c998f | ||
|
|
b27b3455c1 | ||
|
|
679d1a194f |
No files matched your search
@@ -0,0 +1,135 @@
|
||||
# macOS build (CPU-only) — lzply has never been built on a Mac.
|
||||
#
|
||||
# Apple Silicon (arm64) is the standard runner now; Intel still has a
|
||||
# standard runner (macos-15-intel) until ~Aug 2027, so both are built.
|
||||
# Pinned to macos-15, not macos-latest: -latest is a moving target
|
||||
# (migrating 15 -> 26) and the OS generation is part of the build
|
||||
# contract for a release binary.
|
||||
#
|
||||
# No CUDA on Mac (no NVIDIA GPU on modern Macs) and no FUSE
|
||||
# (lzply_mount is Linux-only), so this builds the core tools only.
|
||||
# GNU coreutils (gnubin on PATH) supplies the GNU stat/dd/timeout the
|
||||
# shell suites need. Homebrew's lzlib formula provides liblz + lzlib.h
|
||||
# (the lzip formula is only the CLI tool, used by the test cross-check).
|
||||
#
|
||||
# The mount tests in the shell suites skip cleanly (no /dev/fuse, no
|
||||
# lzply_mount binary). lzply_util.c's /proc mount resolution compiles
|
||||
# on macOS and degrades gracefully (finds no mounts) — a known
|
||||
# limitation, not a failure: stat/heal/check/refresh still work on
|
||||
# plain archive paths.
|
||||
#
|
||||
# Diagnosability: run #3 failed at the chained "C unit tests" step
|
||||
# with no retrievable logs, so each C test is now its own step, every
|
||||
# test writes its output to a log file that is also printed to the
|
||||
# step log, and all logs are uploaded as artifacts on failure.
|
||||
name: macOS build
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, ci/macos-build]
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: macOS ${{ matrix.arch }} (${{ matrix.os }})
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- os: macos-15
|
||||
arch: arm64
|
||||
- os: macos-15-intel
|
||||
arch: x86_64
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- name: Check out
|
||||
uses: actions/checkout@v5
|
||||
|
||||
- name: Install dependencies (lzlib + lzip CLI + GNU coreutils)
|
||||
run: brew install lzip lzlib coreutils
|
||||
|
||||
- name: Build core tools (CPU-only, no FUSE mount)
|
||||
run: |
|
||||
exec > >(tee build.log) 2>&1
|
||||
export PATH="$(brew --prefix coreutils)/libexec/gnubin:$PATH"
|
||||
make -j"$(sysctl -n hw.ncpu)" CC=cc \
|
||||
CFLAGS="-O2 -Wall -Wextra -I$(brew --prefix lzlib)/include" \
|
||||
LDLIBS="-L$(brew --prefix lzlib)/lib -llz" \
|
||||
lzply lz_rs lzply_deep_repair lzply_stat lzply_heal \
|
||||
lzply_check lzply_refresh lzply_hyper \
|
||||
bch_test rs_test crc16_test chase_bench_cpu
|
||||
file lzply
|
||||
|
||||
- name: Pre-flight (test binaries and linked libraries)
|
||||
run: |
|
||||
ls -la bch_test rs_test crc16_test
|
||||
file bch_test rs_test crc16_test
|
||||
otool -L ./bch_test ./rs_test ./crc16_test
|
||||
ls -la "$(brew --prefix lzlib)/lib/"
|
||||
|
||||
- name: C unit test (bch)
|
||||
run: |
|
||||
./bch_test > bch_test.log 2>&1 || rc=$?
|
||||
cat bch_test.log
|
||||
exit ${rc:-0}
|
||||
|
||||
- name: C unit test (rs)
|
||||
run: |
|
||||
./rs_test > rs_test.log 2>&1 || rc=$?
|
||||
cat rs_test.log
|
||||
exit ${rc:-0}
|
||||
|
||||
- name: C unit test (crc16)
|
||||
run: |
|
||||
./crc16_test > crc16_test.log 2>&1 || rc=$?
|
||||
cat crc16_test.log
|
||||
exit ${rc:-0}
|
||||
|
||||
- name: Build test data
|
||||
run: |
|
||||
export PATH="$(brew --prefix coreutils)/libexec/gnubin:$PATH"
|
||||
make testdata
|
||||
|
||||
- name: "Shell suites (mount tests skip: no FUSE on macOS)"
|
||||
run: |
|
||||
export PATH="$(brew --prefix coreutils)/libexec/gnubin:$PATH"
|
||||
./tests/run_rs_tests.sh ./lz_rs
|
||||
./tests/run_tests.sh ./lzply
|
||||
./tests/run_deep_repair_tests.sh ./lzply_deep_repair ./lzply ./lz_rs
|
||||
./tests/run_hyper_tests.sh ./lzply_hyper
|
||||
|
||||
- name: Smoke test (round-trip)
|
||||
run: |
|
||||
for i in $(seq 1 100); do echo "hello macOS $i"; done > /tmp/smoke.txt
|
||||
./lzply -c /tmp/smoke.txt /tmp/smoke.lzply
|
||||
./lzply -t /tmp/smoke.lzply
|
||||
mkdir -p /tmp/smoke-out && ./lzply -d /tmp/smoke.lzply /tmp/smoke-out
|
||||
cmp /tmp/smoke.txt /tmp/smoke-out/smoke.txt
|
||||
|
||||
- name: Upload test logs on failure
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: test-logs-macos-${{ matrix.arch }}
|
||||
path: |
|
||||
build.log
|
||||
bch_test.log
|
||||
rs_test.log
|
||||
crc16_test.log
|
||||
if-no-files-found: warn
|
||||
|
||||
- name: Upload binaries
|
||||
uses: actions/upload-artifact@v5
|
||||
with:
|
||||
name: lzply-macos-${{ matrix.arch }}
|
||||
path: |
|
||||
lzply
|
||||
lz_rs
|
||||
lzply_deep_repair
|
||||
lzply_stat
|
||||
lzply_heal
|
||||
lzply_check
|
||||
lzply_refresh
|
||||
lzply_hyper
|
||||
if-no-files-found: error
|
||||
+21
@@ -14,3 +14,24 @@
|
||||
/testdata/
|
||||
/testwork/
|
||||
/testwork-hyper/
|
||||
/lz_rs
|
||||
/rs_test
|
||||
/testwork-rs/
|
||||
/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/
|
||||
@@ -0,0 +1,97 @@
|
||||
# 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).
|
||||
@@ -3,14 +3,73 @@ CFLAGS = -O2 -Wall -Wextra
|
||||
LDLIBS = -llz
|
||||
PREFIX = /usr/local
|
||||
|
||||
all: lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyper
|
||||
# CUDA (optional): nvcc is found on PATH first; on hot_house it lives
|
||||
# at /usr/local/cuda/bin/nvcc (not on PATH by default), so fall back
|
||||
# to that path when it exists. Two CUDA objects share this NVCC:
|
||||
# bch_cuda.o -- CUDA BCH remainder (bch.c dispatches via weak
|
||||
# symbols for large blobs); linked into liblzply.a
|
||||
# and every tool. Without nvcc the build is
|
||||
# unchanged (CPU-only).
|
||||
# chase_cuda.o -- CUDA Chase-1 scan for deep repair (t=8 only);
|
||||
# linked into lzply and lzply_deep_repair, with a
|
||||
# CPU fallback via weak references.
|
||||
# Without nvcc, the *_cuda_stub.o objects are linked instead, so
|
||||
# the CUDA entry points always resolve -- see the stub comment
|
||||
# below. The stubs are required on macOS: ld64 does not resolve
|
||||
# __attribute__((weak)) declarations to NULL the way GNU ld does,
|
||||
# so a CPU-only build failed at link time with undefined
|
||||
# _bch_cuda_available/_encode/_decode symbols (and, after the
|
||||
# chase-wired merge, _chase_cuda_available/_scan1). A stub is
|
||||
# never built alongside its CUDA object, so the symbols are
|
||||
# defined exactly once.
|
||||
# These definitions MUST stay above every rule that references
|
||||
# $(CUDA_OBJ): make expands prerequisites when the rule is read, so
|
||||
# a definition below the liblzply.a rule would silently leave
|
||||
# bch_cuda.o out of the archive. NOTE: bch_cuda.o is still listed
|
||||
# explicitly on each tool link line below, because the weak
|
||||
# references from bch.o do not make the linker pull it out of the
|
||||
# archive on their own. The stub is listed the same way.
|
||||
NVCC ?= $(shell command -v nvcc 2>/dev/null)
|
||||
ifeq ($(NVCC),)
|
||||
NVCC := $(wildcard /usr/local/cuda/bin/nvcc)
|
||||
endif
|
||||
CUDA_ARCH ?= sm_86
|
||||
NVCCFLAGS = -O3 -arch=$(CUDA_ARCH) -Xcompiler -O2
|
||||
CUDA_OBJ =
|
||||
CUDA_LIBS =
|
||||
ifneq ($(NVCC),)
|
||||
CUDA_OBJ = bch_cuda.o
|
||||
CUDA_LIBS = -L$(dir $(NVCC))../lib64 -lcudart -lstdc++
|
||||
endif
|
||||
CHASE_CUDA_OBJ =
|
||||
ifneq ($(wildcard $(NVCC)),)
|
||||
CHASE_CUDA_OBJ = chase_cuda.o
|
||||
endif
|
||||
|
||||
# Shared core: the v4 archive format, the per-entry pipeline
|
||||
# CPU-only stubs: when nvcc is absent, bch_cuda_stub.o defines the
|
||||
# three BCH CUDA entry points (available() = 0, encode = 0,
|
||||
# decode = -2) and chase_cuda_stub.o defines the two Chase CUDA
|
||||
# entry points (available() = 0, scan1 = -2), so bch.c's and
|
||||
# deep_repair.c's references always resolve. This is required on
|
||||
# macOS: ld64 does not resolve __attribute__((weak)) declarations
|
||||
# to NULL the way GNU ld does, so a CPU-only build failed at link
|
||||
# time with undefined _bch_cuda_available/_encode/_decode symbols
|
||||
# (and, after the chase-wired merge, _chase_cuda_available/_scan1).
|
||||
# A stub is never built alongside its CUDA object, so the symbols
|
||||
# are defined exactly once.
|
||||
CUDA_STUB_OBJ =
|
||||
ifeq ($(NVCC),)
|
||||
CUDA_STUB_OBJ = bch_cuda_stub.o chase_cuda_stub.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
|
||||
# (lzip -> BCH), header I/O, scan, and filters. The
|
||||
# command-line tool (lzply), the FUSE filesystem (lzply_mount),
|
||||
# the statistics tool (lzply_stat) and the heal tool (lzply_heal)
|
||||
# all link it.
|
||||
liblzply.a: lzply_lib.o bch.o sha256.o
|
||||
liblzply.a: lzply_lib.o bch.o sha256.o $(CUDA_OBJ) $(CUDA_STUB_OBJ)
|
||||
ar rcs $@ $^
|
||||
|
||||
lzply_lib.o: lzply_lib.c lzply_lib.h bch.h bch_polys.h sha256.h
|
||||
@@ -22,11 +81,45 @@ 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
|
||||
bch_cuda_stub.o: bch_cuda_stub.c bch_cuda.h bch.h
|
||||
$(CC) $(CFLAGS) -c -o $@ bch_cuda_stub.c
|
||||
|
||||
chase_cuda_stub.o: chase_cuda_stub.c chase_cuda.h bch.h
|
||||
$(CC) $(CFLAGS) -c -o $@ chase_cuda_stub.c
|
||||
|
||||
# CUDA BCH remainder rules (variables are defined at the top).
|
||||
ifneq ($(NVCC),)
|
||||
bch_cuda.o: bch_cuda.cu bch_cuda.h bch.h bch_polys.h
|
||||
$(NVCC) -O3 -arch=$(CUDA_ARCH) -Xcompiler -O2 -c -o $@ bch_cuda.cu
|
||||
|
||||
bch_cuda_test.o: bch_cuda_test.c bch_cuda.h bch.h
|
||||
$(CC) $(CFLAGS) -c -o $@ bch_cuda_test.c
|
||||
|
||||
bch_cuda_test: bch_cuda_test.o bch_cuda.o bch.o
|
||||
$(NVCC) -arch=$(CUDA_ARCH) -o $@ bch_cuda_test.o bch_cuda.o bch.o
|
||||
|
||||
bch_bench.o: bch_bench.c bch.h
|
||||
$(CC) $(CFLAGS) -c -o $@ bch_bench.c
|
||||
|
||||
bch_bench: bch_bench.o bch.o bch_cuda.o
|
||||
$(NVCC) -arch=$(CUDA_ARCH) -o $@ bch_bench.o bch.o bch_cuda.o
|
||||
else
|
||||
bch_bench.o: bch_bench.c bch.h
|
||||
$(CC) $(CFLAGS) -c -o $@ bch_bench.c
|
||||
|
||||
bch_bench: bch_bench.o bch.o $(CUDA_STUB_OBJ)
|
||||
$(CC) $(CFLAGS) -o $@ bch_bench.o bch.o $(CUDA_STUB_OBJ)
|
||||
endif
|
||||
|
||||
lzply.o: lzply.c lzply_lib.h bch.h bch_polys.h deep_repair.h repair_cmd.h
|
||||
$(CC) $(CFLAGS) -c -o $@ lzply.c
|
||||
|
||||
lzply: lzply.o liblzply.a
|
||||
$(CC) $(CFLAGS) -o $@ lzply.o liblzply.a $(LDLIBS)
|
||||
lzply: lzply.o deep_repair.o repair_cmd.o liblzrs.a liblzply.a $(CUDA_OBJ) $(CHASE_CUDA_OBJ) $(CUDA_STUB_OBJ)
|
||||
ifeq ($(CHASE_CUDA_OBJ),)
|
||||
$(CC) $(CFLAGS) -o $@ lzply.o deep_repair.o repair_cmd.o liblzrs.a $(CUDA_OBJ) $(CUDA_STUB_OBJ) liblzply.a $(LDLIBS) $(CUDA_LIBS)
|
||||
else
|
||||
$(NVCC) -arch=$(CUDA_ARCH) -o $@ lzply.o deep_repair.o repair_cmd.o liblzrs.a $(CUDA_OBJ) $(CUDA_STUB_OBJ) liblzply.a $(CHASE_CUDA_OBJ) $(LDLIBS) $(CUDA_LIBS)
|
||||
endif
|
||||
|
||||
# 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).
|
||||
@@ -36,8 +129,8 @@ FUSE_LIBS = -lfuse3
|
||||
lzply_mount.o: lzply_mount.c lzply_lib.h bch.h bch_polys.h
|
||||
$(CC) $(CFLAGS) $(FUSE_CFLAGS) -c -o $@ lzply_mount.c
|
||||
|
||||
lzply_mount: lzply_mount.o liblzply.a
|
||||
$(CC) $(CFLAGS) $(FUSE_CFLAGS) -o $@ lzply_mount.o liblzply.a $(LDLIBS) $(FUSE_LIBS)
|
||||
lzply_mount: lzply_mount.o liblzply.a $(CUDA_OBJ) $(CUDA_STUB_OBJ)
|
||||
$(CC) $(CFLAGS) $(FUSE_CFLAGS) -o $@ lzply_mount.o $(CUDA_OBJ) $(CUDA_STUB_OBJ) liblzply.a $(LDLIBS) $(FUSE_LIBS) $(CUDA_LIBS)
|
||||
|
||||
# Shared helpers for lzply_stat and lzply_heal (mount resolution via
|
||||
# /proc, human-size formatting). No FUSE needed.
|
||||
@@ -47,14 +140,14 @@ lzply_util.o: lzply_util.c lzply_lib.h lzply_util.h
|
||||
lzply_stat.o: lzply_stat.c lzply_lib.h lzply_util.h
|
||||
$(CC) $(CFLAGS) -c -o $@ lzply_stat.c
|
||||
|
||||
lzply_stat: lzply_stat.o lzply_util.o liblzply.a
|
||||
$(CC) $(CFLAGS) -o $@ lzply_stat.o lzply_util.o liblzply.a $(LDLIBS)
|
||||
lzply_stat: lzply_stat.o lzply_util.o liblzply.a $(CUDA_OBJ) $(CUDA_STUB_OBJ)
|
||||
$(CC) $(CFLAGS) -o $@ lzply_stat.o lzply_util.o $(CUDA_OBJ) $(CUDA_STUB_OBJ) liblzply.a $(LDLIBS) $(CUDA_LIBS)
|
||||
|
||||
lzply_heal.o: lzply_heal.c lzply_lib.h lzply_util.h
|
||||
$(CC) $(CFLAGS) -c -o $@ lzply_heal.c
|
||||
|
||||
lzply_heal: lzply_heal.o lzply_util.o liblzply.a
|
||||
$(CC) $(CFLAGS) -o $@ lzply_heal.o lzply_util.o liblzply.a $(LDLIBS)
|
||||
lzply_heal: lzply_heal.o lzply_util.o liblzply.a $(CUDA_OBJ) $(CUDA_STUB_OBJ)
|
||||
$(CC) $(CFLAGS) -o $@ lzply_heal.o lzply_util.o $(CUDA_OBJ) $(CUDA_STUB_OBJ) liblzply.a $(LDLIBS) $(CUDA_LIBS)
|
||||
|
||||
# Bit error rate detector. Read-only: decodes each BCH entry's stored
|
||||
# bytes in memory and counts the corrected bit errors. Links the same
|
||||
@@ -62,8 +155,8 @@ lzply_heal: lzply_heal.o lzply_util.o liblzply.a
|
||||
lzply_check.o: lzply_check.c lzply_lib.h lzply_util.h
|
||||
$(CC) $(CFLAGS) -c -o $@ lzply_check.c
|
||||
|
||||
lzply_check: lzply_check.o lzply_util.o liblzply.a
|
||||
$(CC) $(CFLAGS) -o $@ lzply_check.o lzply_util.o liblzply.a $(LDLIBS) -lm
|
||||
lzply_check: lzply_check.o lzply_util.o liblzply.a $(CUDA_OBJ) $(CUDA_STUB_OBJ)
|
||||
$(CC) $(CFLAGS) -o $@ lzply_check.o lzply_util.o $(CUDA_OBJ) $(CUDA_STUB_OBJ) liblzply.a $(LDLIBS) -lm $(CUDA_LIBS)
|
||||
|
||||
# In-place platter refresher. Reads a file (or every regular file
|
||||
# under a directory / mount point) and rewrites it over itself, with
|
||||
@@ -72,8 +165,8 @@ lzply_check: lzply_check.o lzply_util.o liblzply.a
|
||||
lzply_refresh.o: lzply_refresh.c lzply_lib.h lzply_util.h
|
||||
$(CC) $(CFLAGS) -c -o $@ lzply_refresh.c
|
||||
|
||||
lzply_refresh: lzply_refresh.o lzply_util.o liblzply.a
|
||||
$(CC) $(CFLAGS) -o $@ lzply_refresh.o lzply_util.o liblzply.a $(LDLIBS)
|
||||
lzply_refresh: lzply_refresh.o lzply_util.o liblzply.a $(CUDA_OBJ) $(CUDA_STUB_OBJ)
|
||||
$(CC) $(CFLAGS) -o $@ lzply_refresh.o lzply_util.o $(CUDA_OBJ) $(CUDA_STUB_OBJ) liblzply.a $(LDLIBS) $(CUDA_LIBS)
|
||||
|
||||
# Striped volume (bit-plane, 8 data stripes + 1-3 XOR/GF parity stripes
|
||||
# + BCH). No compression, so it links only bch.o + sha256.o — no
|
||||
@@ -81,11 +174,70 @@ lzply_refresh: lzply_refresh.o lzply_util.o liblzply.a
|
||||
lzply_hyper.o: lzply_hyper.c bch.h bch_polys.h sha256.h
|
||||
$(CC) $(CFLAGS) -c -o $@ lzply_hyper.c
|
||||
|
||||
lzply_hyper: lzply_hyper.o bch.o sha256.o
|
||||
$(CC) $(CFLAGS) -o $@ lzply_hyper.o bch.o sha256.o
|
||||
lzply_hyper: lzply_hyper.o bch.o sha256.o $(CUDA_STUB_OBJ)
|
||||
$(CC) $(CFLAGS) -o $@ lzply_hyper.o bch.o sha256.o $(CUDA_STUB_OBJ)
|
||||
|
||||
bch_test: bch.c bch_test.c bch.h bch_polys.h
|
||||
$(CC) $(CFLAGS) -o $@ bch.c bch_test.c
|
||||
bch_test: bch.c bch_test.c bch_cuda_stub.c bch.h bch_polys.h bch_cuda.h
|
||||
$(CC) $(CFLAGS) -o $@ bch.c bch_test.c bch_cuda_stub.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_cuda_stub.c bch.h bch_polys.h bch_cuda.h
|
||||
$(CC) $(CFLAGS) -o $@ chase_bench.c bch.c bch_cuda_stub.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).
|
||||
rs.o: rs.c rs.h
|
||||
$(CC) $(CFLAGS) -c -o $@ rs.c
|
||||
|
||||
lzrs_lib.o: lzrs_lib.c lzrs_lib.h lzply_lib.h rs.h bch.h sha256.h
|
||||
$(CC) $(CFLAGS) -c -o $@ lzrs_lib.c
|
||||
|
||||
liblzrs.a: lzrs_lib.o rs.o
|
||||
ar rcs $@ $^
|
||||
|
||||
lz_rs.o: lz_rs.c lzrs_lib.h lzply_lib.h bch.h bch_polys.h
|
||||
$(CC) $(CFLAGS) -c -o $@ lz_rs.c
|
||||
|
||||
lz_rs: lz_rs.o liblzrs.a liblzply.a $(CUDA_OBJ) $(CUDA_STUB_OBJ)
|
||||
$(CC) $(CFLAGS) -o $@ lz_rs.o liblzrs.a $(CUDA_OBJ) $(CUDA_STUB_OBJ) liblzply.a $(LDLIBS) $(CUDA_LIBS)
|
||||
|
||||
rs_test: rs.c rs_test.c rs.h
|
||||
$(CC) $(CFLAGS) -o $@ rs.c rs_test.c
|
||||
|
||||
# CRC-16/CCITT-FALSE unit test (vectors + cross-checks). Links the
|
||||
# shared core for crc16_of.
|
||||
crc16_test: crc16_test.c liblzply.a $(CUDA_STUB_OBJ)
|
||||
$(CC) $(CFLAGS) -o $@ crc16_test.c liblzply.a $(CUDA_STUB_OBJ) $(LDLIBS)
|
||||
|
||||
# Deep repair: Chase / list decoding past t (bch.c) + the escalating
|
||||
# ladder (deep_repair.c) + the lzply_deep_repair CLI. Links both
|
||||
# archive layers (LZPL v5 + LZRS v1).
|
||||
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
|
||||
$(CC) $(CFLAGS) -c -o $@ lzply_deep_repair.c
|
||||
|
||||
lzply_deep_repair: lzply_deep_repair.o repair_cmd.o deep_repair.o liblzrs.a liblzply.a $(CUDA_OBJ) $(CHASE_CUDA_OBJ) $(CUDA_STUB_OBJ)
|
||||
ifeq ($(CHASE_CUDA_OBJ),)
|
||||
$(CC) $(CFLAGS) -o $@ lzply_deep_repair.o repair_cmd.o deep_repair.o liblzrs.a $(CUDA_OBJ) $(CUDA_STUB_OBJ) liblzply.a $(LDLIBS) $(CUDA_LIBS)
|
||||
else
|
||||
$(NVCC) -arch=$(CUDA_ARCH) -o $@ lzply_deep_repair.o repair_cmd.o deep_repair.o liblzrs.a $(CUDA_OBJ) $(CUDA_STUB_OBJ) liblzply.a $(CHASE_CUDA_OBJ) $(LDLIBS) $(CUDA_LIBS)
|
||||
endif
|
||||
|
||||
# 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
|
||||
@@ -107,22 +259,51 @@ bch_test: bch.c bch_test.c bch.h bch_polys.h
|
||||
testdata:
|
||||
@if [ ! -d testdata/mixed ]; then ./tests/make_testdata.sh; fi
|
||||
|
||||
test: testdata bch_test lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyper
|
||||
test: testdata bch_test rs_test crc16_test lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyper lz_rs lzply_deep_repair
|
||||
./bch_test
|
||||
./rs_test
|
||||
./crc16_test
|
||||
if [ -x ./tests/run_rs_tests.sh ]; then \
|
||||
./tests/run_rs_tests.sh ./lz_rs; \
|
||||
elif [ -x ../tests/run_rs_tests.sh ]; then \
|
||||
../tests/run_rs_tests.sh ./lz_rs; \
|
||||
else echo "run_rs_tests.sh not found"; exit 1; fi
|
||||
if [ -x ./tests/run_tests.sh ]; then \
|
||||
./tests/run_tests.sh ./lzply; \
|
||||
elif [ -x ../tests/run_tests.sh ]; then \
|
||||
../tests/run_tests.sh ./lzply; \
|
||||
else echo "run_tests.sh not found"; exit 1; fi
|
||||
if [ -x ./tests/run_deep_repair_tests.sh ]; then \
|
||||
./tests/run_deep_repair_tests.sh ./lzply_deep_repair ./lzply ./lz_rs; \
|
||||
elif [ -x ../tests/run_deep_repair_tests.sh ]; then \
|
||||
../tests/run_deep_repair_tests.sh ./lzply_deep_repair ./lzply ./lz_rs; \
|
||||
else echo "run_deep_repair_tests.sh not found"; exit 1; fi
|
||||
if [ -x ./tests/run_hyper_tests.sh ]; then \
|
||||
./tests/run_hyper_tests.sh ./lzply_hyper; \
|
||||
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
|
||||
|
||||
install: lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyper
|
||||
# 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
|
||||
install -m 755 lzply $(PREFIX)/bin/lzply
|
||||
install -m 755 lz_rs $(PREFIX)/bin/lz_rs
|
||||
install -m 755 lzply_deep_repair $(PREFIX)/bin/lzply_deep_repair
|
||||
install -m 755 lzply_mount $(PREFIX)/bin/lzply_mount
|
||||
install -m 755 lzply_stat $(PREFIX)/bin/lzply_stat
|
||||
install -m 755 lzply_heal $(PREFIX)/bin/lzply_heal
|
||||
@@ -132,6 +313,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 bch_test *.o liblzply.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 bch_cuda_test bch_bench chase_bench_cpu chase_bench_cuda *.o liblzply.a liblzrs.a
|
||||
|
||||
.PHONY: all test install clean
|
||||
.PHONY: all test install clean exp experiments
|
||||
@@ -11,7 +11,7 @@ One archive file (like zip) holding many entries. Every entry is an
|
||||
independent byte stream:
|
||||
|
||||
```
|
||||
compress -> BCH encode (on write, v4)
|
||||
compress -> BCH encode (on write, v5)
|
||||
BCH-decode -> decompress (on read)
|
||||
```
|
||||
|
||||
@@ -62,6 +62,9 @@ SHA-256 implementation (`sha256.c`).
|
||||
* **`lzply`** — the archiver. Create, extract, test, list, inspect
|
||||
(`-i`), tree (`-tr`), append (`-a`), date filters, store mode.
|
||||
The core of the repo.
|
||||
* **`lz_rs`** — the archiver with Reed-Solomon on top: the same
|
||||
modes as `lzply`, plus `-r <0..4>` for the RS level, writing
|
||||
the LZRS v1 format (see `docs/lzrs-format.md`). Default `-r 2`.
|
||||
* **`lzply_mount`** — mount a `.lzply` archive as a writable
|
||||
filesystem (FUSE). `mount -t lzply` works too.
|
||||
* **`lzply_stat`** — statistics for an archive or a mount point:
|
||||
@@ -110,24 +113,28 @@ Full write-up, including the prior-art check and the per-length
|
||||
tables:
|
||||
https://www.lzply.com/reed-solomon-is-leaving-40-of-your-parity-on-the-table-i-searched-16-377-payload-lengths-and-found-97-612-codes-that-beat-it-all-58-polynomials-full-source/
|
||||
|
||||
## Format (v4; a single format, all integers little-endian)
|
||||
## Format (v5; a single format, all integers little-endian)
|
||||
|
||||
```
|
||||
global header (16 bytes):
|
||||
magic "LZPL", version u8 (4), flags u8, entry_count u32, reserved u64
|
||||
magic "LZPL", version u8 (5), flags u8, entry_count u32, reserved u64
|
||||
entries, each:
|
||||
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,
|
||||
u32 mode, u64 mtime, u16 crc16, u32 header_crc32,
|
||||
path[path_len], data[stored_size]
|
||||
end marker: u16 path_len == 0
|
||||
```
|
||||
|
||||
`header_crc32` covers the 74 bytes before it. `blob_size` is the
|
||||
`header_crc32` covers the 76 bytes before it. `blob_size` is the
|
||||
length of the compressed (or, for a stored entry, raw) stream
|
||||
before error-correction
|
||||
parity was added. `mtime` is the source's modification time in
|
||||
seconds since the epoch (UTC). Level is the lzip level (1..9) of
|
||||
seconds since the epoch (UTC). `crc16` is CRC-16/CCITT-FALSE
|
||||
(poly 0x1021, init 0xFFFF, no reflection, xorout 0) of the blob;
|
||||
writers compute and store it, readers verify it after
|
||||
error-correction decoding and before decompression, and a mismatch
|
||||
is a clean failure, never a misdecode. Level is the lzip level (1..9) of
|
||||
the blob, or 0 for a stored (uncompressed) entry. Flags: bit 0 is
|
||||
unused (it was used
|
||||
by v3), bit 1 =
|
||||
@@ -138,8 +145,10 @@ parent, so `lzply -c photos/` stores `photos/...` and restores the
|
||||
tree on extract. Entry paths containing `..` or starting with `/`
|
||||
are rejected on extract.
|
||||
|
||||
There is no legacy support: v1 (Reed-Solomon), v2, and v3 archives
|
||||
are not readable (v3 had AES-256-GCM encryption, removed in v4),
|
||||
There is no legacy support: v1 (Reed-Solomon), v2, v3, and v4
|
||||
archives
|
||||
are not readable (v3 had AES-256-GCM encryption, removed in v4;
|
||||
v4 predates the CRC16 migration to v5),
|
||||
and neither is any archive with an old magic (`LZRS`
|
||||
or `LZBC`) — the magic is now `LZPL`, and old magics are rejected
|
||||
outright. The format was never used anywhere yet, so it changes
|
||||
@@ -153,13 +162,121 @@ polynomial and checks it byte-identical to `polys.txt`, so the
|
||||
embedded table is verified, not just copied. Regenerate with
|
||||
`python3 gen_bch_polys.py` (or `make bch_polys.h`).
|
||||
|
||||
## lz_rs — lzip + BCH + Reed-Solomon
|
||||
|
||||
`lz_rs` is `lzply` plus a Reed-Solomon layer, in its own format
|
||||
(LZRS v1, magic `LZRS`). The pipeline per entry is lzip compress
|
||||
-> BCH encode -> RS encode, decoded in reverse, with the SHA-256
|
||||
check as the oracle for the whole stack. RS is the outer layer
|
||||
because it corrects whole-byte and burst errors — up to 16 byte
|
||||
errors per 255-byte block at `-r 4` — while BCH stays responsible
|
||||
for scattered bit errors. RS(255, 255-p) over GF(2^8), primitive
|
||||
polynomial `0x11D`, primitive element 2, first consecutive root 0.
|
||||
|
||||
`-r <0..4>` selects the parity per block: 0 = none, 1 -> 8, 2 -> 16,
|
||||
3 -> 24, 4 -> 32 symbols, correcting 0, 4, 8, 12, 16 byte errors
|
||||
per block. Default `-r 2`. `-r 0` behaves like plain lzply: the
|
||||
stored bytes are byte-identical to `lzply -e 0` for the same input.
|
||||
The LZRS v1 entry header is 82 bytes (the v5 layout plus
|
||||
`bch_poly_id` before the header CRC); `crc16` is CRC-16/CCITT-FALSE
|
||||
of the blob, computed by writers and verified by readers (see
|
||||
`docs/lzrs-format.md`). Full design, format, benchmarks and
|
||||
tests: `docs/lzrs-format.md`. `make test` runs `rs_test`
|
||||
(6,243 checks) and `tests/run_rs_tests.sh` (59 checks).
|
||||
|
||||
`lz_rs` rejects lzply v4 archives (they predate the CRC16
|
||||
migration) and `lzply` rejects `.lzrs`
|
||||
archives, in both directions. There is no legacy support: LZRS v1
|
||||
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
|
||||
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):
|
||||
|
||||
```
|
||||
lzply_deep_repair [-l max-level 0..3] [--time-budget seconds] [-v]
|
||||
[-o outdir] [--entry name] archive
|
||||
```
|
||||
|
||||
- L0: standard decode to t.
|
||||
- L1: Chase-1 — single-bit trial flips (suspects first, then an
|
||||
exhaustive scan). Recovers t+1 essentially always: flipping any
|
||||
one true error leaves t errors, which Berlekamp-Massey corrects.
|
||||
Measured 10/10 at t+1 on 512-byte blocks (t=8), 5/5 on 2 KiB
|
||||
blocks, in 0.03–0.28 s.
|
||||
- L2: Chase-2 — two-bit trial flips over a bounded first-element
|
||||
list (suspects, then a positional prefix, at most 128 entries)
|
||||
paired with every position: at most 128·nbits trials, plus a
|
||||
wall-clock deadline. Measured 3/10 at t+2 on 512-byte blocks
|
||||
(t=8), ~3.9 s each; the rate scales with the list size, roughly
|
||||
1 − (1 − (t+2)/nbits)^128.
|
||||
- L3: cross-block list decoding — two failing blocks varied at
|
||||
once from retained per-block candidate pools (at most 256 blob
|
||||
tries). Lands when each of two blocks holds its true data in
|
||||
the pool but neither single-block variation passes the CRC.
|
||||
|
||||
The CRC16 is the oracle: every beyond-t candidate is CRC-verified
|
||||
before acceptance (then decompressed and SHA-256-checked); the
|
||||
tool reports candidates tried, CRC rejections, and the accepted
|
||||
repair. Expected residual false-accept is ~2^-16 per candidate.
|
||||
Measured across the corruption matrix: 1,162 candidates
|
||||
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
|
||||
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
|
||||
word (Chase-1 recovered 0/20 before the fix), and L1 pooled
|
||||
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`
|
||||
(round-trips, old-format rejection, corruption matrix,
|
||||
false-accept measurement).
|
||||
|
||||
On NVIDIA GPUs the Chase-1 scan runs on CUDA instead — 453–512x
|
||||
faster with bit-identical candidates; see "CUDA acceleration" below.
|
||||
|
||||
## CUDA acceleration
|
||||
|
||||
Optional: built only when `nvcc` is present (CUDA 13.x); without it
|
||||
the CPU path is unchanged and nothing is lost.
|
||||
|
||||
* **CUDA BCH remainder** (`bch_cuda.cu`, `bch_cuda_test.c`): the
|
||||
remainder computation that dominates `-e7` encode moves to the
|
||||
GPU — t=32 runs 1,094 MB/s vs 22.8 MB/s on the CPU (48x), and a
|
||||
full `-e7` encode drops from 2.439 s to 0.571 s (4.3x end to end).
|
||||
Verified by `bch_cuda_test`: 612 checks, 0 fails.
|
||||
* **CUDA Chase-1** (`chase_cuda.cu`, `CHASE_CUDA.md`): the
|
||||
deep-repair Chase-1 scan (one CUDA thread per trial position,
|
||||
Berlekamp-Massey + the lambda-splits test in-kernel) — 453–512x
|
||||
vs the CPU scan (171.571 s -> 0.335–0.379 s on a 524 KiB block,
|
||||
m=22, t=8) with bit-identical candidate sets (same hash, same
|
||||
candidates, same order) across 5 patterns, and 453–562x across a
|
||||
24-pattern sweep with 10/10 CPU/CUDA hash agreements. t=8 only;
|
||||
Chase-2 is not ported. Benchmark with `chase_bench_cuda`
|
||||
(vs `chase_bench_cpu`).
|
||||
|
||||
Write-ups: [171 seconds to a third of a second: deep-repair Chase on CUDA runs 500x faster](https://www.lzply.com/cuda-chase-500x-deep-repair/) and [GPU day: BCH, zseg, and the mixer that said no](https://www.lzply.com/gpu-day-bch-zseg-mixer-no/) (which also covers the segment-parallel zpaq driver, now in [lzpaq](https://github.com/cnmcdee/lzpaq), and the zpaq context-mixer GPU port — a negative: per-bit sequential dependencies, 32–64 MB of mutating tables).
|
||||
|
||||
## Building
|
||||
|
||||
```sh
|
||||
apt install build-essential liblz-dev # Debian/Ubuntu
|
||||
make # produces ./lzply, ./lzply_mount, ./lzply_stat, ./lzply_heal, ./lzply_check, ./lzply_refresh
|
||||
make test # BCH unit tests + full archive test suite
|
||||
sudo make install # /usr/local/bin/lzply*, /sbin/mount.lzply
|
||||
make # produces ./lzply, ./lz_rs, ./lzply_mount, ./lzply_stat, ./lzply_heal, ./lzply_check, ./lzply_refresh, ./lzply_deep_repair
|
||||
make test # BCH + RS + CRC16 unit tests + full archive test suites (lzply + lz_rs + deep repair)
|
||||
sudo make install # /usr/local/bin/lzply* (including lz_rs), /sbin/mount.lzply
|
||||
```
|
||||
|
||||
## Usage
|
||||
@@ -351,7 +468,37 @@ 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`).
|
||||
|
||||
## Limitations (v4)
|
||||
## 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`.
|
||||
|
||||
Write-up with the measured tables: [Four new defences, measured](https://www.lzply.com/four-new-defences-measured/).
|
||||
|
||||
## Limitations (v5)
|
||||
|
||||
* Whole files are buffered in memory (compress, BCH, and
|
||||
the archive entry). A 50 MiB file is fine; multi-gigabyte files
|
||||
@@ -633,3 +780,25 @@ 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.
|
||||
|
||||
Phase 2 (`randfec/PHASE2.md`, `PHASE3.md`, `PHASE4.md`) took three
|
||||
further shots at a better lzply: **GRAND-MO** — noise guesses
|
||||
ordered by a burst model fitted to real archive damage — beats
|
||||
Berlekamp-Massey (e.g. 89.78 -> 97.48 repair rate on burst damage);
|
||||
a **RaptorQ outer layer** ties Reed-Solomon everywhere (max gap
|
||||
0.06 points over 350,300 trials) and wins nowhere; and the **CRC
|
||||
polynomial swap** buys nothing under an ML decoder (within +/-0.35
|
||||
points at n<=32, worse at (64,48,16)). Short LDPC was a dead end
|
||||
too — no per-bit reliability signal exists in lzply's channel.
|
||||
Write-up: [Three shots at a better lzply](https://www.lzply.com/three-shots-at-a-better-lzply/).
|
||||
Research only — nothing integrated into lzply core.
|
||||
@@ -39,8 +39,44 @@
|
||||
*/
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
#include "bch.h"
|
||||
|
||||
/* CUDA fast path (bch_cuda.cu, linked only when built with nvcc).
|
||||
* Without nvcc the Makefile links bch_cuda_stub.c, which defines
|
||||
* these three functions to report "no GPU", so a CPU-only build
|
||||
* always takes the CPU path below. The declarations are also marked
|
||||
* weak, so an out-of-tree consumer that links bch.o without either
|
||||
* object still resolves them to NULL on linkers that support that
|
||||
* (GNU ld does; macOS ld64 does not -- the stub is what the build
|
||||
* relies on). bch_cuda_encode returns the stored length or 0
|
||||
* on failure; bch_cuda_decode returns 0, -1 (uncorrectable) or -2
|
||||
* (internal error). Any CUDA failure falls through to the CPU path,
|
||||
* which re-verifies, so results are identical with or without a GPU. */
|
||||
extern size_t bch_cuda_encode(const uint8_t *, size_t, const bch_poly_t *,
|
||||
uint8_t *) __attribute__((weak));
|
||||
extern int bch_cuda_decode(const uint8_t *, size_t, size_t,
|
||||
const bch_poly_t *, uint8_t *,
|
||||
int *) __attribute__((weak));
|
||||
extern int bch_cuda_available(void) __attribute__((weak));
|
||||
|
||||
/* Minimum blob size for the GPU path, by t. A fresh process pays
|
||||
* ~0.12 s of CUDA first-touch cost (context creation + first
|
||||
* cudaMalloc, measured on hot_house) before any kernel runs, so the
|
||||
* GPU only wins once the CPU remainder time exceeds that: t=8 runs
|
||||
* ~87 MB/s on the CPU (break-even ~12 MB), t=32 ~23 MB/s
|
||||
* (break-even ~3 MB). The thresholds are deliberately conservative
|
||||
* and, critically, are checked BEFORE any CUDA call, so small blobs
|
||||
* never pay the init cost at all. */
|
||||
static size_t bch_cuda_min_len(int t)
|
||||
{
|
||||
if (t >= 32)
|
||||
return 4u << 20;
|
||||
if (t >= 16)
|
||||
return 8u << 20;
|
||||
return 16u << 20;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* polynomial lookup */
|
||||
/* ------------------------------------------------------------------ */
|
||||
@@ -318,15 +354,22 @@ static uint32_t gf_pow_slow(uint32_t a, uint32_t e, uint32_t P, int m)
|
||||
|
||||
/* (gf_inv via the log/exp tables is used instead; see gf_div_tab.) */
|
||||
|
||||
/* log/exp tables, cached per m (single slot; lzply is single-threaded). */
|
||||
/* log/exp tables, cached per m (single slot; lzply is single-threaded).
|
||||
* For large m the tables (2^m entries each) stop fitting in cache and
|
||||
* random table lookups cost more than the shift-and-xor multiply, so
|
||||
* gf_mul_tab dispatches to gf_mul_slow when slow is set (m >= 17,
|
||||
* tables >= 1 MiB). Both compute the same field multiplication;
|
||||
* only the speed differs. */
|
||||
typedef struct {
|
||||
int m;
|
||||
uint32_t N; /* 2^m - 1 */
|
||||
uint32_t P; /* primitive polynomial for this m */
|
||||
int slow; /* use gf_mul_slow instead of the tables */
|
||||
uint32_t *exp; /* exp[i] = alpha^i, i = 0..N-1 */
|
||||
uint32_t *log; /* log[v] = i with alpha^i = v, v = 1..N-1 */
|
||||
} gf_tables_t;
|
||||
|
||||
static gf_tables_t gf_cache = { 0, 0, NULL, NULL };
|
||||
static gf_tables_t gf_cache = { 0, 0, 0, 0, NULL, NULL };
|
||||
|
||||
static const gf_tables_t *gf_tables_for(int m)
|
||||
{
|
||||
@@ -335,6 +378,8 @@ static const gf_tables_t *gf_tables_for(int m)
|
||||
free(gf_cache.exp);
|
||||
free(gf_cache.log);
|
||||
gf_cache.m = 0;
|
||||
gf_cache.P = 0;
|
||||
gf_cache.slow = 0;
|
||||
gf_cache.exp = NULL;
|
||||
gf_cache.log = NULL;
|
||||
uint32_t P = bch_prim_poly[m];
|
||||
@@ -357,6 +402,8 @@ static const gf_tables_t *gf_tables_for(int m)
|
||||
log[0] = 0;
|
||||
gf_cache.m = m;
|
||||
gf_cache.N = N;
|
||||
gf_cache.P = P;
|
||||
gf_cache.slow = (m >= 17);
|
||||
gf_cache.exp = exp;
|
||||
gf_cache.log = log;
|
||||
return &gf_cache;
|
||||
@@ -366,6 +413,8 @@ static uint32_t gf_mul_tab(uint32_t a, uint32_t b, const gf_tables_t *t)
|
||||
{
|
||||
if (!a || !b)
|
||||
return 0;
|
||||
if (t->slow)
|
||||
return gf_mul_slow(a, b, t->P, t->m);
|
||||
uint32_t s = t->log[a] + t->log[b];
|
||||
if (s >= t->N)
|
||||
s -= t->N;
|
||||
@@ -600,6 +649,13 @@ size_t bch_encode(const uint8_t *data, size_t len, const bch_poly_t *p,
|
||||
bch_encode_block(data, 0, p, out);
|
||||
return bch_block_stored_len(0, p);
|
||||
}
|
||||
if (len >= bch_cuda_min_len(p->t) && bch_cuda_available &&
|
||||
bch_cuda_available()) {
|
||||
size_t n = bch_cuda_encode(data, len, p, out);
|
||||
if (n != 0)
|
||||
return n;
|
||||
/* fall through to the CPU path on any CUDA failure */
|
||||
}
|
||||
while (off < len) {
|
||||
size_t chunk = len - off;
|
||||
if (chunk > maxd)
|
||||
@@ -629,6 +685,13 @@ int bch_decode(const uint8_t *in, size_t len, size_t orig_len,
|
||||
*corrected = c1;
|
||||
return 0;
|
||||
}
|
||||
if (orig_len >= bch_cuda_min_len(p->t) && bch_cuda_available &&
|
||||
bch_cuda_available()) {
|
||||
if (bch_cuda_decode(in, len, orig_len, p, out, corrected) == 0)
|
||||
return 0;
|
||||
/* fall through to the CPU path on any CUDA failure or
|
||||
* uncorrectable result (the CPU path re-verifies) */
|
||||
}
|
||||
while (off < orig_len) {
|
||||
size_t chunk = orig_len - off;
|
||||
if (chunk > maxd)
|
||||
@@ -1005,3 +1068,811 @@ int bch_decode_candidates(const uint8_t *in, size_t len, size_t orig_len,
|
||||
free(bslen);
|
||||
return nc;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Deep repair: Chase / list decoding past t (see bch.h). */
|
||||
/* */
|
||||
/* A trial flip at bit position p changes the syndrome by the */
|
||||
/* column col(p): S_j ^= alpha^(j*(n-1-p)). A trial is GOOD iff the */
|
||||
/* BM locator for the flipped syndrome splits completely over */
|
||||
/* GF(2^m) with all roots at in-range positions and the corrected */
|
||||
/* word has zero remainder. The splitting test (gcd with */
|
||||
/* x^(2^m) - x) costs O(m*t^2) per trial versus O(n*t) for Chien, */
|
||||
/* so it filters trials cheaply and Chien runs only for survivors. */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
double bch_now(void)
|
||||
{
|
||||
struct timespec ts;
|
||||
clock_gettime(CLOCK_MONOTONIC, &ts);
|
||||
return (double)ts.tv_sec + (double)ts.tv_nsec / 1e9;
|
||||
}
|
||||
|
||||
/* Berlekamp-Massey on S_1..S_2t, using the log/exp tables. Same
|
||||
* arithmetic as berlekamp_massey (exact same result), faster.
|
||||
* Returns the degree L and fills lambda[0..L] (lambda[0]=1). */
|
||||
static int berlekamp_massey_tab(const uint32_t *S, int t, int m,
|
||||
const gf_tables_t *tab, uint32_t *lambda)
|
||||
{
|
||||
(void)m; /* the field is fully described by tab */
|
||||
uint32_t C[33], B[33], T[33];
|
||||
for (int i = 0; i <= 32; 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 < 2 * t; n++) {
|
||||
/* discrepancy d = S_{n+1} + sum_{i=1..L} C_i * S_{n+1-i} */
|
||||
uint32_t d = S[n];
|
||||
for (int i = 1; i <= L; i++) {
|
||||
if (C[i] && n - i >= 0)
|
||||
d ^= gf_mul_tab(C[i], S[n - i], tab);
|
||||
}
|
||||
if (d == 0) {
|
||||
shift++;
|
||||
continue;
|
||||
}
|
||||
memcpy(T, C, sizeof(T));
|
||||
uint32_t coef = gf_div_tab(d, b, tab);
|
||||
/* C = C + coef * x^shift * B */
|
||||
for (int i = 0; i <= 32 - shift; i++) {
|
||||
if (B[i])
|
||||
C[i + shift] ^= gf_mul_tab(coef, B[i], tab);
|
||||
}
|
||||
if (2 * L <= n) {
|
||||
L = n + 1 - L;
|
||||
memcpy(B, T, sizeof(B));
|
||||
b = d;
|
||||
shift = 1;
|
||||
} else {
|
||||
shift++;
|
||||
}
|
||||
}
|
||||
for (int i = 0; i <= L; i++)
|
||||
lambda[i] = C[i];
|
||||
return L;
|
||||
}
|
||||
|
||||
/* Degree of a polynomial (highest nonzero coefficient), -1 if zero.
|
||||
* Coefficients are co[0..maxd]. */
|
||||
static int poly_deg(const uint32_t *a, int maxd)
|
||||
{
|
||||
for (int i = maxd; i >= 0; i--)
|
||||
if (a[i])
|
||||
return i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Reduce prod (degree <= 2L-2) modulo the monic polynomial mod[0..L]
|
||||
* (mod[L] == 1, only mod[0..L-1] are read). In place. */
|
||||
static void poly_reduce(uint32_t *prod, int L, const uint32_t *mod,
|
||||
const gf_tables_t *tab)
|
||||
{
|
||||
for (int k = 2 * L - 2; k >= L; k--) {
|
||||
uint32_t c = prod[k];
|
||||
if (!c)
|
||||
continue;
|
||||
prod[k] = 0;
|
||||
for (int j = 0; j < L; j++)
|
||||
if (mod[j])
|
||||
prod[k - L + j] ^= gf_mul_tab(c, mod[j], tab);
|
||||
}
|
||||
}
|
||||
|
||||
/* Square a (degree < L) modulo mod: in characteristic 2,
|
||||
* (sum a_i x^i)^2 = sum a_i^2 x^{2i}. out[0..L-1]. */
|
||||
static void poly_square_mod(const uint32_t *a, int L, const uint32_t *mod,
|
||||
const gf_tables_t *tab, uint32_t *out)
|
||||
{
|
||||
uint32_t prod[65];
|
||||
memset(prod, 0, sizeof prod);
|
||||
for (int i = 0; i < L; i++)
|
||||
if (a[i])
|
||||
prod[2 * i] ^= gf_mul_tab(a[i], a[i], tab);
|
||||
poly_reduce(prod, L, mod, tab);
|
||||
memset(out, 0, (size_t)33 * sizeof(uint32_t));
|
||||
memcpy(out, prod, (size_t)L * sizeof(uint32_t));
|
||||
}
|
||||
|
||||
/* Remainder of a (degree da) divided by b (degree db). out gets the
|
||||
* remainder (degree < db). */
|
||||
static void poly_rem(const uint32_t *a, int da, const uint32_t *b, int db,
|
||||
const gf_tables_t *tab, uint32_t *out)
|
||||
{
|
||||
uint32_t r[33];
|
||||
memset(r, 0, sizeof r);
|
||||
memcpy(r, a, (size_t)(da + 1) * sizeof(uint32_t));
|
||||
for (int i = da; i >= db; i--) {
|
||||
uint32_t f;
|
||||
if (!r[i])
|
||||
continue;
|
||||
f = gf_div_tab(r[i], b[db], tab);
|
||||
r[i] = 0;
|
||||
for (int j = 0; j < db; j++)
|
||||
if (b[j])
|
||||
r[i - db + j] ^= gf_mul_tab(f, b[j], tab);
|
||||
}
|
||||
memset(out, 0, (size_t)33 * sizeof(uint32_t));
|
||||
memcpy(out, r, (size_t)(db > 0 ? db : 0) * sizeof(uint32_t));
|
||||
}
|
||||
|
||||
/* gcd of a (degree da) and b (degree db). Returns the degree in
|
||||
* *dout, coefficients in out[0..dout]. */
|
||||
static void poly_gcd(const uint32_t *a, int da, const uint32_t *b, int db,
|
||||
const gf_tables_t *tab, uint32_t *out, int *dout)
|
||||
{
|
||||
uint32_t x[33], y[33], r[33];
|
||||
int dx, dy;
|
||||
memset(x, 0, sizeof x);
|
||||
memset(y, 0, sizeof y);
|
||||
memcpy(x, a, (size_t)(da + 1) * sizeof(uint32_t));
|
||||
memcpy(y, b, (size_t)(db + 1) * sizeof(uint32_t));
|
||||
dx = da;
|
||||
dy = db;
|
||||
for (;;) {
|
||||
int dr;
|
||||
if (dy < 0) { /* y is zero: gcd is x */
|
||||
memcpy(out, x, sizeof(uint32_t) * (size_t)(dx + 1));
|
||||
*dout = dx;
|
||||
return;
|
||||
}
|
||||
if (dy == 0) { /* y is a nonzero constant: gcd is 1 */
|
||||
out[0] = 1;
|
||||
*dout = 0;
|
||||
return;
|
||||
}
|
||||
if (dx < dy) { /* keep deg x >= deg y */
|
||||
uint32_t t[33];
|
||||
int td = dx;
|
||||
memcpy(t, x, sizeof t);
|
||||
memcpy(x, y, sizeof x);
|
||||
dx = dy;
|
||||
memcpy(y, t, sizeof y);
|
||||
dy = td;
|
||||
}
|
||||
poly_rem(x, dx, y, dy, tab, r);
|
||||
dr = poly_deg(r, dy - 1);
|
||||
if (dr < 0) { /* y divides x: gcd is y */
|
||||
memcpy(out, y, sizeof(uint32_t) * (size_t)(dy + 1));
|
||||
*dout = dy;
|
||||
return;
|
||||
}
|
||||
memcpy(x, y, sizeof x);
|
||||
dx = dy;
|
||||
memcpy(y, r, sizeof y);
|
||||
dy = dr;
|
||||
}
|
||||
}
|
||||
|
||||
/* Does the monic locator lambda[0..L] (lambda[L] == 1) split
|
||||
* completely into L distinct linear factors over GF(2^m)?
|
||||
* Computes g = gcd(lambda, x^(2^m) - x); splits iff deg g == L.
|
||||
* x^(2^m) mod lambda comes from m repeated squarings of x. */
|
||||
static int lambda_splits(const uint32_t *lambda, int L, int m,
|
||||
const gf_tables_t *tab)
|
||||
{
|
||||
uint32_t cur[33], nxt[33], h[33], g[33];
|
||||
int dg, dh;
|
||||
if (L <= 1)
|
||||
return 1; /* degree 0/1 always splits */
|
||||
/* cur = x mod lambda */
|
||||
memset(cur, 0, sizeof cur);
|
||||
cur[1] = 1;
|
||||
for (int i = 0; i < m; i++) {
|
||||
poly_square_mod(cur, L, lambda, tab, nxt);
|
||||
memcpy(cur, nxt, sizeof cur);
|
||||
}
|
||||
/* h = cur - x = x^(2^m) - x mod lambda */
|
||||
memcpy(h, cur, sizeof h);
|
||||
h[1] ^= 1;
|
||||
dh = poly_deg(h, L - 1);
|
||||
poly_gcd(lambda, L, h, dh, tab, g, &dg);
|
||||
return dg == L;
|
||||
}
|
||||
|
||||
/* Chien search: evaluate lambda at x_p = alpha^(p-(n-1)) for
|
||||
* p = 0..nbits-1; record the positions where it vanishes (up to
|
||||
* maxpos). Returns the number found. lambda[0..L]. */
|
||||
static int chien_positions(const uint32_t *lambda, int L, size_t nbits,
|
||||
const gf_tables_t *tab, size_t *positions,
|
||||
int maxpos)
|
||||
{
|
||||
uint32_t N = tab->N;
|
||||
uint32_t x0 = tab->exp[(N - (nbits - 1) % N) % N]; /* alpha^-(n-1) */
|
||||
uint32_t v[33];
|
||||
uint32_t ajpow[33];
|
||||
uint32_t xp = 1;
|
||||
int found = 0;
|
||||
for (int j = 0; j <= L; j++) {
|
||||
/* v[j] = lambda[j] * x0^j */
|
||||
v[j] = lambda[j] ? gf_mul_tab(lambda[j], xp, tab) : 0;
|
||||
xp = gf_mul_tab(xp, x0, tab);
|
||||
ajpow[j] = tab->exp[j % N];
|
||||
}
|
||||
for (size_t p = 0; p < nbits && found < L; p++) {
|
||||
uint32_t sum = 0;
|
||||
for (int j = 0; j <= L; j++)
|
||||
sum ^= v[j];
|
||||
if (sum == 0) {
|
||||
if (found < maxpos)
|
||||
positions[found] = p;
|
||||
found++;
|
||||
}
|
||||
/* advance to p+1: v[j] *= alpha^j */
|
||||
for (int j = 1; j <= L; j++)
|
||||
if (v[j])
|
||||
v[j] = gf_mul_tab(v[j], ajpow[j], tab);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/* Syndromes S_j = R(alpha^j) * alpha^(-j*r), j = 1..2t, from the
|
||||
* received word. Returns 0 with S filled, 1 if the remainder is
|
||||
* zero (no errors), -1 on bad input. */
|
||||
static int compute_syndrome(const uint8_t *in, size_t in_len, size_t data_len,
|
||||
const bch_poly_t *p, bch_ctx_t *ctx,
|
||||
const gf_tables_t *tab, uint32_t *S)
|
||||
{
|
||||
int r = p->r, m = p->m, t = p->t;
|
||||
uint32_t P = bch_prim_poly[m];
|
||||
uint32_t N = (1u << m) - 1;
|
||||
int nb = (r + 7) / 8;
|
||||
size_t stored = bch_block_stored_len(data_len, p);
|
||||
if (in_len != stored)
|
||||
return -1;
|
||||
uint8_t *rem = malloc(nb);
|
||||
if (!rem)
|
||||
return -1;
|
||||
rem_of_codeword(in, data_len, in + data_len, ctx, rem);
|
||||
if (rem_is_zero(rem, nb)) {
|
||||
free(rem);
|
||||
return 1;
|
||||
}
|
||||
for (int j = 1; j <= 2 * t; j++) {
|
||||
uint32_t aj = tab->exp[j % N];
|
||||
uint32_t v = rem_eval(rem, r, aj, P, m);
|
||||
uint32_t e = (uint32_t)(((uint64_t)j * (uint64_t)r) % N);
|
||||
uint32_t inv = (e == 0) ? 1 : tab->exp[N - e];
|
||||
S[j - 1] = gf_mul_tab(v, inv, tab);
|
||||
}
|
||||
free(rem);
|
||||
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,
|
||||
uint32_t *col)
|
||||
{
|
||||
uint32_t N = tab->N;
|
||||
uint32_t K = (uint32_t)(nbits - 1 - pos);
|
||||
for (int j = 1; j <= 2 * t; j++)
|
||||
col[j - 1] = tab->exp[(uint32_t)(((uint64_t)j * K) % N)];
|
||||
}
|
||||
|
||||
/* One Chase trial: syndrome S (2t entries) for a word that differs
|
||||
* from the received word by the trial flip(s) `flips[0..nflips-1]`.
|
||||
* Run BM, the complete-splitting filter, Chien, and the
|
||||
* zero-remainder check. The corrected word is the received word
|
||||
* with BOTH the trial flips AND the Chien roots flipped -- the
|
||||
* trial flips are part of the correction, not just a syndrome
|
||||
* tweak. On success, copy the decoded data bytes to out and
|
||||
* return 1. Stats: trials, split_pass, codewords. */
|
||||
static int chase_trial(const uint32_t *S, const uint8_t *in, size_t in_len,
|
||||
size_t data_len, const bch_poly_t *p,
|
||||
const size_t *flips, int nflips,
|
||||
const gf_tables_t *tab, bch_ctx_t *ctx,
|
||||
uint8_t *out, bch_chase_stats_t *st)
|
||||
{
|
||||
int t = p->t, m = p->m;
|
||||
size_t nbits = (size_t)8 * data_len + (size_t)p->r;
|
||||
int nb = (p->r + 7) / 8;
|
||||
uint32_t lambda[33], mono[33];
|
||||
int L = berlekamp_massey_tab(S, t, m, tab, lambda);
|
||||
st->trials++;
|
||||
if (L < 0 || L > t)
|
||||
return 0;
|
||||
/* Normalize to monic for the splitting test (roots are
|
||||
* scale-invariant, so Chien may use the normalized form too). */
|
||||
{
|
||||
uint32_t inv = gf_div_tab(1, lambda[L], tab);
|
||||
for (int i = 0; i <= L; i++)
|
||||
mono[i] = gf_mul_tab(lambda[i], inv, tab);
|
||||
}
|
||||
if (!lambda_splits(mono, L, m, tab))
|
||||
return 0;
|
||||
st->split_pass++;
|
||||
{
|
||||
size_t *pos = malloc(sizeof(size_t) * (size_t)(L > 0 ? L : 1));
|
||||
uint8_t *work, *rem;
|
||||
int found, ok;
|
||||
if (!pos)
|
||||
return 0;
|
||||
found = chien_positions(mono, L, nbits, tab, pos, L);
|
||||
if (found != L) {
|
||||
free(pos);
|
||||
return 0;
|
||||
}
|
||||
work = malloc(in_len);
|
||||
if (!work) {
|
||||
free(pos);
|
||||
return 0;
|
||||
}
|
||||
memcpy(work, in, in_len);
|
||||
/* The trial flips AND the Chien roots are both part of the
|
||||
* correction: the trial flips produced the syndrome S, and
|
||||
* the Chien roots are the remaining errors in that
|
||||
* trial-flipped word. */
|
||||
for (int i = 0; i < nflips; i++)
|
||||
flip_bit_at(work, flips[i]);
|
||||
for (int i = 0; i < found; i++)
|
||||
flip_bit_at(work, pos[i]);
|
||||
free(pos);
|
||||
rem = malloc(nb);
|
||||
if (!rem) {
|
||||
free(work);
|
||||
return 0;
|
||||
}
|
||||
rem_of_codeword(work, data_len, work + data_len, ctx, rem);
|
||||
ok = rem_is_zero(rem, nb);
|
||||
free(rem);
|
||||
if (!ok) {
|
||||
free(work);
|
||||
return 0;
|
||||
}
|
||||
st->codewords++;
|
||||
memcpy(out, work, data_len);
|
||||
free(work);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
/* Add v to pos[0..n-1] if not already present and room remains.
|
||||
* Returns the new count. */
|
||||
static int pos_add(size_t *pos, int n, int max_pos, size_t v)
|
||||
{
|
||||
int i;
|
||||
if (n >= max_pos)
|
||||
return n;
|
||||
for (i = 0; i < n; i++)
|
||||
if (pos[i] == v)
|
||||
return n;
|
||||
pos[n++] = v;
|
||||
return n;
|
||||
}
|
||||
|
||||
int bch_suspect_positions(const uint8_t *in, size_t in_len, size_t data_len,
|
||||
const bch_poly_t *p, size_t *pos, int max_pos)
|
||||
{
|
||||
size_t nbits;
|
||||
size_t *E, *D;
|
||||
int n = 0, L, Ld = -1;
|
||||
if (max_pos <= 0 || !pos || !p)
|
||||
return 0;
|
||||
nbits = (size_t)8 * data_len + (size_t)p->r;
|
||||
E = malloc(sizeof(size_t) * 33);
|
||||
D = malloc(sizeof(size_t) * 33);
|
||||
if (!E || !D) {
|
||||
free(E);
|
||||
free(D);
|
||||
return 0;
|
||||
}
|
||||
L = find_errors_in(in, in_len, data_len, p, E);
|
||||
if (L > 0) {
|
||||
uint8_t *Rp = malloc(in_len);
|
||||
if (Rp) {
|
||||
int i;
|
||||
memcpy(Rp, in, in_len);
|
||||
for (i = 0; i < L; i++)
|
||||
flip_bit_at(Rp, E[i]);
|
||||
Ld = find_errors_in(Rp, in_len, data_len, p, D);
|
||||
free(Rp);
|
||||
}
|
||||
}
|
||||
if (L > 0) {
|
||||
int i, j;
|
||||
for (i = 0; i < L; i++)
|
||||
n = pos_add(pos, n, max_pos, E[i]);
|
||||
for (j = 0; j < Ld; j++)
|
||||
n = pos_add(pos, n, max_pos, D[j]);
|
||||
for (i = 0; i < L; i++) {
|
||||
if (E[i] > 0)
|
||||
n = pos_add(pos, n, max_pos, E[i] - 1);
|
||||
if (E[i] + 1 < nbits)
|
||||
n = pos_add(pos, n, max_pos, E[i] + 1);
|
||||
}
|
||||
}
|
||||
free(E);
|
||||
free(D);
|
||||
return n;
|
||||
}
|
||||
|
||||
/* Shared Chase setup: returns 0 with *ctx_out, *tab_out, *S_out
|
||||
* (2t syndromes) filled, or -1. The caller frees ctx and S.
|
||||
* Returns 1 when there is nothing to chase (standard decode
|
||||
* already succeeds, or the word is clean). */
|
||||
static int chase_setup(const uint8_t *in, size_t in_len, size_t data_len,
|
||||
const bch_poly_t *p, bch_ctx_t **ctx_out,
|
||||
const gf_tables_t **tab_out, uint32_t **S_out)
|
||||
{
|
||||
int t = p->t, m = p->m;
|
||||
size_t stored = bch_block_stored_len(data_len, p);
|
||||
bch_ctx_t *ctx;
|
||||
const gf_tables_t *tab;
|
||||
uint32_t *S;
|
||||
if (in_len != stored)
|
||||
return -1;
|
||||
{
|
||||
/* Nothing to chase when the standard decoder succeeds. */
|
||||
uint8_t *dec = malloc(data_len ? data_len : 1);
|
||||
if (!dec)
|
||||
return -1;
|
||||
if (bch_decode_block(in, in_len, data_len, p, dec, NULL) == 0) {
|
||||
free(dec);
|
||||
return 1;
|
||||
}
|
||||
free(dec);
|
||||
}
|
||||
ctx = bch_ctx_new(p);
|
||||
if (!ctx)
|
||||
return -1;
|
||||
tab = gf_tables_for(m);
|
||||
if (!tab) {
|
||||
bch_ctx_free(ctx);
|
||||
return -1;
|
||||
}
|
||||
S = malloc(sizeof(uint32_t) * (size_t)(2 * t > 0 ? 2 * t : 1));
|
||||
if (!S) {
|
||||
bch_ctx_free(ctx);
|
||||
return -1;
|
||||
}
|
||||
if (compute_syndrome(in, in_len, data_len, p, ctx, tab, S) != 0) {
|
||||
free(S);
|
||||
bch_ctx_free(ctx);
|
||||
return 1; /* clean word: nothing to chase */
|
||||
}
|
||||
*ctx_out = ctx;
|
||||
*tab_out = tab;
|
||||
*S_out = S;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int bch_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)
|
||||
{
|
||||
bch_chase_stats_t dummy;
|
||||
bch_ctx_t *ctx = NULL;
|
||||
const gf_tables_t *tab = NULL;
|
||||
uint32_t *S = NULL, *Sp = NULL, *col = NULL;
|
||||
uint8_t *out = NULL;
|
||||
int t, m, nc = 0, rc;
|
||||
size_t nbits;
|
||||
if (!stats)
|
||||
stats = &dummy;
|
||||
memset(stats, 0, sizeof *stats);
|
||||
if (!in || !p || !cands)
|
||||
return -1;
|
||||
if (max_cands <= 0)
|
||||
return 0;
|
||||
if (max_cands > BCH_CHASE_MAX_CANDS)
|
||||
max_cands = BCH_CHASE_MAX_CANDS;
|
||||
t = p->t;
|
||||
m = p->m;
|
||||
nbits = (size_t)8 * data_len + (size_t)p->r;
|
||||
rc = chase_setup(in, in_len, data_len, p, &ctx, &tab, &S);
|
||||
if (rc != 0)
|
||||
return rc < 0 ? -1 : 0;
|
||||
Sp = malloc(sizeof(uint32_t) * (size_t)(2 * t > 0 ? 2 * t : 1));
|
||||
col = malloc(sizeof(uint32_t) * (size_t)(2 * t > 0 ? 2 * t : 1));
|
||||
out = malloc(data_len ? data_len : 1);
|
||||
if (!Sp || !col || !out) {
|
||||
free(Sp);
|
||||
free(col);
|
||||
free(out);
|
||||
free(S);
|
||||
bch_ctx_free(ctx);
|
||||
return -1;
|
||||
}
|
||||
/* Phase A: suspect positions first (direct columns). */
|
||||
{
|
||||
int si;
|
||||
for (si = 0; si < nsuspects && nc < max_cands; si++) {
|
||||
size_t s = suspects ? suspects[si] : 0;
|
||||
int j;
|
||||
if (!suspects || s >= nbits)
|
||||
continue;
|
||||
col_at(s, nbits, t, tab, col);
|
||||
for (j = 0; j < 2 * t; j++)
|
||||
Sp[j] = S[j] ^ col[j];
|
||||
if (chase_trial(Sp, in, in_len, data_len, p, &s, 1, tab, ctx,
|
||||
out, stats) &&
|
||||
!cand_seen(cands, nc, data_len, out)) {
|
||||
memcpy(cands + (size_t)nc * data_len, out, data_len);
|
||||
nc++;
|
||||
}
|
||||
if (deadline >= 0 && bch_now() > deadline) {
|
||||
stats->partial = 1;
|
||||
goto done;
|
||||
}
|
||||
}
|
||||
}
|
||||
/* Phase B: exhaustive ascending scan with incremental columns.
|
||||
* cur[j] = alpha^(j*K) for the current position (K = n-1-p);
|
||||
* each step multiplies by alpha^(-j). */
|
||||
{
|
||||
uint32_t *cur = malloc(sizeof(uint32_t) *
|
||||
(size_t)(2 * t > 0 ? 2 * t : 1));
|
||||
uint32_t *step = malloc(sizeof(uint32_t) *
|
||||
(size_t)(2 * t > 0 ? 2 * t : 1));
|
||||
uint32_t N;
|
||||
size_t pp;
|
||||
int j;
|
||||
if (!cur || !step) {
|
||||
free(cur);
|
||||
free(step);
|
||||
free(Sp);
|
||||
free(col);
|
||||
free(out);
|
||||
free(S);
|
||||
bch_ctx_free(ctx);
|
||||
return -1;
|
||||
}
|
||||
N = tab->N;
|
||||
for (j = 1; j <= 2 * t; j++) {
|
||||
cur[j - 1] = tab->exp[(uint32_t)(((uint64_t)j * (nbits - 1)) % N)];
|
||||
step[j - 1] = tab->exp[(N - (uint32_t)j) % N]; /* alpha^-j */
|
||||
}
|
||||
for (pp = 0; pp < nbits && nc < max_cands; pp++) {
|
||||
int is_suspect = 0;
|
||||
int si;
|
||||
for (si = 0; si < nsuspects; si++)
|
||||
if (suspects && suspects[si] == pp) {
|
||||
is_suspect = 1;
|
||||
break;
|
||||
}
|
||||
if (!is_suspect) {
|
||||
for (j = 0; j < 2 * t; j++)
|
||||
Sp[j] = S[j] ^ cur[j];
|
||||
if (chase_trial(Sp, in, in_len, data_len, p, &pp, 1, tab, ctx,
|
||||
out, stats) &&
|
||||
!cand_seen(cands, nc, data_len, out)) {
|
||||
memcpy(cands + (size_t)nc * data_len, out, data_len);
|
||||
nc++;
|
||||
}
|
||||
}
|
||||
for (j = 0; j < 2 * t; j++)
|
||||
cur[j] = gf_mul_tab(cur[j], step[j], tab);
|
||||
if (deadline >= 0 && (pp & 255) == 0 && bch_now() > deadline) {
|
||||
stats->partial = 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
free(cur);
|
||||
free(step);
|
||||
}
|
||||
done:
|
||||
stats->candidates = nc;
|
||||
free(Sp);
|
||||
free(col);
|
||||
free(out);
|
||||
free(S);
|
||||
bch_ctx_free(ctx);
|
||||
(void)m;
|
||||
return nc;
|
||||
}
|
||||
|
||||
int bch_chase2_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)
|
||||
{
|
||||
bch_chase_stats_t dummy;
|
||||
bch_ctx_t *ctx = NULL;
|
||||
const gf_tables_t *tab = NULL;
|
||||
uint32_t *S = NULL, *Sp = NULL, *col = NULL, *col2 = NULL;
|
||||
uint8_t *out = NULL;
|
||||
int t, m, nc = 0, rc;
|
||||
size_t nbits;
|
||||
if (!stats)
|
||||
stats = &dummy;
|
||||
memset(stats, 0, sizeof *stats);
|
||||
if (!in || !p || !cands)
|
||||
return -1;
|
||||
if (max_cands <= 0)
|
||||
return 0;
|
||||
if (max_cands > BCH_CHASE_MAX_CANDS)
|
||||
max_cands = BCH_CHASE_MAX_CANDS;
|
||||
/* No early return when suspects are empty: phase B builds its
|
||||
* first-element list from the suspects plus a positional prefix,
|
||||
* so it runs even with an empty suspect set. */
|
||||
t = p->t;
|
||||
m = p->m;
|
||||
nbits = (size_t)8 * data_len + (size_t)p->r;
|
||||
rc = chase_setup(in, in_len, data_len, p, &ctx, &tab, &S);
|
||||
if (rc != 0)
|
||||
return rc < 0 ? -1 : 0;
|
||||
Sp = malloc(sizeof(uint32_t) * (size_t)(2 * t > 0 ? 2 * t : 1));
|
||||
col = malloc(sizeof(uint32_t) * (size_t)(2 * t > 0 ? 2 * t : 1));
|
||||
col2 = malloc(sizeof(uint32_t) * (size_t)(2 * t > 0 ? 2 * t : 1));
|
||||
out = malloc(data_len ? data_len : 1);
|
||||
if (!Sp || !col || !col2 || !out) {
|
||||
free(Sp);
|
||||
free(col);
|
||||
free(col2);
|
||||
free(out);
|
||||
free(S);
|
||||
bch_ctx_free(ctx);
|
||||
return -1;
|
||||
}
|
||||
/* Phase A: pairs within the suspect set. */
|
||||
{
|
||||
int i, j, k;
|
||||
for (i = 0; i < nsuspects && nc < max_cands; i++) {
|
||||
size_t si = suspects[i];
|
||||
if (si >= nbits)
|
||||
continue;
|
||||
col_at(si, nbits, t, tab, col);
|
||||
for (j = i + 1; j < nsuspects && nc < max_cands; j++) {
|
||||
size_t sj = suspects[j];
|
||||
if (sj >= nbits)
|
||||
continue;
|
||||
col_at(sj, nbits, t, tab, col2);
|
||||
for (k = 0; k < 2 * t; k++)
|
||||
Sp[k] = S[k] ^ col[k] ^ col2[k];
|
||||
{
|
||||
size_t fl[2];
|
||||
fl[0] = si;
|
||||
fl[1] = sj;
|
||||
if (chase_trial(Sp, in, in_len, data_len, p, fl, 2, tab, ctx,
|
||||
out, stats) &&
|
||||
!cand_seen(cands, nc, data_len, out)) {
|
||||
memcpy(cands + (size_t)nc * data_len, out, data_len);
|
||||
nc++;
|
||||
}
|
||||
}
|
||||
if (deadline >= 0 && bch_now() > deadline) {
|
||||
stats->partial = 1;
|
||||
goto done;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/* Phase B: (first-element, any-position) pairs. The first
|
||||
* element ranges over a bounded list: the suspect set first,
|
||||
* then ascending bit positions, capped at
|
||||
* BCH_CHASE2_FIRST_MAX entries in total. For a fixed first
|
||||
* element s, base = S ^ col(s); q scans ascending with
|
||||
* incremental col(q). A pair {a,b} with both ends in the
|
||||
* first list is tried once, at the smaller outer element
|
||||
* (skip q in the list with q < s); pairs with one end
|
||||
* outside the list are tried when the outer element is the
|
||||
* in-list end. Trial count is bounded by
|
||||
* BCH_CHASE2_FIRST_MAX * nbits, and the deadline caps the
|
||||
* wall time. Why the positional prefix: the failed decode's
|
||||
* Chien roots provably do not overlap the true errors (the
|
||||
* two same-syndrome patterns differ by a codeword of weight
|
||||
* >= 2t+1, forcing zero overlap when the failed decode
|
||||
* returns a full root set), so for random error patterns a
|
||||
* suspect is no more likely than any other position to be a
|
||||
* true error. The recovery probability therefore scales
|
||||
* with the size of the first-element list: roughly
|
||||
* 1 - (1 - (t+2)/nbits)^F for F first elements, and the
|
||||
* list is what buys the rate. */
|
||||
{
|
||||
uint32_t *base = malloc(sizeof(uint32_t) *
|
||||
(size_t)(2 * t > 0 ? 2 * t : 1));
|
||||
uint32_t *cur = malloc(sizeof(uint32_t) *
|
||||
(size_t)(2 * t > 0 ? 2 * t : 1));
|
||||
uint32_t *step = malloc(sizeof(uint32_t) *
|
||||
(size_t)(2 * t > 0 ? 2 * t : 1));
|
||||
uint32_t N;
|
||||
size_t first[BCH_CHASE2_FIRST_MAX];
|
||||
int nfirst = 0, si, j;
|
||||
size_t P = 0; /* prefix length: positions < P are in the
|
||||
* first list unless they are suspects,
|
||||
* and every suspect is in the list */
|
||||
if (!base || !cur || !step) {
|
||||
free(base);
|
||||
free(cur);
|
||||
free(step);
|
||||
goto done;
|
||||
}
|
||||
for (si = 0; si < nsuspects && nfirst < BCH_CHASE2_FIRST_MAX; si++)
|
||||
if (suspects[si] < nbits)
|
||||
first[nfirst++] = suspects[si];
|
||||
{
|
||||
size_t pp;
|
||||
for (pp = 0; pp < nbits && nfirst < BCH_CHASE2_FIRST_MAX; pp++) {
|
||||
int dup = 0, sj;
|
||||
for (sj = 0; sj < nfirst; sj++)
|
||||
if (first[sj] == pp) {
|
||||
dup = 1;
|
||||
break;
|
||||
}
|
||||
if (!dup)
|
||||
first[nfirst++] = pp;
|
||||
P = pp + 1;
|
||||
}
|
||||
}
|
||||
N = tab->N;
|
||||
for (j = 1; j <= 2 * t; j++)
|
||||
step[j - 1] = tab->exp[(N - (uint32_t)j) % N]; /* alpha^-j */
|
||||
for (si = 0; si < nfirst && nc < max_cands; si++) {
|
||||
size_t s = first[si];
|
||||
size_t q;
|
||||
col_at(s, nbits, t, tab, col);
|
||||
for (j = 0; j < 2 * t; j++)
|
||||
base[j] = S[j] ^ col[j];
|
||||
for (j = 1; j <= 2 * t; j++)
|
||||
cur[j - 1] = tab->exp[(uint32_t)(((uint64_t)j * (nbits - 1)) % N)];
|
||||
for (q = 0; q < nbits && nc < max_cands; q++) {
|
||||
int in_first = (q < P);
|
||||
int sj;
|
||||
if (!in_first)
|
||||
for (sj = 0; sj < nsuspects; sj++)
|
||||
if (suspects[sj] == q) {
|
||||
in_first = 1;
|
||||
break;
|
||||
}
|
||||
if (q != s && !(in_first && q < s)) {
|
||||
size_t fl[2];
|
||||
for (j = 0; j < 2 * t; j++)
|
||||
Sp[j] = base[j] ^ cur[j];
|
||||
fl[0] = s;
|
||||
fl[1] = q;
|
||||
if (chase_trial(Sp, in, in_len, data_len, p, fl, 2, tab, ctx,
|
||||
out, stats) &&
|
||||
!cand_seen(cands, nc, data_len, out)) {
|
||||
memcpy(cands + (size_t)nc * data_len, out, data_len);
|
||||
nc++;
|
||||
}
|
||||
}
|
||||
for (j = 0; j < 2 * t; j++)
|
||||
cur[j] = gf_mul_tab(cur[j], step[j], tab);
|
||||
if (deadline >= 0 && (q & 255) == 0 && bch_now() > deadline) {
|
||||
stats->partial = 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (stats->partial)
|
||||
break;
|
||||
}
|
||||
free(base);
|
||||
free(cur);
|
||||
free(step);
|
||||
}
|
||||
done:
|
||||
stats->candidates = nc;
|
||||
free(Sp);
|
||||
free(col);
|
||||
free(col2);
|
||||
free(out);
|
||||
free(S);
|
||||
bch_ctx_free(ctx);
|
||||
(void)m;
|
||||
return nc;
|
||||
}
|
||||
@@ -106,4 +106,113 @@ int bch_decode_candidates(const uint8_t *in, size_t len, size_t orig_len,
|
||||
int bch_remainder_bruteforce(const uint8_t *data, size_t data_len,
|
||||
const bch_poly_t *p, uint8_t *rem_out);
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Deep repair: Chase / list decoding past t (lzply_deep_repair). */
|
||||
/* */
|
||||
/* The standard decoder corrects up to t bit errors per block. Past */
|
||||
/* t it fails or miscorrects. The Chase levels below recover data */
|
||||
/* past t by trial flips, verified against an external oracle (the */
|
||||
/* caller CRC16/SHA-256-checks every candidate; nothing here is ever */
|
||||
/* returned as "the" answer). */
|
||||
/* */
|
||||
/* Method. Flipping one bit at position p changes the syndrome by */
|
||||
/* the column col(p): S_j ^= alpha^(j*(n-1-p)), j = 1..2t. A trial */
|
||||
/* flip is GOOD (it hit a true error, leaving t errors) iff the */
|
||||
/* Berlekamp-Massey locator for the flipped syndrome splits */
|
||||
/* completely over GF(2^m) with all roots at in-range positions and */
|
||||
/* the corrected word has zero remainder. The splitting test is a */
|
||||
/* gcd with x^(2^m) - x (m repeated squarings mod the locator): it */
|
||||
/* costs O(m*t^2) field operations per trial, versus O(n*t) for a */
|
||||
/* full Chien search, so it filters the trials cheaply and Chien */
|
||||
/* runs only for the rare survivors (a random degree-L locator */
|
||||
/* splits with probability ~1/L!). */
|
||||
/* */
|
||||
/* Bounds (all documented, all enforced): */
|
||||
/* chase1: at most nbits trials (one per codeword bit position), */
|
||||
/* suspects first, then an exhaustive ascending scan. */
|
||||
/* chase2: pairs (s, q) with s from a bounded first-element list */
|
||||
/* (the suspect set, then ascending bit positions, at most */
|
||||
/* BCH_CHASE2_FIRST_MAX entries) and q over all positions, plus */
|
||||
/* pairs within the suspect set: at most */
|
||||
/* BCH_CHASE2_FIRST_MAX*nbits + 496 trials. */
|
||||
/* candidates: at most BCH_CHASE_MAX_CANDS distinct decoded blocks */
|
||||
/* per call. A wall-clock deadline (monotonic seconds, < 0 = */
|
||||
/* none) stops a scan early; stats.partial says so, and */
|
||||
/* stats.trials says how far the scan got. */
|
||||
/* */
|
||||
/* "Least-reliable bits": with hard-decision input there is no */
|
||||
/* channel reliability, so suspicion comes from the decoder itself: */
|
||||
/* the Chien roots of the failed decode, the residual-BM difference */
|
||||
/* set, and their neighbours. Those positions are tried first */
|
||||
/* (chase1 phase A). For chase2 they head the first-element list, */
|
||||
/* followed by a positional prefix, because the failed decode's */
|
||||
/* roots provably do NOT overlap the true errors for random */
|
||||
/* patterns: the failed decode's root set and the true error set */
|
||||
/* have the same syndrome, so they differ by a codeword of weight */
|
||||
/* >= 2t+1, which forces zero overlap when the failed decode */
|
||||
/* returns a full root set. A suspect is therefore no more likely */
|
||||
/* than any other position to be a true error, and chase2's */
|
||||
/* recovery rate scales with the size of the first-element list: */
|
||||
/* roughly 1 - (1 - (t+2)/nbits)^F for F first elements on a */
|
||||
/* 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. */
|
||||
#define BCH_CHASE_MAX_SUSPECTS 32
|
||||
/* Maximum first elements in a chase2 pair scan (suspects, then a
|
||||
* positional prefix). Trial count is bounded by this times nbits. */
|
||||
#define BCH_CHASE2_FIRST_MAX 128
|
||||
|
||||
typedef struct {
|
||||
long trials; /* BM runs (one per trial flip / flip pair) */
|
||||
long split_pass; /* trials whose locator splits over GF(2^m) */
|
||||
long codewords; /* trials yielding a valid (zero-remainder) codeword */
|
||||
long candidates; /* distinct candidate blocks returned */
|
||||
int partial; /* scan stopped early (deadline hit) */
|
||||
} bch_chase_stats_t;
|
||||
|
||||
/* Monotonic seconds (CLOCK_MONOTONIC), for repair time budgets. */
|
||||
double bch_now(void);
|
||||
|
||||
/* Suspect positions for a block the standard decoder failed on:
|
||||
* Chien roots of the failed decode, residual-BM difference
|
||||
* positions, and neighbours of the roots -- in that priority order,
|
||||
* deduplicated, capped at max_pos. Returns the count (0 when the
|
||||
* failed decode yields no usable positions). Does not modify `in`.
|
||||
* `pos` must hold max_pos entries. */
|
||||
int bch_suspect_positions(const uint8_t *in, size_t in_len, size_t data_len,
|
||||
const bch_poly_t *p, size_t *pos, int max_pos);
|
||||
|
||||
/* Chase-1 for one block: single-bit trial flips. Tries the suspect
|
||||
* positions first (in order), then every other bit position in
|
||||
* ascending order. Returns the number of distinct candidate decoded
|
||||
* blocks in `cands` (each data_len bytes, 0..max_cands), or -1 on
|
||||
* bad input. Returns 0 when the standard decoder already succeeds
|
||||
* (nothing to chase). `suspects` may be NULL (with nsuspects 0).
|
||||
* `deadline` is an absolute bch_now() time, or < 0 for no deadline.
|
||||
* Stats are zeroed on entry (NULL is allowed). */
|
||||
int bch_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);
|
||||
|
||||
/* Chase-2 for one block: two-bit trial flips. First all pairs within
|
||||
* the suspect set, then (first-element, any-position) pairs where
|
||||
* the first element ranges over a bounded list: the suspects, then
|
||||
* ascending bit positions, capped at BCH_CHASE2_FIRST_MAX entries.
|
||||
* Same return contract as bch_chase1_block. `suspects` may be NULL
|
||||
* (with nsuspects 0); the positional prefix still runs. */
|
||||
int bch_chase2_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);
|
||||
|
||||
#endif /* LZPLY_BCH_H */
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
/* bch_bench.c - micro-benchmark for the BCH layer (encode/decode).
|
||||
*
|
||||
* Times bch_encode / bch_decode on an in-memory blob (no LZMA, SHA or
|
||||
* I/O), so the numbers isolate the remainder + memcpy cost. Also times
|
||||
* a plain memcpy of the same size for reference, and verifies the
|
||||
* round-trip plus 1-bit-flip correction. The same binary measures the
|
||||
* CUDA path when linked with bch_cuda.o (dispatch lives inside
|
||||
* bch_encode/bch_decode); without it, it measures the CPU path.
|
||||
*
|
||||
* Usage: bch_bench [file] [reps]
|
||||
* file: input blob (default: deterministic 50 MiB generated in RAM)
|
||||
* reps: timed repetitions per case (default 5, median reported)
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
#include "bch.h"
|
||||
|
||||
static double now_s(void)
|
||||
{
|
||||
struct timespec ts;
|
||||
clock_gettime(CLOCK_MONOTONIC, &ts);
|
||||
return (double)ts.tv_sec + (double)ts.tv_nsec * 1e-9;
|
||||
}
|
||||
|
||||
static int cmp_dbl(const void *a, const void *b)
|
||||
{
|
||||
double x = *(const double *)a, y = *(const double *)b;
|
||||
return (x > y) - (x < y);
|
||||
}
|
||||
|
||||
static double median(double *v, int n)
|
||||
{
|
||||
qsort(v, (size_t)n, sizeof(double), cmp_dbl);
|
||||
return v[n / 2];
|
||||
}
|
||||
|
||||
/* Deterministic filler: xorshift64, fast and incompressible-ish. */
|
||||
static void fill_pattern(uint8_t *buf, size_t len)
|
||||
{
|
||||
uint64_t s = 0x9e3779b97f4a7c15ULL;
|
||||
size_t i = 0;
|
||||
while (i + 8 <= len) {
|
||||
s ^= s << 13; s ^= s >> 7; s ^= s << 17;
|
||||
memcpy(buf + i, &s, 8);
|
||||
i += 8;
|
||||
}
|
||||
while (i < len) {
|
||||
s ^= s << 13; s ^= s >> 7; s ^= s << 17;
|
||||
buf[i++] = (uint8_t)s;
|
||||
}
|
||||
}
|
||||
|
||||
static const bch_poly_t *poly_for(size_t len, int t)
|
||||
{
|
||||
/* bch_poly_for_data(524000, t) returns the m=22 poly for that t:
|
||||
* 8*524000 + t*22 < 2^22-1, while m=21 (N=2^21-1) is too small. */
|
||||
const bch_poly_t *p = bch_poly_for_data(524000, t);
|
||||
(void)len;
|
||||
return p;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
const char *path = argc > 1 ? argv[1] : NULL;
|
||||
int reps = argc > 2 ? atoi(argv[2]) : 5;
|
||||
if (reps < 1) reps = 1;
|
||||
if (reps > 21) reps = 21;
|
||||
|
||||
uint8_t *data = NULL;
|
||||
size_t len = 0;
|
||||
if (path) {
|
||||
FILE *f = fopen(path, "rb");
|
||||
if (!f) { perror("fopen"); return 1; }
|
||||
fseek(f, 0, SEEK_END);
|
||||
long n = ftell(f);
|
||||
fseek(f, 0, SEEK_SET);
|
||||
if (n < 0) { fprintf(stderr, "ftell failed\n"); return 1; }
|
||||
len = (size_t)n;
|
||||
data = malloc(len ? len : 1);
|
||||
if (fread(data, 1, len, f) != len) { fprintf(stderr, "short read\n"); return 1; }
|
||||
fclose(f);
|
||||
} else {
|
||||
len = 50u << 20;
|
||||
data = malloc(len);
|
||||
fill_pattern(data, len);
|
||||
}
|
||||
printf("blob %zu bytes (%.3f MiB), reps %d\n", len,
|
||||
(double)len / 1048576.0, reps);
|
||||
|
||||
double *ts = malloc(sizeof(double) * (size_t)reps);
|
||||
double s, e;
|
||||
|
||||
/* memcpy reference */
|
||||
uint8_t *tmp = malloc(len ? len : 1);
|
||||
for (int i = 0; i < reps; i++) {
|
||||
s = now_s();
|
||||
memcpy(tmp, data, len);
|
||||
e = now_s();
|
||||
ts[i] = e - s;
|
||||
}
|
||||
printf("memcpy : median %.4f s %8.1f MB/s\n", median(ts, reps),
|
||||
(double)len / 1048576.0 / median(ts, reps));
|
||||
|
||||
for (int ti = 0; ti < 2; ti++) {
|
||||
int t = ti == 0 ? 8 : 32;
|
||||
const bch_poly_t *p = poly_for(len, t);
|
||||
if (!p) { printf("t=%d: no poly\n", t); continue; }
|
||||
size_t maxd = bch_max_data(p);
|
||||
size_t blocks = (len + maxd - 1) / maxd;
|
||||
size_t eclen = bch_encoded_len(len, p);
|
||||
uint8_t *enc = malloc(eclen ? eclen : 1);
|
||||
uint8_t *dec = malloc(len ? len : 1);
|
||||
printf("t=%-2d poly id 0x%04x m=%d r=%d maxdata=%zu blocks=%zu stored=%zu (+%.2f%%)\n",
|
||||
t, p->id, p->m, p->r, maxd, blocks, eclen,
|
||||
100.0 * (double)(eclen - len) / (double)len);
|
||||
|
||||
/* warmup + verify round-trip once */
|
||||
if (bch_encode(data, len, p, enc) != eclen) {
|
||||
printf("t=%d: encode failed\n", t); return 1;
|
||||
}
|
||||
int corr = 0;
|
||||
if (bch_decode(enc, eclen, len, p, dec, &corr) != 0 ||
|
||||
memcmp(dec, data, len) != 0) {
|
||||
printf("t=%d: round-trip FAILED\n", t); return 1;
|
||||
}
|
||||
/* 1-bit flip in the first block must still decode. */
|
||||
enc[0] ^= 0x01;
|
||||
corr = 0;
|
||||
if (bch_decode(enc, eclen, len, p, dec, &corr) != 0 ||
|
||||
memcmp(dec, data, len) != 0 || corr != 1) {
|
||||
printf("t=%d: 1-bit-flip decode FAILED (corr=%d)\n", t, corr);
|
||||
return 1;
|
||||
}
|
||||
enc[0] ^= 0x01;
|
||||
printf("t=%d: round-trip ok, 1-bit flip corrected (corr=1)\n", t);
|
||||
|
||||
for (int i = 0; i < reps; i++) {
|
||||
s = now_s();
|
||||
if (bch_encode(data, len, p, enc) != eclen) { printf("encode fail\n"); return 1; }
|
||||
e = now_s();
|
||||
ts[i] = e - s;
|
||||
}
|
||||
double med = median(ts, reps);
|
||||
printf("t=%-2d encode : median %.4f s %8.1f MB/s\n", t, med,
|
||||
(double)len / 1048576.0 / med);
|
||||
for (int i = 0; i < reps; i++) {
|
||||
s = now_s();
|
||||
if (bch_decode(enc, eclen, len, p, dec, &corr) != 0) { printf("decode fail\n"); return 1; }
|
||||
e = now_s();
|
||||
ts[i] = e - s;
|
||||
}
|
||||
med = median(ts, reps);
|
||||
printf("t=%-2d decode : median %.4f s %8.1f MB/s (corr=%d)\n", t, med,
|
||||
(double)len / 1048576.0 / med, corr);
|
||||
free(enc);
|
||||
free(dec);
|
||||
}
|
||||
free(tmp);
|
||||
free(data);
|
||||
free(ts);
|
||||
printf("ALL OK\n");
|
||||
return 0;
|
||||
}
|
||||
+735
@@ -0,0 +1,735 @@
|
||||
/* bch_cuda.cu - CUDA BCH remainder for lzply.
|
||||
*
|
||||
* See bch_cuda.h for the design. Remainder recap (bch.c): the state
|
||||
* is an r-bit value, left-aligned in nb = (r+7)/8 bytes; feeding a
|
||||
* byte is rem = shift8(rem) XOR T[rem[0] XOR b], where T is the
|
||||
* 256*nb table built from the generator. That step is GF(2)-linear
|
||||
* in (rem, b), so feeding a chunk from zero state gives a partial
|
||||
* remainder, and concatenating chunks is partial-combining with an
|
||||
* advance-by-k-bytes map Adv_k (itself linear, so it is a table:
|
||||
* Adv_k(S) = XOR over bytes j of Adv_k[j][S[j]]).
|
||||
*
|
||||
* Host-side table building duplicates bch.c exactly (glow, T, and
|
||||
* Adv_1); the 12 squarings Adv_1 -> Adv_4096 run on the device.
|
||||
* Bit-identity vs the CPU remainder is verified by bch_cuda_test
|
||||
* (GPU encode output byte-identical to CPU encode, all 82 polys
|
||||
* via the (t, size) grid, plus decode agreement on dirty blocks).
|
||||
*/
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
#include <cuda_runtime.h>
|
||||
|
||||
extern "C" {
|
||||
#include "bch.h"
|
||||
}
|
||||
#include "bch_cuda.h"
|
||||
|
||||
/* Debug prints on failure paths, enabled by BCH_CUDA_DEBUG=1. */
|
||||
static int cu_debug(void)
|
||||
{
|
||||
static int d = -1;
|
||||
if (d < 0)
|
||||
d = getenv("BCH_CUDA_DEBUG") ? 1 : 0;
|
||||
return d;
|
||||
}
|
||||
#define CU_DBG(...) do { if (cu_debug()) { fprintf(stderr, "bch_cuda %s:%d: ", __func__, __LINE__); fprintf(stderr, __VA_ARGS__); fprintf(stderr, "\n"); } } while (0)
|
||||
|
||||
#define BCH_CUDA_CHUNK 4096
|
||||
#define BCH_CUDA_MAX_NB 88 /* r max = 32*22 = 704 bits -> nb = 88 */
|
||||
#define BCH_CUDA_MAX_POLYS 8
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* host-side LFSR helpers: bit-identical copies of bch.c */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
static void cu_rem_set_bit(uint8_t *rem, int r, int i)
|
||||
{
|
||||
int byte = (r - 1 - i) / 8;
|
||||
int bit = 7 - ((r - 1 - i) % 8);
|
||||
rem[byte] |= (uint8_t)(1u << bit);
|
||||
}
|
||||
|
||||
static void cu_rem_shl1(uint8_t *rem, int nb)
|
||||
{
|
||||
for (int i = 0; i < nb; i++)
|
||||
rem[i] = (uint8_t)((rem[i] << 1) | (i + 1 < nb ? (rem[i + 1] >> 7) : 0));
|
||||
}
|
||||
|
||||
static void cu_rem_bitstep(uint8_t *rem, int m, const uint8_t *glow, int nb)
|
||||
{
|
||||
int fb = ((rem[0] >> 7) & 1) ^ (m & 1);
|
||||
cu_rem_shl1(rem, nb);
|
||||
if (fb)
|
||||
for (int i = 0; i < nb; i++)
|
||||
rem[i] ^= glow[i];
|
||||
}
|
||||
|
||||
/* One table-driven byte step, given an explicit table. */
|
||||
static void cu_rem_feed_byte(uint8_t *rem, uint8_t b,
|
||||
const uint8_t *table, int nb)
|
||||
{
|
||||
int idx = rem[0] ^ b;
|
||||
const uint8_t *t = table + (size_t)idx * nb;
|
||||
for (int i = 0; i < nb - 1; i++)
|
||||
rem[i] = rem[i + 1] ^ t[i];
|
||||
rem[nb - 1] = t[nb - 1];
|
||||
}
|
||||
|
||||
static int cu_rem_is_zero(const uint8_t *rem, int nb)
|
||||
{
|
||||
for (int i = 0; i < nb; i++)
|
||||
if (rem[i])
|
||||
return 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* device availability */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
extern "C" int bch_cuda_available(void)
|
||||
{
|
||||
static int cached = -1;
|
||||
if (cached < 0) {
|
||||
int n = 0;
|
||||
cudaError_t err = cudaGetDeviceCount(&n);
|
||||
cached = (err == cudaSuccess && n > 0) ? 1 : 0;
|
||||
}
|
||||
return cached;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* kernels */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/* One thread per chunk: serial table LFSR over the chunk, zero state.
|
||||
* Templated on NB so the remainder stays in registers; the generic
|
||||
* version covers any other nb (local-memory remainder). */
|
||||
template <int NB>
|
||||
__global__ void partial_kernel_t(const uint8_t *__restrict__ in,
|
||||
const int *__restrict__ chunk_off,
|
||||
const int *__restrict__ chunk_len,
|
||||
const uint8_t *__restrict__ table,
|
||||
uint8_t *__restrict__ part, int nchunks)
|
||||
{
|
||||
int c = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
if (c >= nchunks)
|
||||
return;
|
||||
const uint8_t *src = in + chunk_off[c];
|
||||
int len = chunk_len[c];
|
||||
uint8_t rem[NB];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < NB; i++)
|
||||
rem[i] = 0;
|
||||
for (int k = 0; k < len; k++) {
|
||||
int idx = rem[0] ^ src[k];
|
||||
const uint8_t *t = table + (size_t)idx * NB;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < NB - 1; i++)
|
||||
rem[i] = rem[i + 1] ^ t[i];
|
||||
rem[NB - 1] = t[NB - 1];
|
||||
}
|
||||
uint8_t *dst = part + (size_t)c * NB;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < NB; i++)
|
||||
dst[i] = rem[i];
|
||||
}
|
||||
|
||||
__global__ void partial_kernel_g(const uint8_t *__restrict__ in,
|
||||
const int *__restrict__ chunk_off,
|
||||
const int *__restrict__ chunk_len,
|
||||
const uint8_t *__restrict__ table,
|
||||
uint8_t *__restrict__ part, int nchunks,
|
||||
int nb)
|
||||
{
|
||||
int c = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
if (c >= nchunks)
|
||||
return;
|
||||
const uint8_t *src = in + chunk_off[c];
|
||||
int len = chunk_len[c];
|
||||
uint8_t rem[BCH_CUDA_MAX_NB];
|
||||
for (int i = 0; i < nb; i++)
|
||||
rem[i] = 0;
|
||||
for (int k = 0; k < len; k++) {
|
||||
int idx = rem[0] ^ src[k];
|
||||
const uint8_t *t = table + (size_t)idx * nb;
|
||||
for (int i = 0; i < nb - 1; i++)
|
||||
rem[i] = rem[i + 1] ^ t[i];
|
||||
rem[nb - 1] = t[nb - 1];
|
||||
}
|
||||
uint8_t *dst = part + (size_t)c * nb;
|
||||
for (int i = 0; i < nb; i++)
|
||||
dst[i] = rem[i];
|
||||
}
|
||||
|
||||
/* One thread per block: combine that block's chunk partials.
|
||||
* acc = P_first; then acc = Adv_CHUNK(acc) XOR P_k for each later
|
||||
* (full) chunk. adv is the nb*256*nb advance table. */
|
||||
template <int NB>
|
||||
__global__ void combine_kernel_t(const uint8_t *__restrict__ part,
|
||||
const int *__restrict__ block_first,
|
||||
const int *__restrict__ block_nchunk,
|
||||
const uint8_t *__restrict__ adv,
|
||||
uint8_t *__restrict__ rem_out, int nblocks)
|
||||
{
|
||||
int b = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
if (b >= nblocks)
|
||||
return;
|
||||
uint8_t acc[NB];
|
||||
const uint8_t *p0 = part + (size_t)block_first[b] * NB;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < NB; i++)
|
||||
acc[i] = p0[i];
|
||||
for (int k = 1; k < block_nchunk[b]; k++) {
|
||||
uint8_t nxt[NB];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < NB; i++)
|
||||
nxt[i] = 0;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < NB; j++) {
|
||||
const uint8_t *a = adv + ((size_t)j * 256 + acc[j]) * NB;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < NB; i++)
|
||||
nxt[i] ^= a[i];
|
||||
}
|
||||
const uint8_t *pk = part + (size_t)(block_first[b] + k) * NB;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < NB; i++)
|
||||
acc[i] = nxt[i] ^ pk[i];
|
||||
}
|
||||
uint8_t *dst = rem_out + (size_t)b * NB;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < NB; i++)
|
||||
dst[i] = acc[i];
|
||||
}
|
||||
|
||||
__global__ void combine_kernel_g(const uint8_t *__restrict__ part,
|
||||
const int *__restrict__ block_first,
|
||||
const int *__restrict__ block_nchunk,
|
||||
const uint8_t *__restrict__ adv,
|
||||
uint8_t *__restrict__ rem_out, int nblocks,
|
||||
int nb)
|
||||
{
|
||||
int b = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
if (b >= nblocks)
|
||||
return;
|
||||
uint8_t acc[BCH_CUDA_MAX_NB];
|
||||
const uint8_t *p0 = part + (size_t)block_first[b] * nb;
|
||||
for (int i = 0; i < nb; i++)
|
||||
acc[i] = p0[i];
|
||||
for (int k = 1; k < block_nchunk[b]; k++) {
|
||||
uint8_t nxt[BCH_CUDA_MAX_NB];
|
||||
for (int i = 0; i < nb; i++)
|
||||
nxt[i] = 0;
|
||||
for (int j = 0; j < nb; j++) {
|
||||
const uint8_t *a = adv + ((size_t)j * 256 + acc[j]) * nb;
|
||||
for (int i = 0; i < nb; i++)
|
||||
nxt[i] ^= a[i];
|
||||
}
|
||||
const uint8_t *pk = part + (size_t)(block_first[b] + k) * nb;
|
||||
for (int i = 0; i < nb; i++)
|
||||
acc[i] = nxt[i] ^ pk[i];
|
||||
}
|
||||
uint8_t *dst = rem_out + (size_t)b * nb;
|
||||
for (int i = 0; i < nb; i++)
|
||||
dst[i] = acc[i];
|
||||
}
|
||||
|
||||
/* Advance-table squaring: one thread per (byte j, value v) entry.
|
||||
* out[j][v] = Adv(Adv[j][v]), i.e. Adv_{2k} from Adv_k. */
|
||||
__global__ void adv_square_kernel(const uint8_t *__restrict__ adv_in,
|
||||
uint8_t *__restrict__ adv_out, int nb)
|
||||
{
|
||||
int e = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
if (e >= nb * 256)
|
||||
return;
|
||||
uint8_t v[BCH_CUDA_MAX_NB];
|
||||
const uint8_t *src = adv_in + (size_t)e * nb;
|
||||
for (int i = 0; i < nb; i++)
|
||||
v[i] = src[i];
|
||||
uint8_t out[BCH_CUDA_MAX_NB];
|
||||
for (int i = 0; i < nb; i++)
|
||||
out[i] = 0;
|
||||
for (int j = 0; j < nb; j++) {
|
||||
const uint8_t *row = adv_in + ((size_t)j * 256 + v[j]) * nb;
|
||||
for (int i = 0; i < nb; i++)
|
||||
out[i] ^= row[i];
|
||||
}
|
||||
uint8_t *dst = adv_out + (size_t)e * nb;
|
||||
for (int i = 0; i < nb; i++)
|
||||
dst[i] = out[i];
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* per-poly cached device state */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
typedef struct {
|
||||
uint16_t id;
|
||||
int nb;
|
||||
int r;
|
||||
uint8_t glow[BCH_CUDA_MAX_NB];
|
||||
uint8_t *d_table; /* 256*nb */
|
||||
uint8_t *d_adv; /* nb*256*nb, advance by BCH_CUDA_CHUNK */
|
||||
uint8_t *d_adv2; /* scratch for squaring */
|
||||
} cu_poly_t;
|
||||
|
||||
static cu_poly_t g_polys[BCH_CUDA_MAX_POLYS];
|
||||
static int g_npolys = 0;
|
||||
|
||||
static void cu_poly_cleanup_partial(cu_poly_t *cp)
|
||||
{
|
||||
if (cp->d_table) { cudaFree(cp->d_table); cp->d_table = NULL; }
|
||||
if (cp->d_adv) { cudaFree(cp->d_adv); cp->d_adv = NULL; }
|
||||
if (cp->d_adv2) { cudaFree(cp->d_adv2); cp->d_adv2 = NULL; }
|
||||
}
|
||||
|
||||
static cu_poly_t *cu_poly_get(const bch_poly_t *p)
|
||||
{
|
||||
for (int i = 0; i < g_npolys; i++)
|
||||
if (g_polys[i].id == p->id && g_polys[i].d_table)
|
||||
return &g_polys[i];
|
||||
if (g_npolys >= BCH_CUDA_MAX_POLYS) {
|
||||
/* Evict everything (rebuilds are ~ms: the squaring runs on
|
||||
* the device). One lzply process normally uses 1-2 polys. */
|
||||
for (int i = 0; i < g_npolys; i++)
|
||||
cu_poly_cleanup_partial(&g_polys[i]);
|
||||
memset(g_polys, 0, sizeof(g_polys));
|
||||
g_npolys = 0;
|
||||
CU_DBG("poly cache evicted");
|
||||
}
|
||||
cu_poly_t *cp = &g_polys[g_npolys];
|
||||
memset(cp, 0, sizeof(*cp));
|
||||
cp->id = p->id;
|
||||
cp->r = p->r;
|
||||
cp->nb = (p->r + 7) / 8;
|
||||
int nb = cp->nb;
|
||||
uint8_t *table = NULL;
|
||||
uint8_t *adv1 = NULL;
|
||||
|
||||
/* glow + T on the host (same construction as bch_ctx_new). */
|
||||
const uint8_t *gen = bch_poly_bytes + p->off;
|
||||
for (int i = 0; i < p->r; i++)
|
||||
if ((gen[i / 8] >> (i % 8)) & 1)
|
||||
cu_rem_set_bit(cp->glow, p->r, i);
|
||||
table = (uint8_t *)malloc((size_t)256 * nb);
|
||||
if (!table)
|
||||
goto fail;
|
||||
for (int u = 0; u < 256; u++) {
|
||||
uint8_t *t = table + (size_t)u * nb;
|
||||
memset(t, 0, nb);
|
||||
for (int b = 7; b >= 0; b--)
|
||||
cu_rem_bitstep(t, (u >> b) & 1, cp->glow, nb);
|
||||
}
|
||||
/* Adv_1 on the host: one zero byte fed from each single-byte state. */
|
||||
adv1 = (uint8_t *)malloc((size_t)nb * 256 * nb);
|
||||
if (!adv1) {
|
||||
free(table);
|
||||
goto fail;
|
||||
}
|
||||
for (int j = 0; j < nb; j++) {
|
||||
for (int v = 0; v < 256; v++) {
|
||||
uint8_t *s = adv1 + ((size_t)j * 256 + v) * nb;
|
||||
memset(s, 0, nb);
|
||||
s[j] = (uint8_t)v;
|
||||
cu_rem_feed_byte(s, 0, table, nb);
|
||||
}
|
||||
}
|
||||
{
|
||||
cudaError_t err;
|
||||
err = cudaMalloc(&cp->d_table, (size_t)256 * nb);
|
||||
if (err != cudaSuccess) { free(table); free(adv1); CU_DBG("poly 0x%04x d_table malloc: %s", p->id, cudaGetErrorString(err)); goto fail; }
|
||||
err = cudaMemcpy(cp->d_table, table, (size_t)256 * nb,
|
||||
cudaMemcpyHostToDevice);
|
||||
if (err != cudaSuccess) { free(table); free(adv1); CU_DBG("poly 0x%04x d_table copy: %s", p->id, cudaGetErrorString(err)); goto fail; }
|
||||
err = cudaMalloc(&cp->d_adv, (size_t)nb * 256 * nb);
|
||||
if (err != cudaSuccess) { free(table); free(adv1); CU_DBG("poly 0x%04x d_adv malloc: %s", p->id, cudaGetErrorString(err)); goto fail; }
|
||||
err = cudaMalloc(&cp->d_adv2, (size_t)nb * 256 * nb);
|
||||
if (err != cudaSuccess) { free(table); free(adv1); CU_DBG("poly 0x%04x d_adv2 malloc: %s", p->id, cudaGetErrorString(err)); goto fail; }
|
||||
err = cudaMemcpy(cp->d_adv, adv1, (size_t)nb * 256 * nb,
|
||||
cudaMemcpyHostToDevice);
|
||||
free(table);
|
||||
free(adv1);
|
||||
if (err != cudaSuccess) { CU_DBG("poly 0x%04x d_adv copy: %s", p->id, cudaGetErrorString(err)); goto fail; }
|
||||
|
||||
/* Square on the device: Adv_1 -> Adv_CHUNK (CHUNK is a power of 2). */
|
||||
int steps = 0;
|
||||
while ((1 << steps) < BCH_CUDA_CHUNK)
|
||||
steps++;
|
||||
uint8_t *cur = cp->d_adv, *nxt = cp->d_adv2;
|
||||
int nentries = nb * 256;
|
||||
for (int s = 0; s < steps; s++) {
|
||||
adv_square_kernel<<<(nentries + 255) / 256, 256>>>(cur, nxt, nb);
|
||||
err = cudaGetLastError();
|
||||
if (err != cudaSuccess) { CU_DBG("poly 0x%04x square %d launch: %s", p->id, s, cudaGetErrorString(err)); goto fail; }
|
||||
err = cudaDeviceSynchronize();
|
||||
if (err != cudaSuccess) { CU_DBG("poly 0x%04x square %d sync: %s", p->id, s, cudaGetErrorString(err)); goto fail; }
|
||||
uint8_t *tmp = cur;
|
||||
cur = nxt;
|
||||
nxt = tmp;
|
||||
}
|
||||
if (cur != cp->d_adv) {
|
||||
err = cudaMemcpy(cp->d_adv, cur, (size_t)nb * 256 * nb,
|
||||
cudaMemcpyDeviceToDevice);
|
||||
if (err != cudaSuccess) { CU_DBG("poly 0x%04x adv copyback: %s", p->id, cudaGetErrorString(err)); goto fail; }
|
||||
}
|
||||
}
|
||||
g_npolys++;
|
||||
return cp;
|
||||
fail:
|
||||
/* Leave no poisoned slot behind: a retry rebuilds from scratch. */
|
||||
cu_poly_cleanup_partial(cp);
|
||||
memset(cp, 0, sizeof(*cp));
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* cached device scratch buffers */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
static uint8_t *g_d_in = NULL;
|
||||
static size_t g_d_in_cap = 0;
|
||||
static uint8_t *g_d_part = NULL;
|
||||
static size_t g_d_part_cap = 0;
|
||||
static uint8_t *g_d_rem = NULL;
|
||||
static size_t g_d_rem_cap = 0;
|
||||
static int *g_d_coff = NULL, *g_d_clen = NULL;
|
||||
static int *g_d_bfirst = NULL, *g_d_bnc = NULL;
|
||||
static size_t g_d_coff_cap = 0;
|
||||
static size_t g_d_clen_cap = 0;
|
||||
static size_t g_d_bfirst_cap = 0;
|
||||
static size_t g_d_bnc_cap = 0;
|
||||
|
||||
static int cu_ensure_u8(uint8_t **ptr, size_t *cap, size_t need)
|
||||
{
|
||||
if (*cap >= need)
|
||||
return 0;
|
||||
if (*ptr)
|
||||
cudaFree(*ptr);
|
||||
size_t ncap = *cap ? *cap : (1u << 20);
|
||||
while (ncap < need)
|
||||
ncap *= 2;
|
||||
if (cudaMalloc(ptr, ncap) != cudaSuccess) {
|
||||
*ptr = NULL;
|
||||
*cap = 0;
|
||||
return -1;
|
||||
}
|
||||
*cap = ncap;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int cu_ensure_int(int **ptr, size_t *cap, size_t need)
|
||||
{
|
||||
if (*cap >= need)
|
||||
return 0;
|
||||
if (*ptr)
|
||||
cudaFree(*ptr);
|
||||
size_t ncap = *cap ? *cap : 4096;
|
||||
while (ncap < need)
|
||||
ncap *= 2;
|
||||
if (cudaMalloc((void **)ptr, ncap * sizeof(int)) != cudaSuccess) {
|
||||
*ptr = NULL;
|
||||
*cap = 0;
|
||||
return -1;
|
||||
}
|
||||
*cap = ncap;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* chunk plan + remainder runner */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/* Blocks are byte strings [bstart[b], bstart[b]+blen[b]).
|
||||
* Chunk 0 of each block is short (len - (n-1)*CHUNK), the rest are
|
||||
* full CHUNK bytes, so every combine step advances by exactly CHUNK. */
|
||||
static int cu_plan(const size_t *bstart, const size_t *blen, int nblocks,
|
||||
int *coff, int *clen, int *bfirst, int *bnc)
|
||||
{
|
||||
int nc = 0;
|
||||
for (int b = 0; b < nblocks; b++) {
|
||||
size_t L = blen[b];
|
||||
int n = (int)((L + BCH_CUDA_CHUNK - 1) / BCH_CUDA_CHUNK);
|
||||
if (n < 1)
|
||||
n = 1;
|
||||
bfirst[b] = nc;
|
||||
bnc[b] = n;
|
||||
size_t first = L - (size_t)(n - 1) * BCH_CUDA_CHUNK;
|
||||
for (int k = 0; k < n; k++) {
|
||||
coff[nc] = (int)(bstart[b] +
|
||||
(k == 0 ? 0 : first + (size_t)(k - 1) * BCH_CUDA_CHUNK));
|
||||
clen[nc] = (int)(k == 0 ? first : BCH_CUDA_CHUNK);
|
||||
nc++;
|
||||
}
|
||||
}
|
||||
return nc;
|
||||
}
|
||||
|
||||
static int cu_remainders(cu_poly_t *cp, int nchunks, int nblocks)
|
||||
{
|
||||
int nb = cp->nb;
|
||||
dim3 pb(256);
|
||||
dim3 pg((unsigned)((nchunks + 255) / 256));
|
||||
switch (nb) {
|
||||
case 3: partial_kernel_t<3><<<pg, pb>>>(g_d_in, g_d_coff, g_d_clen, cp->d_table, g_d_part, nchunks); break;
|
||||
case 6: partial_kernel_t<6><<<pg, pb>>>(g_d_in, g_d_coff, g_d_clen, cp->d_table, g_d_part, nchunks); break;
|
||||
case 11: partial_kernel_t<11><<<pg, pb>>>(g_d_in, g_d_coff, g_d_clen, cp->d_table, g_d_part, nchunks); break;
|
||||
case 22: partial_kernel_t<22><<<pg, pb>>>(g_d_in, g_d_coff, g_d_clen, cp->d_table, g_d_part, nchunks); break;
|
||||
case 44: partial_kernel_t<44><<<pg, pb>>>(g_d_in, g_d_coff, g_d_clen, cp->d_table, g_d_part, nchunks); break;
|
||||
case 88: partial_kernel_t<88><<<pg, pb>>>(g_d_in, g_d_coff, g_d_clen, cp->d_table, g_d_part, nchunks); break;
|
||||
default: partial_kernel_g<<<pg, pb>>>(g_d_in, g_d_coff, g_d_clen, cp->d_table, g_d_part, nchunks, nb); break;
|
||||
}
|
||||
{
|
||||
cudaError_t err = cudaGetLastError();
|
||||
if (err != cudaSuccess) {
|
||||
CU_DBG("partial kernel: %s", cudaGetErrorString(err));
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
dim3 cb(256);
|
||||
dim3 cg((unsigned)((nblocks + 255) / 256));
|
||||
switch (nb) {
|
||||
case 3: combine_kernel_t<3><<<cg, cb>>>(g_d_part, g_d_bfirst, g_d_bnc, cp->d_adv, g_d_rem, nblocks); break;
|
||||
case 6: combine_kernel_t<6><<<cg, cb>>>(g_d_part, g_d_bfirst, g_d_bnc, cp->d_adv, g_d_rem, nblocks); break;
|
||||
case 11: combine_kernel_t<11><<<cg, cb>>>(g_d_part, g_d_bfirst, g_d_bnc, cp->d_adv, g_d_rem, nblocks); break;
|
||||
case 22: combine_kernel_t<22><<<cg, cb>>>(g_d_part, g_d_bfirst, g_d_bnc, cp->d_adv, g_d_rem, nblocks); break;
|
||||
case 44: combine_kernel_t<44><<<cg, cb>>>(g_d_part, g_d_bfirst, g_d_bnc, cp->d_adv, g_d_rem, nblocks); break;
|
||||
case 88: combine_kernel_t<88><<<cg, cb>>>(g_d_part, g_d_bfirst, g_d_bnc, cp->d_adv, g_d_rem, nblocks); break;
|
||||
default: combine_kernel_g<<<cg, cb>>>(g_d_part, g_d_bfirst, g_d_bnc, cp->d_adv, g_d_rem, nblocks, nb); break;
|
||||
}
|
||||
{
|
||||
cudaError_t err = cudaGetLastError();
|
||||
if (err != cudaSuccess) {
|
||||
CU_DBG("combine kernel: %s", cudaGetErrorString(err));
|
||||
return -1;
|
||||
}
|
||||
err = cudaDeviceSynchronize();
|
||||
if (err != cudaSuccess) {
|
||||
CU_DBG("remainders sync: %s", cudaGetErrorString(err));
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Upload the chunk plan; returns 0 or -1. */
|
||||
static int cu_upload_plan(const int *coff, const int *clen,
|
||||
const int *bfirst, const int *bnc,
|
||||
int nchunks, int nblocks)
|
||||
{
|
||||
if (cu_ensure_int(&g_d_coff, &g_d_coff_cap, (size_t)nchunks) != 0)
|
||||
return -1;
|
||||
if (cu_ensure_int(&g_d_clen, &g_d_clen_cap, (size_t)nchunks) != 0)
|
||||
return -1;
|
||||
if (cu_ensure_int(&g_d_bfirst, &g_d_bfirst_cap, (size_t)nblocks) != 0)
|
||||
return -1;
|
||||
if (cu_ensure_int(&g_d_bnc, &g_d_bnc_cap, (size_t)nblocks) != 0)
|
||||
return -1;
|
||||
if (cudaMemcpy(g_d_coff, coff, (size_t)nchunks * sizeof(int),
|
||||
cudaMemcpyHostToDevice) != cudaSuccess)
|
||||
return -1;
|
||||
if (cudaMemcpy(g_d_clen, clen, (size_t)nchunks * sizeof(int),
|
||||
cudaMemcpyHostToDevice) != cudaSuccess)
|
||||
return -1;
|
||||
if (cudaMemcpy(g_d_bfirst, bfirst, (size_t)nblocks * sizeof(int),
|
||||
cudaMemcpyHostToDevice) != cudaSuccess)
|
||||
return -1;
|
||||
if (cudaMemcpy(g_d_bnc, bnc, (size_t)nblocks * sizeof(int),
|
||||
cudaMemcpyHostToDevice) != cudaSuccess)
|
||||
return -1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* public API */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
extern "C" size_t bch_cuda_encode(const uint8_t *data, size_t len,
|
||||
const bch_poly_t *p, uint8_t *out)
|
||||
{
|
||||
if (!data || !out || !p || len == 0)
|
||||
return 0;
|
||||
if (!bch_cuda_available())
|
||||
return 0;
|
||||
cu_poly_t *cp = cu_poly_get(p);
|
||||
if (!cp)
|
||||
return 0;
|
||||
int nb = cp->nb;
|
||||
size_t maxd = bch_max_data(p);
|
||||
int nblocks = (int)((len + maxd - 1) / maxd);
|
||||
|
||||
size_t *bstart = (size_t *)malloc(sizeof(size_t) * (size_t)nblocks);
|
||||
size_t *blen = (size_t *)malloc(sizeof(size_t) * (size_t)nblocks);
|
||||
int *coff = NULL, *clen = NULL, *bfirst = NULL, *bnc = NULL;
|
||||
uint8_t *rem = NULL;
|
||||
size_t ret = 0;
|
||||
if (!bstart || !blen)
|
||||
goto done;
|
||||
{
|
||||
size_t off = 0;
|
||||
for (int b = 0; b < nblocks; b++) {
|
||||
size_t chunk = len - off;
|
||||
if (chunk > maxd)
|
||||
chunk = maxd;
|
||||
bstart[b] = off;
|
||||
blen[b] = chunk;
|
||||
off += chunk;
|
||||
}
|
||||
}
|
||||
/* Worst-case chunk count: every block split at CHUNK + 1. */
|
||||
coff = (int *)malloc(sizeof(int) * (size_t)(nblocks * (maxd / BCH_CUDA_CHUNK + 2)));
|
||||
clen = (int *)malloc(sizeof(int) * (size_t)(nblocks * (maxd / BCH_CUDA_CHUNK + 2)));
|
||||
bfirst = (int *)malloc(sizeof(int) * (size_t)nblocks);
|
||||
bnc = (int *)malloc(sizeof(int) * (size_t)nblocks);
|
||||
if (!coff || !clen || !bfirst || !bnc)
|
||||
goto done;
|
||||
{
|
||||
int nchunks = cu_plan(bstart, blen, nblocks, coff, clen, bfirst, bnc);
|
||||
if (cu_ensure_u8(&g_d_in, &g_d_in_cap, len) != 0)
|
||||
goto done;
|
||||
if (cu_ensure_u8(&g_d_part, &g_d_part_cap, (size_t)nchunks * nb) != 0)
|
||||
goto done;
|
||||
if (cu_ensure_u8(&g_d_rem, &g_d_rem_cap, (size_t)nblocks * nb) != 0)
|
||||
goto done;
|
||||
if (cudaMemcpy(g_d_in, data, len, cudaMemcpyHostToDevice) != cudaSuccess)
|
||||
goto done;
|
||||
if (cu_upload_plan(coff, clen, bfirst, bnc, nchunks, nblocks) != 0)
|
||||
goto done;
|
||||
if (cu_remainders(cp, nchunks, nblocks) != 0)
|
||||
goto done;
|
||||
rem = (uint8_t *)malloc((size_t)nblocks * nb);
|
||||
if (!rem)
|
||||
goto done;
|
||||
if (cudaMemcpy(rem, g_d_rem, (size_t)nblocks * nb,
|
||||
cudaMemcpyDeviceToHost) != cudaSuccess)
|
||||
goto done;
|
||||
size_t woff = 0;
|
||||
for (int b = 0; b < nblocks; b++) {
|
||||
memcpy(out + woff, data + bstart[b], blen[b]);
|
||||
memcpy(out + woff + blen[b], rem + (size_t)b * nb, nb);
|
||||
woff += blen[b] + nb;
|
||||
}
|
||||
ret = woff;
|
||||
}
|
||||
done:
|
||||
free(bstart);
|
||||
free(blen);
|
||||
free(coff);
|
||||
free(clen);
|
||||
free(bfirst);
|
||||
free(bnc);
|
||||
free(rem);
|
||||
return ret;
|
||||
}
|
||||
|
||||
extern "C" int bch_cuda_decode(const uint8_t *in, size_t len, size_t orig_len,
|
||||
const bch_poly_t *p, uint8_t *out,
|
||||
int *corrected)
|
||||
{
|
||||
if (corrected)
|
||||
*corrected = 0;
|
||||
if (!in || !out || !p)
|
||||
return -2;
|
||||
if (orig_len == 0)
|
||||
return -2; /* CPU handles the empty-blob block */
|
||||
if (len != bch_encoded_len(orig_len, p))
|
||||
return -2; /* malformed length: let the CPU path report it */
|
||||
if (!bch_cuda_available())
|
||||
return -2;
|
||||
cu_poly_t *cp = cu_poly_get(p);
|
||||
if (!cp)
|
||||
return -2;
|
||||
int nb = cp->nb;
|
||||
int r = cp->r;
|
||||
size_t maxd = bch_max_data(p);
|
||||
int nblocks = (int)((orig_len + maxd - 1) / maxd);
|
||||
|
||||
size_t *bstart = (size_t *)malloc(sizeof(size_t) * (size_t)nblocks);
|
||||
size_t *blen = (size_t *)malloc(sizeof(size_t) * (size_t)nblocks);
|
||||
size_t *dlen = (size_t *)malloc(sizeof(size_t) * (size_t)nblocks);
|
||||
size_t *doff = (size_t *)malloc(sizeof(size_t) * (size_t)nblocks);
|
||||
int *coff = NULL, *clen = NULL, *bfirst = NULL, *bnc = NULL;
|
||||
uint8_t *rem = NULL;
|
||||
int ret = -2;
|
||||
if (!bstart || !blen || !dlen || !doff)
|
||||
goto done;
|
||||
{
|
||||
size_t off = 0, roff = 0;
|
||||
for (int b = 0; b < nblocks; b++) {
|
||||
size_t chunk = orig_len - off;
|
||||
if (chunk > maxd)
|
||||
chunk = maxd;
|
||||
dlen[b] = chunk;
|
||||
doff[b] = off;
|
||||
bstart[b] = roff; /* stored offset */
|
||||
blen[b] = chunk + (size_t)(r / 8); /* data + whole parity bytes */
|
||||
off += chunk;
|
||||
roff += chunk + nb;
|
||||
}
|
||||
}
|
||||
coff = (int *)malloc(sizeof(int) * (size_t)(nblocks * (maxd / BCH_CUDA_CHUNK + 2)));
|
||||
clen = (int *)malloc(sizeof(int) * (size_t)(nblocks * (maxd / BCH_CUDA_CHUNK + 2)));
|
||||
bfirst = (int *)malloc(sizeof(int) * (size_t)nblocks);
|
||||
bnc = (int *)malloc(sizeof(int) * (size_t)nblocks);
|
||||
if (!coff || !clen || !bfirst || !bnc)
|
||||
goto done;
|
||||
{
|
||||
int nchunks = cu_plan(bstart, blen, nblocks, coff, clen, bfirst, bnc);
|
||||
if (cu_ensure_u8(&g_d_in, &g_d_in_cap, len) != 0)
|
||||
goto done;
|
||||
if (cu_ensure_u8(&g_d_part, &g_d_part_cap, (size_t)nchunks * nb) != 0)
|
||||
goto done;
|
||||
if (cu_ensure_u8(&g_d_rem, &g_d_rem_cap, (size_t)nblocks * nb) != 0)
|
||||
goto done;
|
||||
if (cudaMemcpy(g_d_in, in, len, cudaMemcpyHostToDevice) != cudaSuccess)
|
||||
goto done;
|
||||
if (cu_upload_plan(coff, clen, bfirst, bnc, nchunks, nblocks) != 0)
|
||||
goto done;
|
||||
if (cu_remainders(cp, nchunks, nblocks) != 0)
|
||||
goto done;
|
||||
rem = (uint8_t *)malloc((size_t)nblocks * nb);
|
||||
if (!rem)
|
||||
goto done;
|
||||
if (cudaMemcpy(rem, g_d_rem, (size_t)nblocks * nb,
|
||||
cudaMemcpyDeviceToHost) != cudaSuccess)
|
||||
goto done;
|
||||
int whole = r / 8;
|
||||
int total_corr = 0;
|
||||
for (int b = 0; b < nblocks; b++) {
|
||||
uint8_t *rb = rem + (size_t)b * nb;
|
||||
/* Feed the remaining (r%8) parity bits, MSB first, from
|
||||
* the final parity byte -- the same tail rem_of_codeword
|
||||
* feeds bit-by-bit. */
|
||||
const uint8_t *par = in + bstart[b] + dlen[b];
|
||||
for (int bit = 7; bit >= 8 - (r % 8) && (r % 8); bit--)
|
||||
cu_rem_bitstep(rb, (par[whole] >> bit) & 1, cp->glow, nb);
|
||||
if (cu_rem_is_zero(rb, nb)) {
|
||||
memcpy(out + doff[b], in + bstart[b], dlen[b]);
|
||||
continue;
|
||||
}
|
||||
/* Dirty block: CPU BM + Chien, identical to the CPU path. */
|
||||
int c1 = 0;
|
||||
if (bch_decode_block(in + bstart[b], dlen[b] + nb, dlen[b], p,
|
||||
out + doff[b], &c1) != 0) {
|
||||
ret = -1;
|
||||
goto done;
|
||||
}
|
||||
total_corr += c1;
|
||||
}
|
||||
if (corrected)
|
||||
*corrected = total_corr;
|
||||
ret = 0;
|
||||
}
|
||||
done:
|
||||
free(bstart);
|
||||
free(blen);
|
||||
free(dlen);
|
||||
free(doff);
|
||||
free(coff);
|
||||
free(clen);
|
||||
free(bfirst);
|
||||
free(bnc);
|
||||
free(rem);
|
||||
return ret;
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
/* bch_cuda.h - CUDA BCH remainder for lzply.
|
||||
*
|
||||
* GPU fast path for the BCH remainder (bch_encode / bch_decode).
|
||||
* The remainder is GF(2)-linear, so parallel-CRC-style chunking
|
||||
* applies: split each block into 4096-byte chunks, compute each
|
||||
* chunk's partial remainder (zero initial state) on the GPU, then
|
||||
* combine with a precomputed advance-by-4096-bytes table
|
||||
* (Adv(S) = the state S advanced by 4096 zero bytes; built on the
|
||||
* device by repeated squaring from Adv_1).
|
||||
*
|
||||
* Chunking puts the short chunk FIRST in each block, so every combine
|
||||
* step advances by exactly 4096 bytes -- no arbitrary-length advance
|
||||
* table is ever needed.
|
||||
*
|
||||
* Encode is fully GPU (remainder per block -> parity bytes). Decode
|
||||
* uses the GPU remainder for the clean path (remainder zero -> copy
|
||||
* the data out); a block with a nonzero remainder falls back to the
|
||||
* CPU bch_decode_block (Berlekamp-Massey + Chien), so correction
|
||||
* behaviour is identical to the CPU path.
|
||||
*
|
||||
* All functions fall back gracefully: bch_cuda_encode returns 0 and
|
||||
* bch_cuda_decode returns -2 on any CUDA problem, and bch.c treats
|
||||
* those as "use the CPU path". bch_cuda_available() is 0 when no
|
||||
* CUDA device is present. A CPU-only build links bch_cuda_stub.c,
|
||||
* which defines these three functions to report "no GPU", so the
|
||||
* references always resolve. (bch.c also declares them
|
||||
* __attribute__((weak)) as a fallback for out-of-tree consumers;
|
||||
* the build itself does not rely on weak-symbol resolution, which
|
||||
* macOS ld64 does not provide for declarations.)
|
||||
*/
|
||||
#ifndef LZPLY_BCH_CUDA_H
|
||||
#define LZPLY_BCH_CUDA_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include "bch.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* 1 if a CUDA device is present and usable, 0 otherwise. */
|
||||
int bch_cuda_available(void);
|
||||
|
||||
/* Encode a whole blob on the GPU (same contract as bch_encode).
|
||||
* Returns the stored length, or 0 on any failure (caller: use CPU). */
|
||||
size_t bch_cuda_encode(const uint8_t *data, size_t len,
|
||||
const bch_poly_t *p, uint8_t *out);
|
||||
|
||||
/* Decode a whole blob on the GPU (same contract as bch_decode).
|
||||
* Returns 0 on success, -1 if any block is uncorrectable, -2 on an
|
||||
* internal/CUDA error (caller: fall back to the CPU path). */
|
||||
int bch_cuda_decode(const uint8_t *in, size_t len, size_t orig_len,
|
||||
const bch_poly_t *p, uint8_t *out, int *corrected);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* LZPLY_BCH_CUDA_H */
|
||||
@@ -0,0 +1,53 @@
|
||||
/* bch_cuda_stub.c - CPU-only fallback for the CUDA BCH entry points.
|
||||
*
|
||||
* Defines the three symbols bch.c references (bch_cuda_available,
|
||||
* bch_cuda_encode, bch_cuda_decode) for builds without nvcc, so a
|
||||
* CPU-only link always resolves. The stub reports "no GPU": the
|
||||
* caller in bch.c then takes the CPU path, exactly as it does when
|
||||
* a CUDA build is present but no device is found.
|
||||
*
|
||||
* This exists because the weak-symbol fallback it replaces does not
|
||||
* work on macOS: bch.c declares these functions
|
||||
* __attribute__((weak)), expecting them to resolve to NULL when no
|
||||
* CUDA object is linked. GNU ld does that; macOS ld64 does not --
|
||||
* a weak declaration is a weak definition, not a weak import, so
|
||||
* the link fails with undefined _bch_cuda_available/_encode/_decode
|
||||
* symbols. Defining the symbols outright removes all reliance on
|
||||
* linker-specific weak-symbol behaviour, on every platform.
|
||||
*
|
||||
* The stub is built only when nvcc is absent (see the Makefile:
|
||||
* CUDA_STUB_OBJ is empty whenever CUDA_OBJ is set), so the symbols
|
||||
* are defined exactly once in every build.
|
||||
*/
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#include "bch.h"
|
||||
#include "bch_cuda.h"
|
||||
|
||||
int bch_cuda_available(void)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
size_t bch_cuda_encode(const uint8_t *data, size_t len,
|
||||
const bch_poly_t *p, uint8_t *out)
|
||||
{
|
||||
(void)data;
|
||||
(void)len;
|
||||
(void)p;
|
||||
(void)out;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int bch_cuda_decode(const uint8_t *in, size_t len, size_t orig_len,
|
||||
const bch_poly_t *p, uint8_t *out, int *corrected)
|
||||
{
|
||||
(void)in;
|
||||
(void)len;
|
||||
(void)orig_len;
|
||||
(void)p;
|
||||
(void)out;
|
||||
(void)corrected;
|
||||
return -2;
|
||||
}
|
||||
+388
@@ -0,0 +1,388 @@
|
||||
/* bch_cuda_test.c - verification + benchmark for the CUDA BCH path.
|
||||
*
|
||||
* 1. Correctness: for t in {1,2,4,8,16,32} and a spread of blob sizes
|
||||
* (1 B .. 1 MiB, incl. chunk and block boundaries), GPU encode must
|
||||
* be byte-identical to a CPU reference encode built block-by-block
|
||||
* from the INDEPENDENT brute-force remainder (bit-by-bit long
|
||||
* division -- no table LFSR, no dispatch, so the comparison cannot
|
||||
* be circular: for len >= 1MB bch_encode itself dispatches to the
|
||||
* GPU). GPU decode of a CPU-encoded blob (clean, and with up to t
|
||||
* flipped bits in one block) must match a per-block CPU decode via
|
||||
* bch_decode_block; a t+1-bit flip must make GPU and CPU decode
|
||||
* agree.
|
||||
* 2. Benchmark: GPU encode/decode MB/s at 1/4/50 MB for t=8/32
|
||||
* (median of 5), via the direct CUDA entry points and via the
|
||||
* bch_encode/bch_decode dispatch (they must agree -- dispatch
|
||||
* overhead ~0). The first CUDA call (table build + context init)
|
||||
* is timed separately from steady state. True CPU numbers come
|
||||
* from bch_bench_cpu (built without bch_cuda.o); compare against
|
||||
* those in the report.
|
||||
*
|
||||
* Usage: bch_cuda_test [datafile]
|
||||
* datafile: blob for the benchmark (default: generated 50 MiB).
|
||||
* Exit 0 only if every check passes.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
#include "bch.h"
|
||||
#include "bch_cuda.h"
|
||||
|
||||
static int fails = 0;
|
||||
static int checks = 0;
|
||||
#define CHECK(cond, ...) do { \
|
||||
checks++; \
|
||||
if (!(cond)) { fails++; printf("FAIL: " __VA_ARGS__); printf("\n"); } \
|
||||
} while (0)
|
||||
|
||||
static uint64_t rng_state = 0x12345678abcdefULL;
|
||||
static uint64_t xr(void)
|
||||
{
|
||||
rng_state ^= rng_state << 13;
|
||||
rng_state ^= rng_state >> 7;
|
||||
rng_state ^= rng_state << 17;
|
||||
return rng_state;
|
||||
}
|
||||
|
||||
static void rand_bytes(uint8_t *buf, size_t n)
|
||||
{
|
||||
for (size_t i = 0; i < n; i++)
|
||||
buf[i] = (uint8_t)(xr() & 0xff);
|
||||
}
|
||||
|
||||
static void flip_bits(uint8_t *buf, size_t nbits, int k)
|
||||
{
|
||||
size_t *pos = malloc(sizeof(size_t) * (size_t)(k > 0 ? k : 1));
|
||||
int got = 0;
|
||||
while (got < k) {
|
||||
size_t p = (size_t)(xr() % nbits);
|
||||
int dup = 0;
|
||||
for (int i = 0; i < got; i++)
|
||||
if (pos[i] == p)
|
||||
dup = 1;
|
||||
if (!dup)
|
||||
pos[got++] = p;
|
||||
}
|
||||
for (int i = 0; i < k; i++)
|
||||
buf[pos[i] / 8] ^= (uint8_t)(1u << (7 - (pos[i] % 8)));
|
||||
free(pos);
|
||||
}
|
||||
|
||||
static double now_s(void)
|
||||
{
|
||||
struct timespec ts;
|
||||
clock_gettime(CLOCK_MONOTONIC, &ts);
|
||||
return (double)ts.tv_sec + (double)ts.tv_nsec * 1e-9;
|
||||
}
|
||||
|
||||
static int cmp_dbl(const void *a, const void *b)
|
||||
{
|
||||
double x = *(const double *)a, y = *(const double *)b;
|
||||
return (x > y) - (x < y);
|
||||
}
|
||||
|
||||
static double median(double *v, int n)
|
||||
{
|
||||
qsort(v, (size_t)n, sizeof(double), cmp_dbl);
|
||||
return v[n / 2];
|
||||
}
|
||||
|
||||
static int t_index(int t)
|
||||
{
|
||||
switch (t) {
|
||||
case 1: return 0;
|
||||
case 2: return 1;
|
||||
case 4: return 2;
|
||||
case 8: return 3;
|
||||
case 16: return 4;
|
||||
case 32: return 5;
|
||||
default: return -1;
|
||||
}
|
||||
}
|
||||
|
||||
/* Same selection as lzply_lib: auto-pick, else largest m for the t. */
|
||||
static const bch_poly_t *test_poly(size_t len, int t)
|
||||
{
|
||||
const bch_poly_t *p = bch_poly_for_data(len, t);
|
||||
if (p)
|
||||
return p;
|
||||
int ti = t_index(t);
|
||||
if (ti < 0)
|
||||
return NULL;
|
||||
for (int m = BCH_MAX_M; m >= BCH_MIN_M; m--) {
|
||||
uint16_t id = bch_poly_by_mt[m - BCH_MIN_M][ti];
|
||||
if (id)
|
||||
return bch_poly_by_id(id);
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* CPU reference encode: block-by-block, brute-force remainder. */
|
||||
static void ref_encode(const uint8_t *data, size_t len,
|
||||
const bch_poly_t *p, uint8_t *out)
|
||||
{
|
||||
size_t maxd = bch_max_data(p);
|
||||
size_t off = 0, woff = 0;
|
||||
if (len == 0) {
|
||||
if (bch_remainder_bruteforce(data, 0, p, out) != 0) {
|
||||
printf("ref_encode: bruteforce failed\n");
|
||||
exit(1);
|
||||
}
|
||||
return;
|
||||
}
|
||||
while (off < len) {
|
||||
size_t chunk = len - off;
|
||||
if (chunk > maxd)
|
||||
chunk = maxd;
|
||||
size_t nb = bch_block_stored_len(chunk, p) - chunk;
|
||||
uint8_t *rem = malloc(nb);
|
||||
if (bch_remainder_bruteforce(data + off, chunk, p, rem) != 0) {
|
||||
printf("ref_encode: bruteforce failed\n");
|
||||
exit(1);
|
||||
}
|
||||
memcpy(out + woff, data + off, chunk);
|
||||
memcpy(out + woff + chunk, rem, nb);
|
||||
free(rem);
|
||||
woff += bch_block_stored_len(chunk, p);
|
||||
off += chunk;
|
||||
}
|
||||
}
|
||||
|
||||
/* CPU reference decode: block-by-block via bch_decode_block.
|
||||
* Returns 0 ok, -1 uncorrectable. */
|
||||
static int ref_decode(const uint8_t *in, size_t len, size_t orig_len,
|
||||
const bch_poly_t *p, uint8_t *out, int *corrected)
|
||||
{
|
||||
if (corrected)
|
||||
*corrected = 0;
|
||||
size_t maxd = bch_max_data(p);
|
||||
size_t off = 0, roff = 0;
|
||||
int total = 0;
|
||||
if (orig_len == 0) {
|
||||
if (len != bch_block_stored_len(0, p))
|
||||
return -1;
|
||||
int c1 = 0;
|
||||
if (bch_decode_block(in, len, 0, p, out, &c1) != 0)
|
||||
return -1;
|
||||
if (corrected)
|
||||
*corrected = c1;
|
||||
return 0;
|
||||
}
|
||||
while (off < orig_len) {
|
||||
size_t chunk = orig_len - off;
|
||||
if (chunk > maxd)
|
||||
chunk = maxd;
|
||||
size_t slen = bch_block_stored_len(chunk, p);
|
||||
if (roff + slen > len)
|
||||
return -1;
|
||||
int c1 = 0;
|
||||
if (bch_decode_block(in + roff, slen, chunk, p, out + off, &c1) != 0)
|
||||
return -1;
|
||||
total += c1;
|
||||
roff += slen;
|
||||
off += chunk;
|
||||
}
|
||||
if (corrected)
|
||||
*corrected = total;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void correctness_case(const uint8_t *data, size_t len, int t)
|
||||
{
|
||||
const bch_poly_t *p = test_poly(len, t);
|
||||
if (!p) {
|
||||
printf("SKIP t=%d len=%zu: no poly\n", t, len);
|
||||
return;
|
||||
}
|
||||
size_t eclen = bch_encoded_len(len, p);
|
||||
uint8_t *enc_cpu = malloc(eclen ? eclen : 1);
|
||||
uint8_t *enc_gpu = malloc(eclen ? eclen : 1);
|
||||
uint8_t *dec = malloc(len ? len : 1);
|
||||
uint8_t *dec2 = malloc(len ? len : 1);
|
||||
uint8_t *work = malloc(eclen ? eclen : 1);
|
||||
if (!enc_cpu || !enc_gpu || !dec || !dec2 || !work) {
|
||||
printf("OOM\n");
|
||||
exit(1);
|
||||
}
|
||||
ref_encode(data, len, p, enc_cpu);
|
||||
size_t gn = bch_cuda_encode(data, len, p, enc_gpu);
|
||||
CHECK(gn == eclen, "t=%d len=%zu gpu encode len %zu != %zu",
|
||||
t, len, gn, eclen);
|
||||
CHECK(gn == eclen && memcmp(enc_cpu, enc_gpu, eclen) == 0,
|
||||
"t=%d len=%zu poly 0x%04x m=%d gpu encode != cpu(bruteforce) encode",
|
||||
t, len, p->id, p->m);
|
||||
/* clean decode both ways */
|
||||
int cc = -1, gc = -1;
|
||||
CHECK(ref_decode(enc_cpu, eclen, len, p, dec, &cc) == 0 &&
|
||||
memcmp(dec, data, len) == 0,
|
||||
"t=%d len=%zu cpu decode of cpu encode", t, len);
|
||||
CHECK(bch_cuda_decode(enc_cpu, eclen, len, p, dec2, &gc) == 0 &&
|
||||
memcmp(dec2, data, len) == 0 && gc == 0,
|
||||
"t=%d len=%zu gpu decode of cpu encode (gc=%d)", t, len, gc);
|
||||
CHECK(ref_decode(enc_gpu, eclen, len, p, dec, &cc) == 0 &&
|
||||
memcmp(dec, data, len) == 0,
|
||||
"t=%d len=%zu cpu decode of gpu encode", t, len);
|
||||
CHECK(bch_cuda_decode(enc_gpu, eclen, len, p, dec2, &gc) == 0 &&
|
||||
memcmp(dec2, data, len) == 0 && gc == 0,
|
||||
"t=%d len=%zu gpu decode of gpu encode", t, len);
|
||||
/* dirty decode: flip k<=t bits in the first block. */
|
||||
if (len > 0) {
|
||||
size_t first = len < bch_max_data(p) ? len : bch_max_data(p);
|
||||
size_t nbits = (size_t)8 * first + p->r;
|
||||
int k = t < 3 ? t : 3;
|
||||
memcpy(work, enc_cpu, eclen);
|
||||
flip_bits(work, nbits, k);
|
||||
int rc_cpu = ref_decode(work, eclen, len, p, dec, &cc);
|
||||
int rc_gpu = bch_cuda_decode(work, eclen, len, p, dec2, &gc);
|
||||
CHECK(rc_cpu == rc_gpu,
|
||||
"t=%d len=%zu %d-bit flip: cpu rc=%d gpu rc=%d",
|
||||
t, len, k, rc_cpu, rc_gpu);
|
||||
if (rc_cpu == 0)
|
||||
CHECK(memcmp(dec, dec2, len) == 0 && cc == gc,
|
||||
"t=%d len=%zu %d-bit flip: decoded bytes/corr differ (cc=%d gc=%d)",
|
||||
t, len, k, cc, gc);
|
||||
/* t+1 bits in one block: GPU and CPU decode must agree. */
|
||||
memcpy(work, enc_cpu, eclen);
|
||||
flip_bits(work, nbits, t + 1);
|
||||
rc_cpu = ref_decode(work, eclen, len, p, dec, &cc);
|
||||
rc_gpu = bch_cuda_decode(work, eclen, len, p, dec2, &gc);
|
||||
CHECK(rc_cpu == rc_gpu,
|
||||
"t=%d len=%zu %d-bit flip: cpu rc=%d gpu rc=%d (must agree)",
|
||||
t, len, t + 1, rc_cpu, rc_gpu);
|
||||
if (rc_cpu == 0)
|
||||
CHECK(memcmp(dec, dec2, len) == 0,
|
||||
"t=%d len=%zu %d-bit flip: both decoded but differ",
|
||||
t, len, t + 1);
|
||||
}
|
||||
free(enc_cpu);
|
||||
free(enc_gpu);
|
||||
free(dec);
|
||||
free(dec2);
|
||||
free(work);
|
||||
}
|
||||
|
||||
static void bench_case(const uint8_t *data, size_t len, int t)
|
||||
{
|
||||
const bch_poly_t *p = test_poly(len, t);
|
||||
if (!p) {
|
||||
printf("SKIP bench t=%d len=%zu: no poly\n", t, len);
|
||||
return;
|
||||
}
|
||||
size_t eclen = bch_encoded_len(len, p);
|
||||
uint8_t *enc = malloc(eclen);
|
||||
uint8_t *enc2 = malloc(eclen);
|
||||
uint8_t *dec = malloc(len);
|
||||
double ts[5];
|
||||
double s, e;
|
||||
int corr = 0;
|
||||
|
||||
/* first-call timing (table build + context init) */
|
||||
s = now_s();
|
||||
size_t gn = bch_cuda_encode(data, len, p, enc2);
|
||||
e = now_s();
|
||||
printf("t=%-2d len=%8zu first-gpu-encode %7.4f s (%7.1f MB/s, incl table build)\n",
|
||||
t, len, e - s, (double)len / 1048576.0 / (e - s));
|
||||
if (gn != eclen) { printf("gpu enc fail\n"); exit(1); }
|
||||
/* steady-state GPU direct */
|
||||
for (int i = 0; i < 5; i++) {
|
||||
s = now_s();
|
||||
gn = bch_cuda_encode(data, len, p, enc2);
|
||||
e = now_s();
|
||||
ts[i] = e - s;
|
||||
if (gn != eclen) { printf("gpu enc fail\n"); exit(1); }
|
||||
}
|
||||
double gpu_enc = median(ts, 5);
|
||||
/* dispatch path (bch_encode): must match GPU direct */
|
||||
for (int i = 0; i < 5; i++) {
|
||||
s = now_s();
|
||||
if (bch_encode(data, len, p, enc) != eclen) { printf("disp enc fail\n"); exit(1); }
|
||||
e = now_s();
|
||||
ts[i] = e - s;
|
||||
}
|
||||
double disp_enc = median(ts, 5);
|
||||
printf("t=%-2d len=%8zu ENCODE gpu-direct %7.4f s %8.1f MB/s | dispatch %7.4f s %8.1f MB/s | equal=%d\n",
|
||||
t, len, gpu_enc, (double)len / 1048576.0 / gpu_enc,
|
||||
disp_enc, (double)len / 1048576.0 / disp_enc,
|
||||
memcmp(enc, enc2, eclen) == 0);
|
||||
for (int i = 0; i < 5; i++) {
|
||||
s = now_s();
|
||||
if (bch_cuda_decode(enc, eclen, len, p, dec, &corr) != 0) { printf("gpu dec fail\n"); exit(1); }
|
||||
e = now_s();
|
||||
ts[i] = e - s;
|
||||
}
|
||||
double gpu_dec = median(ts, 5);
|
||||
for (int i = 0; i < 5; i++) {
|
||||
s = now_s();
|
||||
if (bch_decode(enc, eclen, len, p, dec, &corr) != 0) { printf("disp dec fail\n"); exit(1); }
|
||||
e = now_s();
|
||||
ts[i] = e - s;
|
||||
}
|
||||
double disp_dec = median(ts, 5);
|
||||
printf("t=%-2d len=%8zu DECODE gpu-direct %7.4f s %8.1f MB/s | dispatch %7.4f s %8.1f MB/s\n",
|
||||
t, len, gpu_dec, (double)len / 1048576.0 / gpu_dec,
|
||||
disp_dec, (double)len / 1048576.0 / disp_dec);
|
||||
CHECK(memcmp(dec, data, len) == 0, "t=%d len=%zu bench round-trip", t, len);
|
||||
free(enc);
|
||||
free(enc2);
|
||||
free(dec);
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
printf("CUDA available: %d\n", bch_cuda_available());
|
||||
if (!bch_cuda_available()) {
|
||||
printf("NO CUDA DEVICE -- cannot test\n");
|
||||
return 1;
|
||||
}
|
||||
/* correctness grid */
|
||||
static const size_t sizes[] = { 1, 2, 100, 4095, 4096, 4097, 8192,
|
||||
65536, 524265, 524266, 1048576 };
|
||||
static const int ts_[] = { 1, 2, 4, 8, 16, 32 };
|
||||
size_t maxlen = 1048576;
|
||||
uint8_t *buf = malloc(maxlen);
|
||||
if (!buf) return 1;
|
||||
rand_bytes(buf, maxlen);
|
||||
for (size_t si = 0; si < sizeof(sizes) / sizeof(sizes[0]); si++) {
|
||||
for (size_t ti = 0; ti < sizeof(ts_) / sizeof(ts_[0]); ti++) {
|
||||
correctness_case(buf, sizes[si], ts_[ti]);
|
||||
}
|
||||
}
|
||||
printf("correctness: %d checks, %d failures\n", checks, fails);
|
||||
if (fails) {
|
||||
printf("CORRECTNESS FAILED\n");
|
||||
return 1;
|
||||
}
|
||||
/* benchmark data */
|
||||
uint8_t *big = NULL;
|
||||
size_t biglen = 0;
|
||||
if (argc > 1) {
|
||||
FILE *f = fopen(argv[1], "rb");
|
||||
if (!f) { perror("fopen"); return 1; }
|
||||
fseek(f, 0, SEEK_END);
|
||||
long n = ftell(f);
|
||||
fseek(f, 0, SEEK_SET);
|
||||
biglen = (size_t)n;
|
||||
big = malloc(biglen);
|
||||
if (fread(big, 1, biglen, f) != biglen) { printf("short read\n"); return 1; }
|
||||
fclose(f);
|
||||
} else {
|
||||
biglen = 50u << 20;
|
||||
big = malloc(biglen);
|
||||
rand_bytes(big, biglen);
|
||||
}
|
||||
printf("bench blob %zu bytes (%.1f MiB)\n", biglen,
|
||||
(double)biglen / 1048576.0);
|
||||
for (size_t bi = 0; bi < 3; bi++) {
|
||||
size_t L = bi == 0 ? (1u << 20) : bi == 1 ? (4u << 20) : biglen;
|
||||
if (L > biglen)
|
||||
L = biglen;
|
||||
bench_case(big, L, 8);
|
||||
bench_case(big, L, 32);
|
||||
}
|
||||
free(buf);
|
||||
free(big);
|
||||
printf("checks=%d fails=%d %s\n", checks, fails,
|
||||
fails ? "FAILED" : "ALL OK");
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
+205
@@ -398,6 +398,211 @@ int main(int argc, char **argv)
|
||||
CHECK(silent == 0, "pass2: %d silent wrong outputs", silent);
|
||||
}
|
||||
|
||||
/* --- 8: deep repair (Chase-1 / Chase-2 past t) --- */
|
||||
{
|
||||
/* Small blocks (D=512) so the exhaustive Chase-1 scan is
|
||||
* fast. For each t, corrupt with t+1 bits (one past the
|
||||
* limit) and t+2 bits (two past). Invariants checked:
|
||||
* - standard decode fails at t+1/t+2 (control: the repair
|
||||
* levels are actually needed);
|
||||
* - Chase-1 recovers t+1 essentially always (flipping any
|
||||
* one true error leaves t errors, which BM corrects --
|
||||
* this is a theorem, not luck);
|
||||
* - Chase-1 NEVER recovers t+2 (one flip + <= t Chien
|
||||
* corrections cannot span t+2 errors -- also a theorem);
|
||||
* - Chase-2 recovers t+2 sometimes (its first-element list
|
||||
* must contain a true error; with 128 first elements the
|
||||
* rate is roughly 1 - (1 - (t+2)/nbits)^128 -- measured,
|
||||
* not assumed; the t+2 cells use 256-byte blocks so the
|
||||
* rate is high enough to assert on);
|
||||
* - every candidate a Chase call returns is a VALID
|
||||
* codeword (zero remainder) -- wrong candidates are
|
||||
* possible in principle, so the test re-decodes each
|
||||
* returned candidate and requires it to decode cleanly;
|
||||
* the caller (CRC16/SHA-256) is what rejects wrong ones.
|
||||
* - a deadline in the past stops the scan with partial=1.
|
||||
* Deterministic: fixed RNG seed (argv seed or default). */
|
||||
static const int ts[] = { 4, 8 };
|
||||
int rec1 = 0, tot1 = 0, rec2 = 0, tot2 = 0, c1bad = 0;
|
||||
int wrong_cand = 0, tot_cand = 0, ns_empty = 0;
|
||||
for (int ti = 0; ti < 2; ti++) {
|
||||
int t = ts[ti];
|
||||
const bch_poly_t *p = bch_poly_for_data(512, t);
|
||||
CHECK(p != NULL, "chase: poly for 512B t=%d", t);
|
||||
if (!p)
|
||||
continue;
|
||||
size_t D = 512;
|
||||
size_t slen = bch_block_stored_len(D, p);
|
||||
size_t nbits = (size_t)8 * D + (size_t)p->r;
|
||||
uint8_t *data = malloc(D);
|
||||
uint8_t *enc = malloc(slen);
|
||||
uint8_t *dec = malloc(D);
|
||||
uint8_t *cands = malloc((size_t)BCH_CHASE_MAX_CANDS * D);
|
||||
rand_bytes(data, D);
|
||||
CHECK(bch_encode_block(data, D, p, enc) == 0,
|
||||
"chase encode t=%d", t);
|
||||
/* t+1 errors: Chase-1 must recover, standard must fail. */
|
||||
for (int tr = 0; tr < 10; tr++) {
|
||||
uint8_t *cor = malloc(slen);
|
||||
bch_chase_stats_t cs;
|
||||
size_t *susp = malloc(sizeof(size_t) *
|
||||
BCH_CHASE_MAX_SUSPECTS);
|
||||
int ns, nc, found = 0, q;
|
||||
memcpy(cor, enc, slen);
|
||||
flip_bits(cor, nbits, t + 1);
|
||||
CHECK(bch_decode_block(cor, slen, D, p, dec, NULL) != 0,
|
||||
"chase control: standard decode must fail t=%d k=%d",
|
||||
t, t + 1);
|
||||
ns = bch_suspect_positions(cor, slen, D, p, susp,
|
||||
BCH_CHASE_MAX_SUSPECTS);
|
||||
/* Suspects may be empty: when the failed decode's
|
||||
* locator has no in-range roots there is nothing
|
||||
* to suspect. Chase-1 does not need them (it scans
|
||||
* exhaustively) and Chase-2 falls back to its
|
||||
* positional prefix. Count it, do not fail on it. */
|
||||
if (ns == 0)
|
||||
ns_empty++;
|
||||
for (q = 0; q < ns; q++)
|
||||
CHECK(susp[q] < nbits,
|
||||
"chase: suspect %zu in range (nbits %zu)",
|
||||
susp[q], nbits);
|
||||
nc = bch_chase1_block(cor, slen, D, p, cands,
|
||||
BCH_CHASE_MAX_CANDS, susp, ns, &cs,
|
||||
-1);
|
||||
CHECK(nc >= 0 && nc <= BCH_CHASE_MAX_CANDS,
|
||||
"chase1: candidate count %d t=%d", nc, t);
|
||||
CHECK(cs.partial == 0, "chase1: no deadline, no partial");
|
||||
for (q = 0; q < nc; q++) {
|
||||
tot_cand++;
|
||||
if (memcmp(cands + (size_t)q * D, data, D) == 0)
|
||||
found = 1;
|
||||
else {
|
||||
/* A wrong candidate must still be a valid
|
||||
* codeword: re-encode it and require the
|
||||
* re-encoded form to decode cleanly. */
|
||||
uint8_t *re = malloc(slen);
|
||||
uint8_t *dd = malloc(D);
|
||||
if (bch_encode_block(cands + (size_t)q * D, D, p,
|
||||
re) == 0 &&
|
||||
bch_decode_block(re, slen, D, p, dd, NULL) == 0 &&
|
||||
memcmp(dd, cands + (size_t)q * D, D) == 0) {
|
||||
wrong_cand++;
|
||||
} else {
|
||||
CHECK(0, "chase1: candidate %d is not a valid "
|
||||
"codeword t=%d", q, t);
|
||||
}
|
||||
free(re);
|
||||
free(dd);
|
||||
}
|
||||
}
|
||||
tot1++;
|
||||
rec1 += found;
|
||||
if (!found)
|
||||
c1bad++;
|
||||
free(cor);
|
||||
free(susp);
|
||||
}
|
||||
/* t+2 errors: Chase-1 must NOT recover; Chase-2 may.
|
||||
* 256-byte blocks here: chase2's 128 first elements
|
||||
* cover a bigger fraction of a 256-byte block, so the
|
||||
* recovery rate is high enough to assert on (roughly
|
||||
* 1 - (1 - (t+2)/nbits)^128, about 46% at t=8). */
|
||||
for (int tr = 0; tr < 5; tr++) {
|
||||
const bch_poly_t *p2 = bch_poly_for_data(256, t);
|
||||
size_t D2 = 256;
|
||||
size_t slen2 = bch_block_stored_len(D2, p2);
|
||||
size_t nbits2 = (size_t)8 * D2 + (size_t)p2->r;
|
||||
uint8_t *data2 = malloc(D2);
|
||||
uint8_t *enc2 = malloc(slen2);
|
||||
uint8_t *cor = malloc(slen2);
|
||||
bch_chase_stats_t cs1, cs2;
|
||||
size_t *susp = malloc(sizeof(size_t) *
|
||||
BCH_CHASE_MAX_SUSPECTS);
|
||||
int ns, nc1, nc2, found2 = 0, q;
|
||||
CHECK(p2 != NULL, "chase2: poly for 256B t=%d", t);
|
||||
rand_bytes(data2, D2);
|
||||
CHECK(bch_encode_block(data2, D2, p2, enc2) == 0,
|
||||
"chase2 encode t=%d", t);
|
||||
memcpy(cor, enc2, slen2);
|
||||
flip_bits(cor, nbits2, t + 2);
|
||||
CHECK(bch_decode_block(cor, slen2, D2, p2, NULL, NULL) != 0,
|
||||
"chase2 control: standard decode must fail t=%d",
|
||||
t);
|
||||
ns = bch_suspect_positions(cor, slen2, D2, p2, susp,
|
||||
BCH_CHASE_MAX_SUSPECTS);
|
||||
if (ns == 0)
|
||||
ns_empty++;
|
||||
nc1 = bch_chase1_block(cor, slen2, D2, p2, cands,
|
||||
BCH_CHASE_MAX_CANDS, susp, ns, &cs1,
|
||||
-1);
|
||||
for (q = 0; q < nc1; q++)
|
||||
CHECK(memcmp(cands + (size_t)q * D2, data2, D2) != 0,
|
||||
"chase1: must NOT recover t+2 (t=%d trial %d)",
|
||||
t, tr);
|
||||
nc2 = bch_chase2_block(cor, slen2, D2, p2, cands,
|
||||
BCH_CHASE_MAX_CANDS, susp, ns, &cs2,
|
||||
-1);
|
||||
CHECK(nc2 >= 0 && nc2 <= BCH_CHASE_MAX_CANDS,
|
||||
"chase2: candidate count %d t=%d", nc2, t);
|
||||
CHECK(cs2.partial == 0, "chase2: no deadline, no partial");
|
||||
for (q = 0; q < nc2; q++) {
|
||||
tot_cand++;
|
||||
if (memcmp(cands + (size_t)q * D2, data2, D2) == 0)
|
||||
found2 = 1;
|
||||
else
|
||||
wrong_cand++;
|
||||
}
|
||||
tot2++;
|
||||
rec2 += found2;
|
||||
free(data2);
|
||||
free(enc2);
|
||||
free(cor);
|
||||
free(susp);
|
||||
}
|
||||
free(data);
|
||||
free(enc);
|
||||
free(dec);
|
||||
free(cands);
|
||||
}
|
||||
printf("phase 8 (deep repair Chase): t+1 recovered by Chase-1 "
|
||||
"%d/%d (missed %d), t+2 recovered by Chase-2 %d/%d, "
|
||||
"wrong-but-valid candidates %d/%d, empty suspect sets "
|
||||
"%d\n",
|
||||
rec1, tot1, c1bad, rec2, tot2, wrong_cand, tot_cand,
|
||||
ns_empty);
|
||||
CHECK(rec1 >= tot1 - 1,
|
||||
"chase1: t+1 recovery %d/%d (expected >= %d)", rec1, tot1,
|
||||
tot1 - 1);
|
||||
CHECK(rec2 >= 1, "chase2: t+2 recovery %d/%d (expected >= 1)",
|
||||
rec2, tot2);
|
||||
/* Deadline: a deadline already in the past stops the scan. */
|
||||
{
|
||||
const bch_poly_t *p = bch_poly_for_data(512, 8);
|
||||
size_t D = 512;
|
||||
size_t slen = bch_block_stored_len(D, p);
|
||||
uint8_t *data = malloc(D);
|
||||
uint8_t *enc = malloc(slen);
|
||||
uint8_t *cands = malloc((size_t)BCH_CHASE_MAX_CANDS * D);
|
||||
bch_chase_stats_t cs;
|
||||
int nc;
|
||||
rand_bytes(data, D);
|
||||
CHECK(bch_encode_block(data, D, p, enc) == 0,
|
||||
"chase deadline encode");
|
||||
flip_bits(enc, (size_t)8 * D + (size_t)p->r, 9);
|
||||
nc = bch_chase1_block(enc, slen, D, p, cands,
|
||||
BCH_CHASE_MAX_CANDS, NULL, 0, &cs,
|
||||
bch_now() - 1.0);
|
||||
CHECK(cs.partial == 1,
|
||||
"chase1: past deadline must set partial (got %d, nc %d)",
|
||||
cs.partial, nc);
|
||||
CHECK(bch_now() >= 0, "bch_now returns a time");
|
||||
free(data);
|
||||
free(enc);
|
||||
free(cands);
|
||||
}
|
||||
}
|
||||
printf("phase 8 done: %d checks, %d fails\n", checks, fails);
|
||||
|
||||
/* --- 7: unknown / edge lookups --- */
|
||||
CHECK(bch_poly_by_id(0x0000) == NULL, "id 0000 should be NULL");
|
||||
CHECK(bch_poly_by_id(0x0053) == NULL, "id 0053 should be NULL");
|
||||
|
||||
Executable
+88
@@ -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
@@ -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
|
||||
Executable
+104
@@ -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
@@ -0,0 +1,181 @@
|
||||
/* 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
@@ -0,0 +1,611 @@
|
||||
/* 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;
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/* 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 */
|
||||
@@ -0,0 +1,52 @@
|
||||
/* chase_cuda_stub.c - CPU-only fallback for the CUDA Chase-1 entry points.
|
||||
*
|
||||
* Defines the two symbols deep_repair.c references (chase_cuda_available,
|
||||
* chase_cuda_scan1) for builds without nvcc, so a CPU-only link always
|
||||
* resolves. The stub reports "no GPU": the caller in deep_repair.c then
|
||||
* takes the CPU Chase-1 path, exactly as it does when a CUDA build is
|
||||
* present but no device is found.
|
||||
*
|
||||
* This exists for the same reason as bch_cuda_stub.c: the weak-symbol
|
||||
* fallback it replaces does not work on macOS. deep_repair.c declares
|
||||
* these functions __attribute__((weak)), expecting them to resolve to
|
||||
* NULL when no CUDA object is linked. GNU ld does that; macOS ld64
|
||||
* does not -- a weak declaration is a weak definition, not a weak
|
||||
* import, so the link fails with undefined _chase_cuda_available /
|
||||
* _chase_cuda_scan1 symbols (run 7 on main, both arm64 and x86_64).
|
||||
* Defining the symbols outright removes all reliance on
|
||||
* linker-specific weak-symbol behaviour, on every platform.
|
||||
*
|
||||
* The stub is built only when nvcc is absent (see the Makefile:
|
||||
* CUDA_STUB_OBJ is empty whenever CHASE_CUDA_OBJ is set), so the
|
||||
* symbols are defined exactly once in every build.
|
||||
*/
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#include "bch.h"
|
||||
#include "chase_cuda.h"
|
||||
|
||||
int chase_cuda_available(void)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
(void)in;
|
||||
(void)in_len;
|
||||
(void)data_len;
|
||||
(void)p;
|
||||
(void)cands;
|
||||
(void)max_cands;
|
||||
(void)suspects;
|
||||
(void)nsuspects;
|
||||
(void)trials_out;
|
||||
(void)split_pass_out;
|
||||
(void)codewords_out;
|
||||
return -2;
|
||||
}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
/* crc16_test.c - unit test for crc16_of (CRC-16/CCITT-FALSE).
|
||||
*
|
||||
* Checks the standard test vectors (empty -> 0xFFFF,
|
||||
* "123456789" -> 0x29B1, "A" -> 0xB915), single-bit sensitivity
|
||||
* (flipping any one bit of a buffer changes the CRC), and a
|
||||
* cross-check against an independent bit-by-bit reference
|
||||
* implementation on random buffers.
|
||||
*
|
||||
* Usage: ./crc16_test [seed]
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdint.h>
|
||||
#include "lzply_lib.h"
|
||||
|
||||
static int fails = 0;
|
||||
static int checks = 0;
|
||||
#define CHECK(cond, ...) do { \
|
||||
checks++; \
|
||||
if (!(cond)) { fails++; printf("FAIL: " __VA_ARGS__); printf("\n"); } \
|
||||
} while (0)
|
||||
|
||||
static uint64_t rng_state = 0xabcdef123456789ULL;
|
||||
static uint64_t xr(void)
|
||||
{
|
||||
rng_state ^= rng_state << 13;
|
||||
rng_state ^= rng_state >> 7;
|
||||
rng_state ^= rng_state << 17;
|
||||
return rng_state;
|
||||
}
|
||||
|
||||
/* Independent reference: bit-by-bit CRC-16/CCITT-FALSE. */
|
||||
static uint16_t crc16_ref(const uint8_t *p, size_t n)
|
||||
{
|
||||
uint16_t c = 0xFFFFu;
|
||||
size_t i;
|
||||
int b;
|
||||
for (i = 0; i < n; i++) {
|
||||
c ^= (uint16_t)((uint16_t)p[i] << 8);
|
||||
for (b = 0; b < 8; b++)
|
||||
c = (c & 0x8000u) ? (uint16_t)((c << 1) ^ 0x1021u)
|
||||
: (uint16_t)(c << 1);
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
if (argc > 1)
|
||||
rng_state = strtoull(argv[1], NULL, 0) ^ 0x9e3779b97f4a7c15ULL;
|
||||
|
||||
/* Standard vectors. */
|
||||
CHECK(crc16_of(NULL, 0) == 0xFFFF, "empty -> 0xFFFF (got %04x)",
|
||||
(unsigned)crc16_of(NULL, 0));
|
||||
CHECK(crc16_of((const uint8_t *)"123456789", 9) == 0x29B1,
|
||||
"\"123456789\" -> 0x29B1 (got %04x)",
|
||||
(unsigned)crc16_of((const uint8_t *)"123456789", 9));
|
||||
CHECK(crc16_of((const uint8_t *)"A", 1) == 0xB915,
|
||||
"\"A\" -> 0xB915 (got %04x)",
|
||||
(unsigned)crc16_of((const uint8_t *)"A", 1));
|
||||
|
||||
/* Cross-check against the bit-by-bit reference on random
|
||||
* buffers of many lengths (including 0, 1, and odd sizes). */
|
||||
{
|
||||
static const size_t lens[] = { 0, 1, 2, 3, 7, 8, 15, 16, 31, 64,
|
||||
100, 257, 1000, 4096 };
|
||||
size_t li;
|
||||
for (li = 0; li < sizeof(lens) / sizeof(lens[0]); li++) {
|
||||
size_t n = lens[li];
|
||||
uint8_t *buf = malloc(n ? n : 1);
|
||||
size_t i;
|
||||
for (i = 0; i < n; i++)
|
||||
buf[i] = (uint8_t)(xr() & 0xff);
|
||||
CHECK(crc16_of(buf, n) == crc16_ref(buf, n),
|
||||
"ref mismatch len %zu: table %04x ref %04x",
|
||||
n, (unsigned)crc16_of(buf, n),
|
||||
(unsigned)crc16_ref(buf, n));
|
||||
free(buf);
|
||||
}
|
||||
}
|
||||
|
||||
/* Single-bit sensitivity: flipping any one bit of a buffer
|
||||
* must change the CRC (a CRC that ignores a bit is broken). */
|
||||
{
|
||||
uint8_t buf[64];
|
||||
size_t i;
|
||||
int b;
|
||||
for (i = 0; i < sizeof buf; i++)
|
||||
buf[i] = (uint8_t)(xr() & 0xff);
|
||||
for (i = 0; i < sizeof buf; i++) {
|
||||
for (b = 0; b < 8; b++) {
|
||||
uint16_t before = crc16_of(buf, sizeof buf);
|
||||
uint16_t after;
|
||||
buf[i] ^= (uint8_t)(1u << b);
|
||||
after = crc16_of(buf, sizeof buf);
|
||||
buf[i] ^= (uint8_t)(1u << b);
|
||||
CHECK(before != after,
|
||||
"bit flip at byte %zu bit %d did not change CRC",
|
||||
i, b);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Determinism: same input, same output, twice. */
|
||||
{
|
||||
uint8_t buf[128];
|
||||
size_t i;
|
||||
for (i = 0; i < sizeof buf; i++)
|
||||
buf[i] = (uint8_t)(xr() & 0xff);
|
||||
CHECK(crc16_of(buf, sizeof buf) == crc16_of(buf, sizeof buf),
|
||||
"determinism");
|
||||
}
|
||||
|
||||
printf("TOTAL: %d checks, %d fails\n", checks, fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
+711
@@ -0,0 +1,711 @@
|
||||
/* deep_repair.c - escalating repair past the BCH limit t.
|
||||
*
|
||||
* The ladder (see deep_repair.h and docs/deep-repair.md):
|
||||
* L0: standard decode to t (BCH pass 1, RS first for LZRS).
|
||||
* L1: pass-2 candidates + Chase-1 single-bit flips.
|
||||
* L2: Chase-2 two-bit flips.
|
||||
* L3: bounded list decoding across blocks (two failing blocks
|
||||
* varied at once, from the pooled per-block candidates).
|
||||
* Every candidate blob is CRC16-checked before decompress + SHA-256.
|
||||
* Nothing is ever returned unless it passes both oracles.
|
||||
*/
|
||||
#define _FILE_OFFSET_BITS 64
|
||||
#define _DEFAULT_SOURCE
|
||||
|
||||
#include "deep_repair.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "bch.h"
|
||||
#include "lzply_lib.h"
|
||||
#include "lzrs_lib.h"
|
||||
#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). */
|
||||
static uint8_t *blob_to_raw(const uint8_t *blob, size_t blob_len, int level,
|
||||
const uint8_t want_sha[32], size_t *out_len)
|
||||
{
|
||||
uint8_t *out = NULL;
|
||||
size_t outl = 0;
|
||||
uint8_t sha[32];
|
||||
if (level == 0) {
|
||||
out = xmalloc(blob_len ? blob_len : 1);
|
||||
memcpy(out, blob, blob_len);
|
||||
outl = blob_len;
|
||||
} else if (lz_decompress_mem(blob, blob_len, &out, &outl) != 0) {
|
||||
return NULL;
|
||||
}
|
||||
lzply_sha256(out, outl, sha);
|
||||
if (memcmp(sha, want_sha, 32) != 0) {
|
||||
free(out);
|
||||
return NULL;
|
||||
}
|
||||
*out_len = outl;
|
||||
return out;
|
||||
}
|
||||
|
||||
/* Count differing bits between two buffers of n bytes. */
|
||||
static long count_bit_diffs(const uint8_t *a, const uint8_t *b, size_t n)
|
||||
{
|
||||
static const uint8_t pop[256] = {
|
||||
0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,
|
||||
1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
|
||||
1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
|
||||
2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
|
||||
1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,
|
||||
2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
|
||||
2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,
|
||||
3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,4,5,5,6,5,6,6,7,5,6,6,7,6,7,7,8
|
||||
};
|
||||
long d = 0;
|
||||
size_t i;
|
||||
for (i = 0; i < n; i++)
|
||||
d += pop[a[i] ^ b[i]];
|
||||
return d;
|
||||
}
|
||||
|
||||
/* One candidate blob: CRC-check it (cheap oracle), then decompress
|
||||
* + SHA-256 (final oracle). Returns 1 on success with *raw_out /
|
||||
* *raw_len_out filled, 0 on failure (stats updated). */
|
||||
static int try_blob(const uint8_t *blob, size_t blob_len, int level,
|
||||
const uint8_t want_sha[32], uint16_t want_crc16,
|
||||
deep_stats_t *st, uint8_t **raw_out, size_t *raw_len_out)
|
||||
{
|
||||
uint16_t got = crc16_of(blob, blob_len);
|
||||
uint8_t *raw;
|
||||
size_t raw_len = 0;
|
||||
st->cands_tried++;
|
||||
if (got != want_crc16) {
|
||||
st->crc_rejects++;
|
||||
return 0;
|
||||
}
|
||||
raw = blob_to_raw(blob, blob_len, level, want_sha, &raw_len);
|
||||
if (!raw) {
|
||||
st->sha_rejects++;
|
||||
return 0;
|
||||
}
|
||||
*raw_out = raw;
|
||||
*raw_len_out = raw_len;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Per-block candidate pool (decoded block bytes). */
|
||||
typedef struct {
|
||||
uint8_t *cands; /* n * dlen bytes */
|
||||
int n;
|
||||
size_t dlen;
|
||||
} block_pool_t;
|
||||
|
||||
/* Add a candidate block to the pool (deduped, capped). Returns 1 if
|
||||
* added, 0 if already present / pool full / pool-byte cap hit.
|
||||
* *pool_bytes tracks retained memory against DEEP_MAX_POOL_BYTES. */
|
||||
static int pool_add(block_pool_t *pool, size_t dlen, const uint8_t *cand,
|
||||
size_t *pool_bytes)
|
||||
{
|
||||
int i;
|
||||
if (pool->n >= 2 * DEEP_MAX_BLOCK_CANDS)
|
||||
return 0;
|
||||
if (*pool_bytes + dlen > DEEP_MAX_POOL_BYTES)
|
||||
return 0;
|
||||
for (i = 0; i < pool->n; i++)
|
||||
if (memcmp(pool->cands + (size_t)i * dlen, cand, dlen) == 0)
|
||||
return 0;
|
||||
{
|
||||
uint8_t *nc = realloc(pool->cands,
|
||||
(size_t)(pool->n + 1) * (dlen ? dlen : 1));
|
||||
if (!nc)
|
||||
return 0;
|
||||
pool->cands = nc;
|
||||
memcpy(pool->cands + (size_t)pool->n * dlen, cand, dlen);
|
||||
pool->n++;
|
||||
pool->dlen = dlen;
|
||||
*pool_bytes += dlen;
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
static void pool_free(block_pool_t *pool, size_t *pool_bytes)
|
||||
{
|
||||
if (pool->cands) {
|
||||
*pool_bytes -= (size_t)pool->n * pool->dlen;
|
||||
free(pool->cands);
|
||||
pool->cands = NULL;
|
||||
}
|
||||
pool->n = 0;
|
||||
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,
|
||||
uint16_t want_crc16, int max_level, double budget_sec,
|
||||
uint8_t **raw, size_t *raw_len, deep_stats_t *stats)
|
||||
{
|
||||
deep_stats_t dummy;
|
||||
double start, deadline;
|
||||
const uint8_t *bch_stored = NULL; /* RS-decoded BCH bytes (owned below) */
|
||||
uint8_t *bch_owned = NULL;
|
||||
size_t bch_len = 0;
|
||||
int corr_rs = 0;
|
||||
int rc = -1;
|
||||
if (!stats)
|
||||
stats = &dummy;
|
||||
memset(stats, 0, sizeof *stats);
|
||||
stats->level_landed = -1;
|
||||
stats->bch_corrected = -1;
|
||||
strcpy(stats->fail_stage, "sha");
|
||||
if (!stored || !want_sha || !raw || !raw_len)
|
||||
return -1;
|
||||
*raw = NULL;
|
||||
*raw_len = 0;
|
||||
if (max_level < 0)
|
||||
max_level = 0;
|
||||
if (max_level > DEEP_MAX_LEVEL)
|
||||
max_level = DEEP_MAX_LEVEL;
|
||||
if (budget_sec <= 0)
|
||||
budget_sec = DEEP_DEFAULT_BUDGET_SEC;
|
||||
if (rs_level < 0 || rs_level > 4)
|
||||
return -1;
|
||||
start = bch_now();
|
||||
deadline = start + budget_sec;
|
||||
|
||||
/* --- RS layer (LZRS only): strip it first. --- */
|
||||
if (rs_level > 0) {
|
||||
int parity = rs_parity_for_level(rs_level);
|
||||
const bch_poly_t *poly = NULL;
|
||||
if (parity < 0)
|
||||
return -1;
|
||||
if (is_bch) {
|
||||
poly = bch_poly_by_id(poly_id);
|
||||
if (!poly)
|
||||
return -1;
|
||||
bch_len = bch_encoded_len(blob_size, poly);
|
||||
} else {
|
||||
bch_len = blob_size;
|
||||
}
|
||||
if (stored_len != rs_encoded_len(bch_len, parity)) {
|
||||
strcpy(stats->fail_stage, "len");
|
||||
return -1;
|
||||
}
|
||||
bch_owned = xmalloc(bch_len ? bch_len : 1);
|
||||
if (rs_decode(stored, stored_len, bch_len, parity,
|
||||
bch_owned, &corr_rs) != 0) {
|
||||
free(bch_owned);
|
||||
strcpy(stats->fail_stage, "rs");
|
||||
stats->t_total = bch_now() - start;
|
||||
return -1;
|
||||
}
|
||||
stats->rs_corrected = corr_rs;
|
||||
bch_stored = bch_owned;
|
||||
} else {
|
||||
if (is_bch) {
|
||||
const bch_poly_t *poly = bch_poly_by_id(poly_id);
|
||||
if (!poly)
|
||||
return -1;
|
||||
bch_len = bch_encoded_len(blob_size, poly);
|
||||
if (stored_len != bch_len) {
|
||||
strcpy(stats->fail_stage, "len");
|
||||
return -1;
|
||||
}
|
||||
} else {
|
||||
bch_len = blob_size;
|
||||
if (stored_len != blob_size) {
|
||||
strcpy(stats->fail_stage, "len");
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
bch_stored = stored;
|
||||
}
|
||||
|
||||
/* --- No BCH layer: CRC + SHA only, nothing to repair. --- */
|
||||
if (!is_bch) {
|
||||
double t0 = bch_now();
|
||||
uint16_t got = crc16_of(bch_stored, blob_size);
|
||||
if (got != want_crc16) {
|
||||
stats->cands_tried++;
|
||||
stats->crc_rejects++;
|
||||
strcpy(stats->fail_stage, "crc");
|
||||
stats->t_level[0] = bch_now() - t0;
|
||||
stats->t_total = bch_now() - start;
|
||||
free(bch_owned);
|
||||
return -1;
|
||||
}
|
||||
{
|
||||
uint8_t *out = NULL;
|
||||
size_t out_len = 0;
|
||||
stats->cands_tried++;
|
||||
out = blob_to_raw(bch_stored, blob_size, level, want_sha,
|
||||
&out_len);
|
||||
stats->t_level[0] = bch_now() - t0;
|
||||
if (!out) {
|
||||
stats->sha_rejects++;
|
||||
strcpy(stats->fail_stage, "sha");
|
||||
stats->t_total = bch_now() - start;
|
||||
free(bch_owned);
|
||||
return -1;
|
||||
}
|
||||
*raw = out;
|
||||
*raw_len = out_len;
|
||||
stats->level_landed = 0;
|
||||
stats->bch_corrected = 0;
|
||||
strcpy(stats->fail_stage, "ok");
|
||||
stats->t_total = bch_now() - start;
|
||||
free(bch_owned);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* --- BCH layer: split into blocks, pass 1 each. --- */
|
||||
{
|
||||
const bch_poly_t *poly = bch_poly_by_id(poly_id);
|
||||
size_t maxd = bch_max_data(poly);
|
||||
size_t nblocks = blob_size == 0 ? 1
|
||||
: (blob_size + maxd - 1) / maxd;
|
||||
size_t *boff = malloc(nblocks * sizeof(size_t));
|
||||
size_t *bdlen = malloc(nblocks * sizeof(size_t));
|
||||
size_t *bslen = malloc(nblocks * sizeof(size_t));
|
||||
uint8_t *ok = malloc(nblocks);
|
||||
uint8_t *base = xmalloc(blob_size ? blob_size : 1);
|
||||
uint8_t *won = xmalloc(blob_size ? blob_size : 1);
|
||||
block_pool_t *pools = calloc(nblocks, sizeof(block_pool_t));
|
||||
size_t pool_bytes = 0;
|
||||
size_t *vary = malloc(nblocks * sizeof(size_t));
|
||||
long nfail = 0, nfail_idx = 0;
|
||||
int retain_pools = 0;
|
||||
double t0;
|
||||
int corr_total = 0;
|
||||
size_t i, off = 0, roff = 0;
|
||||
if (!boff || !bdlen || !bslen || !ok || !pools || !vary) {
|
||||
free(boff); free(bdlen); free(bslen); free(ok);
|
||||
free(base); free(won); free(pools); free(vary);
|
||||
free(bch_owned);
|
||||
return -1;
|
||||
}
|
||||
stats->blocks_total = (long)nblocks;
|
||||
for (i = 0; i < nblocks; i++) {
|
||||
size_t chunk = blob_size - off;
|
||||
size_t slen;
|
||||
int c1 = 0;
|
||||
if (chunk > maxd)
|
||||
chunk = maxd;
|
||||
slen = bch_block_stored_len(chunk, poly);
|
||||
boff[i] = off;
|
||||
bdlen[i] = chunk;
|
||||
bslen[i] = slen;
|
||||
ok[i] = (roff + slen <= bch_len &&
|
||||
bch_decode_block(bch_stored + roff, slen, chunk, poly,
|
||||
base + off, &c1) == 0);
|
||||
if (!ok[i])
|
||||
nfail++;
|
||||
corr_total += c1;
|
||||
roff += slen;
|
||||
off += chunk;
|
||||
}
|
||||
stats->blocks_failed = nfail;
|
||||
/* Vary set: failing blocks; when none failed (miscorrection),
|
||||
* every block in turn. Pools are retained only when some
|
||||
* block failed (the multi-block L3 case). */
|
||||
if (nfail > 0) {
|
||||
retain_pools = 1;
|
||||
for (i = 0; i < nblocks; i++)
|
||||
if (!ok[i])
|
||||
vary[nfail_idx++] = i;
|
||||
} else {
|
||||
for (i = 0; i < nblocks; i++)
|
||||
vary[nfail_idx++] = i;
|
||||
}
|
||||
|
||||
/* --- L0: the pass-1 blob. --- */
|
||||
t0 = bch_now();
|
||||
if (nfail == 0) {
|
||||
uint8_t *out = NULL;
|
||||
size_t out_len = 0;
|
||||
if (try_blob(base, blob_size, level, want_sha, want_crc16,
|
||||
stats, &out, &out_len)) {
|
||||
memcpy(won, base, blob_size);
|
||||
*raw = out;
|
||||
*raw_len = out_len;
|
||||
stats->level_landed = 0;
|
||||
stats->bch_corrected = corr_total;
|
||||
strcpy(stats->fail_stage, "ok");
|
||||
stats->t_level[0] = bch_now() - t0;
|
||||
stats->t_total = bch_now() - start;
|
||||
rc = 0;
|
||||
goto bch_done;
|
||||
}
|
||||
}
|
||||
stats->t_level[0] = bch_now() - t0;
|
||||
if (max_level < 1)
|
||||
goto bch_fail;
|
||||
|
||||
/* --- L1: pass-2 candidates + Chase-1, one block at a time. --- */
|
||||
t0 = bch_now();
|
||||
{
|
||||
uint8_t *cand_blob = xmalloc(blob_size ? blob_size : 1);
|
||||
size_t vi;
|
||||
for (vi = 0; vi < (size_t)nfail_idx; vi++) {
|
||||
size_t bi = vary[vi];
|
||||
int added0 = pools[bi].n;
|
||||
int added1;
|
||||
int k;
|
||||
/* Pass-2 candidates first (cheap). */
|
||||
{
|
||||
uint8_t *bc = malloc((size_t)BCH_PASS2_MAX_CANDS *
|
||||
(bdlen[bi] ? bdlen[bi] : 1));
|
||||
int nbc = 0, q;
|
||||
size_t s_off = 0;
|
||||
size_t j;
|
||||
for (j = 0; j < bi; j++)
|
||||
s_off += bslen[j];
|
||||
if (bc) {
|
||||
nbc = bch_decode_block_candidates(
|
||||
bch_stored + s_off, bslen[bi], bdlen[bi], poly,
|
||||
bc, BCH_PASS2_MAX_CANDS);
|
||||
for (q = 0; q < nbc && pools[bi].n < DEEP_MAX_BLOCK_CANDS; q++)
|
||||
pool_add(&pools[bi], bdlen[bi],
|
||||
bc + (size_t)q * bdlen[bi], &pool_bytes);
|
||||
}
|
||||
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. */
|
||||
{
|
||||
size_t *susp = malloc(sizeof(size_t) *
|
||||
BCH_CHASE_MAX_SUSPECTS);
|
||||
uint8_t *cc = malloc((size_t)BCH_CHASE_MAX_CANDS *
|
||||
(bdlen[bi] ? bdlen[bi] : 1));
|
||||
bch_chase_stats_t cs;
|
||||
int ns = 0, ncc = 0, q;
|
||||
size_t s_off = 0;
|
||||
size_t j;
|
||||
for (j = 0; j < bi; j++)
|
||||
s_off += bslen[j];
|
||||
if (susp && cc) {
|
||||
ns = bch_suspect_positions(bch_stored + s_off,
|
||||
bslen[bi], bdlen[bi],
|
||||
poly, susp,
|
||||
BCH_CHASE_MAX_SUSPECTS);
|
||||
{
|
||||
int used_cuda = 0;
|
||||
ncc = 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;
|
||||
}
|
||||
stats->trials[1] += cs.trials;
|
||||
stats->split_pass[1] += cs.split_pass;
|
||||
stats->codewords[1] += cs.codewords;
|
||||
if (cs.partial)
|
||||
stats->partial = 1;
|
||||
/* Try the Chase-1 candidates DIRECTLY, in
|
||||
* scan order, before pooling: the pool cap
|
||||
* would truncate the list, and the true
|
||||
* candidate can arrive late in scan order
|
||||
* (wrong-but-valid codewords accumulate at
|
||||
* ~1 per 32K trials, so on a 4M-bit block
|
||||
* the genuine candidate can be the 20th+
|
||||
* one returned). Pooling first and trying
|
||||
* only the pooled prefix lost it. Pool
|
||||
* afterwards for the L3 list. */
|
||||
for (q = 0; q < ncc; q++) {
|
||||
uint8_t *out = NULL;
|
||||
size_t out_len = 0;
|
||||
memcpy(cand_blob, base, blob_size);
|
||||
memcpy(cand_blob + boff[bi],
|
||||
cc + (size_t)q * bdlen[bi],
|
||||
bdlen[bi]);
|
||||
if (try_blob(cand_blob, blob_size, level,
|
||||
want_sha, want_crc16, stats,
|
||||
&out, &out_len)) {
|
||||
memcpy(won, cand_blob, blob_size);
|
||||
*raw = out;
|
||||
*raw_len = out_len;
|
||||
stats->level_landed = 1;
|
||||
strcpy(stats->fail_stage, "ok");
|
||||
stats->t_level[1] = bch_now() - t0;
|
||||
stats->t_total = bch_now() - start;
|
||||
rc = 0;
|
||||
free(susp);
|
||||
free(cc);
|
||||
free(cand_blob);
|
||||
goto bch_done;
|
||||
}
|
||||
pool_add(&pools[bi], bdlen[bi],
|
||||
cc + (size_t)q * bdlen[bi], &pool_bytes);
|
||||
}
|
||||
}
|
||||
free(susp);
|
||||
free(cc);
|
||||
}
|
||||
/* Try the pass-2 candidates pooled above (added0 to
|
||||
* the pool size after pass-2; the Chase-1 candidates
|
||||
* were already tried directly). */
|
||||
for (k = added0; k < added1; k++) {
|
||||
uint8_t *out = NULL;
|
||||
size_t out_len = 0;
|
||||
memcpy(cand_blob, base, blob_size);
|
||||
memcpy(cand_blob + boff[bi],
|
||||
pools[bi].cands + (size_t)k * bdlen[bi],
|
||||
bdlen[bi]);
|
||||
if (try_blob(cand_blob, blob_size, level, want_sha,
|
||||
want_crc16, stats, &out, &out_len)) {
|
||||
memcpy(won, cand_blob, blob_size);
|
||||
*raw = out;
|
||||
*raw_len = out_len;
|
||||
stats->level_landed = 1;
|
||||
strcpy(stats->fail_stage, "ok");
|
||||
stats->t_level[1] = bch_now() - t0;
|
||||
stats->t_total = bch_now() - start;
|
||||
rc = 0;
|
||||
free(cand_blob);
|
||||
goto bch_done;
|
||||
}
|
||||
}
|
||||
if (!retain_pools)
|
||||
pool_free(&pools[bi], &pool_bytes);
|
||||
if (bch_now() > deadline) {
|
||||
stats->partial = 1;
|
||||
free(cand_blob);
|
||||
stats->t_level[1] = bch_now() - t0;
|
||||
goto bch_fail;
|
||||
}
|
||||
}
|
||||
free(cand_blob);
|
||||
}
|
||||
stats->t_level[1] = bch_now() - t0;
|
||||
if (max_level < 2)
|
||||
goto bch_fail;
|
||||
|
||||
/* --- L2: Chase-2 pairs, one block at a time. --- */
|
||||
t0 = bch_now();
|
||||
{
|
||||
uint8_t *cand_blob = xmalloc(blob_size ? blob_size : 1);
|
||||
size_t vi;
|
||||
for (vi = 0; vi < (size_t)nfail_idx; vi++) {
|
||||
size_t bi = vary[vi];
|
||||
{
|
||||
size_t *susp = malloc(sizeof(size_t) *
|
||||
BCH_CHASE_MAX_SUSPECTS);
|
||||
uint8_t *cc = malloc((size_t)BCH_CHASE_MAX_CANDS *
|
||||
(bdlen[bi] ? bdlen[bi] : 1));
|
||||
bch_chase_stats_t cs;
|
||||
int ns = 0, ncc = 0, q;
|
||||
size_t s_off = 0;
|
||||
size_t j;
|
||||
for (j = 0; j < bi; j++)
|
||||
s_off += bslen[j];
|
||||
if (susp && cc) {
|
||||
ns = bch_suspect_positions(bch_stored + s_off,
|
||||
bslen[bi], bdlen[bi],
|
||||
poly, susp,
|
||||
BCH_CHASE_MAX_SUSPECTS);
|
||||
ncc = bch_chase2_block(bch_stored + s_off,
|
||||
bslen[bi], bdlen[bi], poly,
|
||||
cc, BCH_CHASE_MAX_CANDS,
|
||||
susp, ns, &cs, deadline);
|
||||
stats->trials[2] += cs.trials;
|
||||
stats->split_pass[2] += cs.split_pass;
|
||||
stats->codewords[2] += cs.codewords;
|
||||
if (cs.partial)
|
||||
stats->partial = 1;
|
||||
/* Try the Chase-2 candidates directly (the
|
||||
* pool may already be full from L1, so
|
||||
* pooling first would starve them); pool
|
||||
* each afterwards for the L3 list. */
|
||||
for (q = 0; q < ncc; q++) {
|
||||
uint8_t *out = NULL;
|
||||
size_t out_len = 0;
|
||||
memcpy(cand_blob, base, blob_size);
|
||||
memcpy(cand_blob + boff[bi],
|
||||
cc + (size_t)q * bdlen[bi],
|
||||
bdlen[bi]);
|
||||
if (try_blob(cand_blob, blob_size, level,
|
||||
want_sha, want_crc16, stats,
|
||||
&out, &out_len)) {
|
||||
memcpy(won, cand_blob, blob_size);
|
||||
*raw = out;
|
||||
*raw_len = out_len;
|
||||
stats->level_landed = 2;
|
||||
strcpy(stats->fail_stage, "ok");
|
||||
stats->t_level[2] = bch_now() - t0;
|
||||
stats->t_total = bch_now() - start;
|
||||
rc = 0;
|
||||
free(susp);
|
||||
free(cc);
|
||||
free(cand_blob);
|
||||
goto bch_done;
|
||||
}
|
||||
pool_add(&pools[bi], bdlen[bi],
|
||||
cc + (size_t)q * bdlen[bi], &pool_bytes);
|
||||
}
|
||||
}
|
||||
free(susp);
|
||||
free(cc);
|
||||
}
|
||||
if (!retain_pools)
|
||||
pool_free(&pools[bi], &pool_bytes);
|
||||
if (bch_now() > deadline) {
|
||||
stats->partial = 1;
|
||||
free(cand_blob);
|
||||
stats->t_level[2] = bch_now() - t0;
|
||||
goto bch_fail;
|
||||
}
|
||||
}
|
||||
free(cand_blob);
|
||||
}
|
||||
stats->t_level[2] = bch_now() - t0;
|
||||
if (max_level < 3)
|
||||
goto bch_fail;
|
||||
|
||||
/* --- L3: two failing blocks varied at once (list). --- */
|
||||
t0 = bch_now();
|
||||
if (nfail >= 2 && retain_pools) {
|
||||
uint8_t *cand_blob = xmalloc(blob_size ? blob_size : 1);
|
||||
long tried3 = 0;
|
||||
size_t ai, bj;
|
||||
for (ai = 0; ai < (size_t)nfail_idx && tried3 < DEEP_MAX_BLOB_CANDS; ai++) {
|
||||
size_t bi = vary[ai];
|
||||
for (bj = ai + 1; bj < (size_t)nfail_idx && tried3 < DEEP_MAX_BLOB_CANDS; bj++) {
|
||||
size_t bk = vary[bj];
|
||||
int ci, cj;
|
||||
if (pools[bi].n == 0 || pools[bk].n == 0)
|
||||
continue;
|
||||
for (ci = 0; ci < pools[bi].n && tried3 < DEEP_MAX_BLOB_CANDS; ci++) {
|
||||
for (cj = 0; cj < pools[bk].n && tried3 < DEEP_MAX_BLOB_CANDS; cj++) {
|
||||
uint8_t *out = NULL;
|
||||
size_t out_len = 0;
|
||||
memcpy(cand_blob, base, blob_size);
|
||||
memcpy(cand_blob + boff[bi],
|
||||
pools[bi].cands + (size_t)ci * bdlen[bi],
|
||||
bdlen[bi]);
|
||||
memcpy(cand_blob + boff[bk],
|
||||
pools[bk].cands + (size_t)cj * bdlen[bk],
|
||||
bdlen[bk]);
|
||||
tried3++;
|
||||
if (try_blob(cand_blob, blob_size, level,
|
||||
want_sha, want_crc16, stats,
|
||||
&out, &out_len)) {
|
||||
memcpy(won, cand_blob, blob_size);
|
||||
*raw = out;
|
||||
*raw_len = out_len;
|
||||
stats->level_landed = 3;
|
||||
strcpy(stats->fail_stage, "ok");
|
||||
stats->t_level[3] = bch_now() - t0;
|
||||
stats->t_total = bch_now() - start;
|
||||
rc = 0;
|
||||
free(cand_blob);
|
||||
goto bch_done;
|
||||
}
|
||||
if ((tried3 & 15) == 0 && bch_now() > deadline) {
|
||||
stats->partial = 1;
|
||||
free(cand_blob);
|
||||
stats->t_level[3] = bch_now() - t0;
|
||||
goto bch_fail;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
free(cand_blob);
|
||||
}
|
||||
stats->t_level[3] = bch_now() - t0;
|
||||
|
||||
bch_fail:
|
||||
if (stats->partial && bch_now() > deadline)
|
||||
strcpy(stats->fail_stage, "budget");
|
||||
else if (stats->cands_tried == 0)
|
||||
strcpy(stats->fail_stage, "nocand");
|
||||
else if (stats->crc_rejects == stats->cands_tried)
|
||||
strcpy(stats->fail_stage, "crc");
|
||||
else
|
||||
strcpy(stats->fail_stage, "sha");
|
||||
stats->t_total = bch_now() - start;
|
||||
rc = -1;
|
||||
goto bch_cleanup;
|
||||
|
||||
bch_done:
|
||||
/* Bits corrected at the landing level: re-encode the WINNING
|
||||
* blob (`won`, the candidate that verified) and count bit
|
||||
* differences against the received BCH bytes -- exact for
|
||||
* L1+ (the re-encoded true codeword differs from the
|
||||
* received word exactly at the error positions). L0 uses
|
||||
* the pass-1 corrected count. */
|
||||
if (stats->level_landed > 0) {
|
||||
size_t elen = bch_encoded_len(blob_size, poly);
|
||||
uint8_t *enc = malloc(elen ? elen : 1);
|
||||
if (enc && bch_encode(won, blob_size, poly, enc) == elen)
|
||||
stats->bch_corrected = (int)count_bit_diffs(
|
||||
enc, bch_stored, elen < bch_len ? elen : bch_len);
|
||||
free(enc);
|
||||
}
|
||||
/* level 0 already set bch_corrected = corr_total. */
|
||||
|
||||
bch_cleanup:
|
||||
for (i = 0; i < nblocks; i++)
|
||||
pool_free(&pools[i], &pool_bytes);
|
||||
free(boff);
|
||||
free(bdlen);
|
||||
free(bslen);
|
||||
free(ok);
|
||||
free(base);
|
||||
free(won);
|
||||
free(pools);
|
||||
free(vary);
|
||||
free(bch_owned);
|
||||
return rc;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
/* deep_repair.h - escalating repair past the BCH limit t.
|
||||
*
|
||||
* The ladder, per entry (see docs/deep-repair.md for the full
|
||||
* design, bounds, and measured numbers):
|
||||
* L0: standard decode to t (BCH pass 1, plus RS first for LZRS).
|
||||
* L1: pass-2 candidates + Chase-1 single-bit flips (suspects
|
||||
* first, then an exhaustive scan of the failing block).
|
||||
* L2: Chase-2 two-bit flips (pairs within the suspect set, then
|
||||
* (suspect, any-position) pairs).
|
||||
* L3: bounded list decoding across blocks: candidate blobs formed
|
||||
* by varying TWO failing blocks at once, from the pooled
|
||||
* per-block candidates of L1+L2.
|
||||
* Every candidate blob is CRC16-checked before the expensive
|
||||
* decompress + SHA-256 step; the CRC16 is the fast oracle and the
|
||||
* SHA-256 is the final oracle. Nothing is ever returned unless it
|
||||
* passes both. Expected residual false-accept is ~2^-16 per
|
||||
* candidate at the CRC stage (the SHA-256 stage then gates
|
||||
* acceptance).
|
||||
*
|
||||
* Bounds (enforced, not aspirational): per-block candidate pools
|
||||
* are capped (8 Chase-1 + 8 Chase-2 candidates per block), L3 tries
|
||||
* at most 256 candidate blobs, retained pool memory is capped at
|
||||
* 128 MiB, and the whole entry is capped by a wall-clock budget
|
||||
* (default 120 s). stats.partial says when a level stopped early
|
||||
* on its budget, and stats.trials says how far the scan got.
|
||||
* Per-level timing is reported in stats.t_level -- that is the
|
||||
* "time of arrival": how long each level took, and which level the
|
||||
* repair landed at.
|
||||
*/
|
||||
#ifndef LZPLY_DEEP_REPAIR_H
|
||||
#define LZPLY_DEEP_REPAIR_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
/* Highest repair level. */
|
||||
#define DEEP_MAX_LEVEL 3
|
||||
/* Default wall-clock budget per entry, seconds. */
|
||||
#define DEEP_DEFAULT_BUDGET_SEC 120.0
|
||||
/* Max candidate blobs combined at L3. */
|
||||
#define DEEP_MAX_BLOB_CANDS 256
|
||||
/* Max per-block candidates pooled per level source (L1, L2). */
|
||||
/* Maximum candidates retained per block in the L3 pool. The pool
|
||||
* holds up to 2x this many (pass-2 plus Chase candidates); the
|
||||
* Chase levels try their candidates directly, so this cap only
|
||||
* bounds what L3 can combine. 32 keeps a genuine candidate that
|
||||
* arrives late in scan order (see deep_repair.c L1) while the
|
||||
* 128 MiB pool byte cap bounds memory. */
|
||||
#define DEEP_MAX_BLOCK_CANDS 32
|
||||
/* Max retained pool memory across blocks, bytes. */
|
||||
#define DEEP_MAX_POOL_BYTES (128u * 1024u * 1024u)
|
||||
|
||||
typedef struct {
|
||||
int level_landed; /* -1 failed, else 0..3 */
|
||||
int rs_corrected; /* RS symbols corrected (LZRS only) */
|
||||
int bch_corrected; /* BCH bits corrected at the landing level
|
||||
(-1 when not computed) */
|
||||
long cands_tried; /* candidate blobs CRC-checked */
|
||||
long crc_rejects; /* candidates failing CRC16 */
|
||||
long sha_rejects; /* candidates passing CRC but failing
|
||||
decompression / SHA-256 */
|
||||
long trials[4]; /* Chase BM trials per level */
|
||||
long split_pass[4]; /* trials passing the splitting filter */
|
||||
long codewords[4]; /* trials yielding a valid codeword */
|
||||
double t_level[4]; /* seconds spent per level */
|
||||
double t_total; /* seconds for the whole entry */
|
||||
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;
|
||||
|
||||
/* Attempt the escalating repair of one archive entry.
|
||||
* `stored` / `stored_len` are the entry's stored bytes (RS-encoded
|
||||
* when rs_level > 0), `level` the lzip level, `is_bch` / `poly_id`
|
||||
* / `rs_level` from the entry header, `want_sha` the entry's
|
||||
* SHA-256, `blob_size` the pre-ECC blob length, `want_crc16` the
|
||||
* entry header's CRC16. `max_level` caps the ladder (0..3);
|
||||
* `budget_sec` is the wall-clock budget for this entry (<= 0
|
||||
* means the default). On success returns 0 with *raw / *raw_len
|
||||
* the recovered bytes and stats.level_landed set; on failure
|
||||
* returns -1 with stats.fail_stage set. Stats are zeroed on entry
|
||||
* (NULL is allowed). */
|
||||
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,
|
||||
uint16_t want_crc16, int max_level, double budget_sec,
|
||||
uint8_t **raw, size_t *raw_len, deep_stats_t *stats);
|
||||
|
||||
#endif /* LZPLY_DEEP_REPAIR_H */
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -0,0 +1,264 @@
|
||||
# Deep repair — past the BCH limit t
|
||||
|
||||
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.
|
||||
|
||||
## The levels
|
||||
|
||||
- **L0 — standard decode to t.** The normal BCH (and RS, for LZRS)
|
||||
decode. If it succeeds, the entry is recovered at L0.
|
||||
- **L1 — Chase-1.** Single-bit trial flips: the suspect positions
|
||||
first, then an exhaustive scan of every codeword bit position.
|
||||
For each trial flip the syndrome is updated by XOR-ing the
|
||||
flipped bit's syndrome column, Berlekamp-Massey runs on the
|
||||
trial syndrome, and a candidate is kept only if the locator
|
||||
splits completely over GF(2^m) (a gcd test against x^(2^m)−x),
|
||||
the Chien search finds all its roots at in-range positions, and
|
||||
the corrected word has zero remainder. Recovering t+1 is a
|
||||
theorem, not luck: flipping any one true error leaves t errors,
|
||||
which BM corrects. Chase-1 can never recover t+2 (one flip plus
|
||||
at most t Chien corrections cannot span t+2 errors — also a
|
||||
theorem).
|
||||
- **L2 — Chase-2.** Two-bit trial flips: pairs within the suspect
|
||||
set, then pairs (first element, any position) where the first
|
||||
element ranges over a bounded list — the suspects, then ascending
|
||||
bit positions, at most 128 entries in total
|
||||
(`BCH_CHASE2_FIRST_MAX`). At most 128·nbits trials, plus a
|
||||
wall-clock deadline. The recovery rate scales with the list
|
||||
size: roughly 1 − (1 − (t+2)/nbits)^F for F first elements on a
|
||||
weight-(t+2) pattern.
|
||||
- **L3 — cross-block list decoding.** Two failing blocks varied at
|
||||
once from retained per-block candidate pools (at most 256 blob
|
||||
tries, `DEEP_MAX_BLOB_CANDS`). Lands when each of two blocks
|
||||
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
|
||||
"least-reliable bits" come from the decoder itself: the Chien
|
||||
roots of the failed decode, the residual-BM difference set, and
|
||||
their neighbours. For Chase-1 the suspects only order the scan
|
||||
(the exhaustive scan covers everything anyway). For Chase-2 the
|
||||
suspects head the first-element list — but they provably do NOT
|
||||
overlap the true errors for random patterns: the failed decode's
|
||||
root set and the true error set have the same syndrome, so they
|
||||
differ by a codeword of weight ≥ 2t+1, which forces zero overlap
|
||||
when the failed decode returns a full root set. A suspect is
|
||||
therefore no more likely than any other position to be a true
|
||||
error, and Chase-2's rate comes from the size of the
|
||||
first-element list (the positional prefix does the work), not
|
||||
from the suspects. The list is what buys the rate. (Measured:
|
||||
in `bch_test` phase 8 the suspect set was empty in 15 of 30
|
||||
trials — when the failed decode's locator has no in-range roots
|
||||
there is nothing to suspect — and Chase-2 still runs, on the
|
||||
positional prefix alone.)
|
||||
|
||||
## Bounds (all enforced)
|
||||
|
||||
| bound | value | where |
|
||||
|---|---|---|
|
||||
| chase1 trials | ≤ nbits (one per codeword bit) | `bch_chase1_block` |
|
||||
| chase2 trials | ≤ 128·nbits + 496 | `bch_chase2_block` |
|
||||
| candidates per chase call | ≤ 64 distinct blocks | `BCH_CHASE_MAX_CANDS` |
|
||||
| candidates retained per block (L3 pool) | ≤ 64 (2× `DEEP_MAX_BLOCK_CANDS`) | `deep_repair.h` |
|
||||
| L3 blob tries | ≤ 256 | `DEEP_MAX_BLOB_CANDS` |
|
||||
| retained pool memory | ≤ 128 MiB | `DEEP_MAX_POOL_BYTES` |
|
||||
| time budget | default 120 s per entry (`--time-budget`) | CLI |
|
||||
| max level | 0..3 (`-l`) | CLI |
|
||||
|
||||
A deadline stops a scan early; the stats report `partial=1` and
|
||||
how many trials ran, so a budget-limited run is honest about its
|
||||
coverage. The tool exits 0 when every entry recovered, 3 when
|
||||
any failed, 1 on usage errors, 2 on I/O errors.
|
||||
|
||||
## The oracle and the false-accept rate
|
||||
|
||||
Every candidate blob is CRC16-checked before decompression; only
|
||||
CRC-passing candidates go to decompress + SHA-256. Expected
|
||||
residual false-accept is ~2^-16 per candidate at the CRC stage
|
||||
(the SHA-256 stage then gates acceptance). Measured across the
|
||||
corruption matrix (see below): 1,162 candidates CRC-checked,
|
||||
1,024 rejected by CRC, 0 false accepts. The strongest stress is
|
||||
at small t: at t=4 there are hundreds of codewords within t+2 of
|
||||
a random word, so Chase-2 returns ~66 wrong-but-valid candidates
|
||||
per trial and the CRC rejects all of them; at t=8 there are
|
||||
almost none, so the chase returns few wrong candidates at all.
|
||||
(The far-past-t cases produce no codewords: the chase finds
|
||||
nothing to offer the CRC.)
|
||||
|
||||
## CLI
|
||||
|
||||
```
|
||||
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:
|
||||
|
||||
```
|
||||
path: RECOVERED at L1 in 0.070s (L0 0.000s, L1 0.069s, L2 0.000s, L3 0.000s) cands 1 crc-rejects 0 sha-rejects 0 bch-corrected 9
|
||||
```
|
||||
|
||||
or `path: FAILED (stage nocand) after 3.048s, cands 0 crc-rejects 0 ...`.
|
||||
`-v` adds per-level trial/split/codeword counts and the failed
|
||||
block count. The summary line gives per-level landing counts.
|
||||
Output files are written under `-o` (default `./repaired`),
|
||||
preserving stored paths; directory entries are recreated.
|
||||
Overwrites existing output files.
|
||||
|
||||
## Measured corruption matrix
|
||||
|
||||
`tests/run_deep_repair_tests.sh` (hot_newyork). Scattered errors
|
||||
are `corrupt_bits` over the whole blob; burst errors are
|
||||
`corrupt_run` (1 byte = 8 bit errors, 2 bytes = 16). All files
|
||||
use `-e 4` (t=8) unless noted. Recovery means the extracted bytes
|
||||
are bit-identical to the original; a RECOVERED entry whose bytes
|
||||
differ is a false accept and fails the suite.
|
||||
|
||||
<!-- MATRIX TABLE: filled in from the suite run -->
|
||||
|
||||
| cell | n | recovered | level | mean time | mean cands |
|
||||
|---|---|---|---|---|---|
|
||||
| r512, -e 4 (t=8), scatter 0 | 10 | 10 | L0 | 0.00 s | 1 |
|
||||
| r512, -e 4, scatter 4 | 10 | 10 | L0 | 0.00 s | 1 |
|
||||
| r512, -e 4, scatter 8 (= t) | 10 | 10 | L0 | 0.00 s | 1 |
|
||||
| r512, -e 4, scatter 9 (= t+1) | 10 | 10 | L1 | 0.04 s | 1 |
|
||||
| r512, -e 4, scatter 10 (= t+2) | 10 | 3 | L2 | 4.37 s | 0 |
|
||||
| r512, -e 4, scatter 11 | 10 | 0 | — | 4.38 s | 0 |
|
||||
| r512, -e 4, scatter 12 | 10 | 0 | — | 4.38 s | 0 |
|
||||
| r512, -e 4, burst 1 byte (8 bits) | 3 | 3 | L0 | 0.00 s | 1 |
|
||||
| r512, -e 4, burst 2 bytes (16 bits) | 3 | 0 | — | 4.34 s | 0 |
|
||||
| r512, -e 3 (t=4), scatter 0/2/4 | 10 each | 10 | L0 | 0.00 s | 1 |
|
||||
| r512, -e 3, scatter 5 (= t+1) | 10 | 10 | L1 | 0.04 s | 3 |
|
||||
| r512, -e 3, scatter 6/7/8 | 5 each | 0 | — | 1.0–1.3 s | 66 |
|
||||
| r2048, -e 4, scatter 0/8 | 5 each | 5 | L0 | 0.00 s | 1 |
|
||||
| r2048, -e 4, scatter 9 (= t+1) | 5 | 5 | L1 | 0.17 s | 1 |
|
||||
| r2048, -e 4, scatter 10 (= t+2) | 5 | 0 | — | 20.75 s | 0 |
|
||||
| text 2 KiB, -e 4, scatter 0/8 | 5 each | 5 | L0 | 0.00 s | 1 |
|
||||
| text 2 KiB, -e 4, scatter 9 (= t+1) | 5 | 5 | L1 | 0.04 s | 1 |
|
||||
| big600, -e 4, scatter 8 | 2 | 2 | L0 | 0.66 s | 1 |
|
||||
| big600 pinned poly 001a, 9 in block 1 | 2 | 2 | L1 | 0.13 s | 1 |
|
||||
| big600 pinned poly 001a, 9+9 in blocks 1+2 | 2 | 2 | L3 | 16.67 s | 8 |
|
||||
| lz_rs -r 0, r512, scatter 9 | 3 | 3 | L1 | 0.04 s | 1 |
|
||||
| lz_rs -r 2, r512, scatter 9 | 3 | 3 | L0 | 0.00 s | 1 |
|
||||
|
||||
False-accept measurement (same run): t+2 cases 10/20 recovered at
|
||||
L2 with 10 candidates CRC-checked and 0 accepts; 24- and
|
||||
40-error cases 0/10 with 1 candidate CRC-checked (rejected) and
|
||||
0 accepts. **Matrix-wide: 1,162 candidates CRC-checked, 1,024
|
||||
rejected by CRC, 0 false accepts.** The dedicated false-accept
|
||||
cells are weak at t=8 (almost no codewords within t+2 of a random
|
||||
word, so the chase returns few wrong candidates); the strong
|
||||
evidence is the -e 3 (t=4) t+2 cells, where Chase-2 returns ~66
|
||||
wrong-but-valid candidates per trial and the CRC rejects all
|
||||
~992 of them.
|
||||
|
||||
## Limits, measured honestly
|
||||
|
||||
- **Chase scans are O(nbits) trials.** On m=22 blocks the trial
|
||||
rate is ~8,900/s (the GF(2^22) log/exp tables are 16 MiB each
|
||||
and stop fitting in cache; the multiply dispatches to the
|
||||
shift-and-xor path at m ≥ 17, which is ~3.5× faster than the
|
||||
cache-missing table lookup and arithmetically identical —
|
||||
`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
|
||||
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
|
||||
block reports partial coverage and does not land. Small blocks
|
||||
are fast: a 512-byte block scans in ~0.07 s.
|
||||
- **L2's rate collapses on large blocks.** The recovery
|
||||
probability is roughly 1 − (1 − (t+2)/nbits)^128: ~26% on a
|
||||
512-byte block (measured 3/10 at t+2), ~7.5% on a 2 KiB block
|
||||
(measured 0/5), ~0.03% on a 524 KiB block. L2 is a small-block
|
||||
tool.
|
||||
- **L3 needs per-block candidates.** It can only combine what L1
|
||||
and L2 retained in the pools. On pinned small blocks it lands
|
||||
(measured: 9+9 errors in two blocks recovered at L3 in 2/2
|
||||
trials, mean 16.67 s — the L2 phase dominates at 17.7 s, the L3
|
||||
combine itself is 0.014 s); on large blocks the pools stay empty
|
||||
because L1/L2 cannot finish a scan in budget.
|
||||
- **Pass-2 (the two-pass repair in `bch.c`) recovers 0/100 at
|
||||
t+1 and t+2 on 4 KiB blocks** (measured in `bch_test` phase 6):
|
||||
for random patterns the failed decode's roots do not overlap
|
||||
the true errors, so the residual step finds nothing. Chase-1
|
||||
is what actually recovers t+1. (Pass-2 still helps when the
|
||||
failed decode happens to overlap, e.g. clustered errors.)
|
||||
|
||||
## Bugs found by measurement (fixed)
|
||||
|
||||
1. **The trial flip was not applied to the reconstructed word.**
|
||||
`chase_trial` flipped only the Chien roots into the work copy,
|
||||
not the trial flip itself — so a good trial reconstructed the
|
||||
wrong word and failed the remainder check. Chase-1 recovered
|
||||
0/20 at t+1 before the fix, 20/20 after. (The trial flips are
|
||||
part of the correction, not just a syndrome tweak.)
|
||||
2. **L1 pooled candidates before trying them.** The pool cap
|
||||
(16) truncated the candidate list, and the genuine candidate
|
||||
can arrive late in scan order (wrong-but-valid codewords
|
||||
accumulate at ~1 per 32K trials, so on a 4M-bit block the
|
||||
genuine candidate can be the 20th+ one returned). A 600 KiB
|
||||
file with 9 errors in one block failed at a 60 s budget before
|
||||
the fix; after the fix L1 tries Chase candidates directly in
|
||||
scan order (as L2 already did) and pools afterwards for L3 —
|
||||
it recovers at L1 in 471.9 s. The pool cap was also raised
|
||||
(`DEEP_MAX_BLOCK_CANDS` 8 → 32) so L3 retention keeps late
|
||||
genuine candidates.
|
||||
@@ -0,0 +1,242 @@
|
||||
# LZRS v1 — lzip + BCH + Reed-Solomon archives
|
||||
|
||||
`lz_rs` is `lzply` plus a Reed-Solomon layer: the same archive
|
||||
pipeline, the same modes (`-c -d -l -t -a -i -tr`, selectors, date
|
||||
filters), but the LZRS v1 format (magic `LZRS`) and one more layer
|
||||
of error correction. The BCH layer is unchanged (same 82
|
||||
polynomials, same `-e` levels, same two-pass hash-gated repair);
|
||||
RS is layered on the outside of it.
|
||||
|
||||
## Why two layers
|
||||
|
||||
BCH corrects scattered bit errors cheaply: for the same
|
||||
correction power it needs 39–42% less parity than Reed-Solomon
|
||||
(see the BCH study in the README). But BCH is a *bit* code — one
|
||||
bad byte with 8 flipped bits costs 8 of its t, and a burst that
|
||||
wipes a run of bytes costs far more. Reed-Solomon is a *symbol*
|
||||
code: one bad byte costs 1 of its t no matter how many bits in
|
||||
that byte flipped, so a burst of N bad bytes costs N. RS is the
|
||||
right tool for byte damage and bursts; BCH stays the right tool
|
||||
for scattered bit rot. Stacked, the archive survives both.
|
||||
|
||||
## Pipeline
|
||||
|
||||
Per entry, on write:
|
||||
|
||||
```
|
||||
raw bytes -> lzip compress (or store, level 0) -> BCH encode -> RS encode
|
||||
```
|
||||
|
||||
On read, the layers run in reverse:
|
||||
|
||||
```
|
||||
RS decode -> BCH decode (two-pass, hash-gated) -> lzip decompress -> SHA-256 check
|
||||
```
|
||||
|
||||
`blob_size` in the header is the compressed stream length before
|
||||
BCH and RS parity was added. Every layer length is reconstructible
|
||||
from the header alone: the BCH length from `blob_size` + the poly
|
||||
id, the RS length from the BCH length + the parity. A truncated or
|
||||
mis-sized entry fails the length check before any decoding.
|
||||
|
||||
The SHA-256 check at the end is the oracle for the whole stack:
|
||||
no data is ever returned unless it hashes correctly. A
|
||||
bounded-distance decoder can miscorrect when damage exceeds the
|
||||
level limit, and the hash is what catches it — the same guarantee
|
||||
lzply makes for BCH alone.
|
||||
|
||||
## RS parameters (`rs.c`, `rs.h`)
|
||||
|
||||
* Code: RS(255, 255-p) over GF(2^8), systematic (data first,
|
||||
parity after), first byte = highest-degree coefficient.
|
||||
* Field: primitive polynomial `0x11D`, primitive element
|
||||
alpha = 2, first consecutive root fcr = 0, so the generator is
|
||||
`g(x) = prod_{i=0}^{p-1} (x - alpha^i)`.
|
||||
* Block: 255 symbols. A block corrects up to `p/2` symbol (byte)
|
||||
errors.
|
||||
* Shortening: the last block of an entry holds fewer than
|
||||
`k = 255-p` data bytes. It is encoded as if zero-padded to `k`
|
||||
bytes, but only the data bytes present plus the `p` parity bytes
|
||||
are stored. The decoder reconstructs the zero pad (those symbols
|
||||
were never stored, so they cannot be corrupt) and, after
|
||||
correction, checks the pad is still zero — a miscorrection that
|
||||
flips a pad symbol is rejected outright.
|
||||
* Decode: syndromes → Berlekamp-Massey (error-locator polynomial)
|
||||
→ Chien search (error positions) → Forney (error magnitudes) →
|
||||
re-check the syndromes. Anything that does not come back clean
|
||||
is a loud failure, never a silent wrong answer at this layer.
|
||||
|
||||
## The `-r` levels
|
||||
|
||||
| level | parity symbols per 255-byte block | corrects per block | overhead on incompressible data |
|
||||
|-------|-----------------------------------|--------------------|----------------------------------|
|
||||
| 0 | 0 (no RS) | 0 | 0% |
|
||||
| 1 | 8 | 4 byte errors | ~3.2% |
|
||||
| 2 | 16 | 8 byte errors | ~6.7% |
|
||||
| 3 | 24 | 12 byte errors | ~10.4% |
|
||||
| 4 | 32 | 16 byte errors | ~14.3% |
|
||||
|
||||
Default is `-r 2` (16 parity symbols, 8 correctable byte errors
|
||||
per block). `-r 0` behaves like plain lzply: the stored bytes are
|
||||
byte-identical to what `lzply -e 0` writes for the same input
|
||||
(verified by the test suite — only the headers differ).
|
||||
|
||||
## Format (LZRS v1; all integers little-endian)
|
||||
|
||||
```
|
||||
global header (16 bytes):
|
||||
magic "LZRS", version u8 (=1), flags u8, entry_count u32, reserved u64
|
||||
entries, each:
|
||||
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, u16 bch_poly_id, u16 crc16, u32 header_crc32,
|
||||
path[path_len], data[stored_size]
|
||||
end marker: u16 path_len == 0
|
||||
```
|
||||
|
||||
The entry header is 82 bytes. `header_crc32` covers the 78 bytes
|
||||
before it. Level is the lzip level (1..9) of the blob, or 0 for a
|
||||
stored (uncompressed) entry, exactly as in lzply v4. Flags: bit 1
|
||||
= directory, bit 2 = BCH mode (same bits as v4; bit 0 is unused).
|
||||
`rs_level` is the RS level (0..4). `bch_poly_id` is the BCH
|
||||
polynomial id (0 when the entry has no BCH layer); it needed its
|
||||
own field because `rs_level` no longer carries the low byte of
|
||||
the poly id the way v4 does.
|
||||
|
||||
There is no legacy support: LZRS v1 is the only LZRS format.
|
||||
`lz_rs` rejects lzply v4 archives (`LZPL` magic) outright, and
|
||||
`lzply` rejects `.lzrs` archives (`LZRS` magic) outright — the
|
||||
test suite checks both directions. The `LZRS` magic is the same
|
||||
four bytes the original unreleased v1 Reed-Solomon format used
|
||||
(the README notes it as an old rejected magic); no archive from
|
||||
that v1 is known to exist, and one would fail the entry-header
|
||||
CRC here in any case, since the v1 entry layout differs from the
|
||||
82-byte layout above — it is rejected, never misread.
|
||||
|
||||
## CRC16 (implemented; the deep-repair oracle)
|
||||
|
||||
The `crc16` field in the entry header is CRC-16/CCITT-FALSE
|
||||
(polynomial 0x1021, init 0xFFFF, no reflection, xorout 0x0000;
|
||||
check value CRC16("123456789") == 0x29B1) of the **blob** — the
|
||||
compressed stream before BCH/RS parity was added (for a stored
|
||||
entry the blob is the raw bytes; for a directory entry the blob is
|
||||
empty, so crc16 == 0xFFFF). Writers compute and store it; readers
|
||||
verify it after error-correction decoding and before
|
||||
decompression. A mismatch is a clean failure, never a misdecode:
|
||||
the SHA-256 check remains the final oracle.
|
||||
|
||||
A stored crc16 of 0x0000 with a computed value that differs means
|
||||
the archive predates the CRC16 migration (old writers wrote 0):
|
||||
it is rejected with a message telling the user to re-create it.
|
||||
(An old archive whose blob CRC happens to be 0x0000, probability
|
||||
2^-16, would pass the CRC gate — but the SHA-256 check still gates
|
||||
the data, so it cannot misdecode.)
|
||||
|
||||
The CRC16 is the fast oracle for deep repair
|
||||
(`docs/deep-repair.md`): candidate blobs are CRC-checked before
|
||||
the expensive decompress + SHA-256 step, so most wrong candidates
|
||||
are rejected cheaply. Expected residual false-accept is ~2^-16
|
||||
per candidate at the CRC stage (the SHA-256 stage then gates
|
||||
acceptance). Measured: 1,162 candidates CRC-checked across the
|
||||
deep-repair corruption matrix, 1,024 rejected by CRC, 0 false
|
||||
accepts (see `tests/run_deep_repair_tests.sh`, matrix-results.txt).
|
||||
|
||||
## Usage
|
||||
|
||||
`lz_rs` takes the same arguments as `lzply`, plus `-r`:
|
||||
|
||||
```
|
||||
lz_rs -c -r 2 photos/ photos.lzrs # default RS level
|
||||
lz_rs -c -r 4 -e 5 -9 docs/ backup.lzrs
|
||||
lz_rs -c -r 0 docs/ no-rs.lzrs # no RS parity, like plain lzply
|
||||
lz_rs -c -r2 file.txt # attached form also works
|
||||
lz_rs -c --rs-level 3 file.txt # long form
|
||||
lz_rs -d backup.lzrs out/ # extract (RS+BCH repair automatic)
|
||||
lz_rs -t backup.lzrs # test (decode and verify)
|
||||
lz_rs -i backup.lzrs # inspect: shows "BCH 001a r2"
|
||||
lz_rs -l backup.lzrs # list
|
||||
lz_rs -tr backup.lzrs # tree
|
||||
lz_rs -a backup.lzrs more/ # append (new entries use the same -r)
|
||||
```
|
||||
|
||||
Exit codes are the same as lzply: 0 ok, 1 usage, 2 I/O error,
|
||||
3 corrupt/unrecoverable. On extract/test, a repaired entry prints
|
||||
what was fixed, e.g. `file OK (RS corrected 8 symbols)` or
|
||||
`file OK (RS corrected 3 symbols, BCH corrected 5 bits)`.
|
||||
|
||||
## Benchmarks (measured on hot_newyork, 8 cores)
|
||||
|
||||
testdata/mixed: 2,387,757 bytes in, 13 entries, default `-e 4 -6`:
|
||||
|
||||
| -r | archive bytes | compress | extract |
|
||||
|----|--------------:|---------:|--------:|
|
||||
| 0 | 1,065,039 | 772 ms | 92 ms |
|
||||
| 1 | 1,099,551 | 754 ms | 143 ms |
|
||||
| 2 | 1,136,367 | 811 ms | 191 ms |
|
||||
| 3 | 1,175,727 | 819 ms | 252 ms |
|
||||
| 4 | 1,217,903 | 872 ms | 307 ms |
|
||||
|
||||
random.bin: 1,048,576 bytes of incompressible data:
|
||||
|
||||
| -r | archive bytes | compress | test |
|
||||
|----|--------------:|---------:|-----:|
|
||||
| 0 | 1,048,752 | 515 ms | 49 ms |
|
||||
| 1 | 1,082,720 | 555 ms | 106 ms |
|
||||
| 2 | 1,118,960 | 512 ms | 158 ms |
|
||||
| 3 | 1,157,712 | 565 ms | 218 ms |
|
||||
| 4 | 1,199,248 | 545 ms | 271 ms |
|
||||
|
||||
RS overhead on incompressible data is +33,968 / +36,240 / +38,752 /
|
||||
+41,536 bytes per level step — about 3.2–3.9% of the data per step.
|
||||
Compress time is flat across levels (lzip + BCH dominate); decode
|
||||
time grows about 50 ms per level per MiB (Berlekamp-Massey + Chien
|
||||
search per block). Small compressible files cost almost nothing:
|
||||
text.txt (218,800 bytes) archives to 644 bytes at `-r 0` and 740
|
||||
at `-r 4` (+24 bytes per level).
|
||||
|
||||
## Tests
|
||||
|
||||
* `rs_test` (unit): 6,243 checks, 0 failures. Covers the
|
||||
level→parity mapping, encoded lengths, clean round-trips at
|
||||
every parity for 15 buffer lengths (including shortened last
|
||||
blocks and empty input), determinism, an independent
|
||||
re-implementation cross-check of the encoder (own GF tables,
|
||||
own generator build, own polynomial division — 200 random blocks
|
||||
per parity), a syndrome-zero check on every encoded block, and
|
||||
corruption recovery: random symbol errors and burst errors up
|
||||
to t per block must decode back to the exact original, while
|
||||
t+1 errors in one block must never decode back to the original.
|
||||
Parity-byte-only errors and shortened-last-block errors are
|
||||
covered explicitly.
|
||||
* `tests/run_rs_tests.sh` (shell, wired into `make test`): 59
|
||||
checks, 0 failures. Covers round-trips at every `-r` level,
|
||||
`-e 0` / `-e 7` / `-0` combinations, determinism, `-r2` and
|
||||
`--rs-level` forms, `-r 5` rejection, `-l` / `-tr` / `-i`,
|
||||
selectors, empty and one-byte files, append + duplicate
|
||||
replacement, byte-identical stored data for `-r 0` vs
|
||||
`lzply -e 0`, and the corruption matrix on a 1 MiB random file
|
||||
at every level: t scattered byte errors recovered, t errors in
|
||||
one block recovered, burst of t recovered, burst of 2t over a
|
||||
block boundary recovered, t+1 in one block fails with exit 3,
|
||||
burst of t+1 fails with exit 3, 8 scattered bit errors
|
||||
recovered (BCH layer under RS), `-i` still works on corrupted
|
||||
data. Also `-e 0 -r 2` (RS alone) recovers 8 and fails 9, both
|
||||
formats reject each other, and a truncated archive fails.
|
||||
|
||||
## Notes and differences from lzply
|
||||
|
||||
* `lz_rs.c` is derived from `lzply.c`: same modes, same
|
||||
helpers, same append/selectors/date-filter logic, with the
|
||||
format calls swapped (82-byte LZRS headers, `lzrs_entry_encode`
|
||||
/ `lzrs_entry_decode`, `-r` option). The shared core
|
||||
(`lzply_lib.c`, `bch.c`, `sha256.c`) is untouched — no
|
||||
regression risk to the existing tools. `lzply_mount`,
|
||||
`lzply_stat`, `lzply_heal`, `lzply_check` and `lzply_refresh`
|
||||
do not read LZRS archives; that is out of scope for this job.
|
||||
* Temp files created during append still use the shared
|
||||
`.lzply-tmp-XXXXXX` name from `lzply_lib.c` (cosmetic only).
|
||||
* Directory entries carry `rs_level` 0 in the header (they hold
|
||||
no data), so `-i` shows them as `RS r0`.
|
||||
* The RS codec is self-contained (`rs.c`, no external library):
|
||||
encoder and decoder share the same generator, so no outside RS
|
||||
implementation is needed or assumed.
|
||||
@@ -1,7 +1,6 @@
|
||||
bench
|
||||
ldpc_diag
|
||||
pass2_diag
|
||||
uep_diag
|
||||
*.o
|
||||
corpora/
|
||||
results/
|
||||
+2
-5
@@ -4,7 +4,7 @@ CC ?= gcc
|
||||
CFLAGS ?= -O2 -Wall -Wextra -march=native
|
||||
CPPFLAGS ?= -I. -I..
|
||||
|
||||
SRCS = bench.c bch_wrap.c interleave.c ldpc.c polar.c uep.c \
|
||||
SRCS = bench.c bch_wrap.c interleave.c ldpc.c \
|
||||
../bch.c ../sha256.c
|
||||
OBJS = $(SRCS:.c=.o)
|
||||
|
||||
@@ -17,13 +17,10 @@ ldpc_diag: ldpc_diag.c ldpc.c
|
||||
pass2_diag: pass2_diag.c ../bch.c ../sha256.c
|
||||
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ pass2_diag.c ../bch.c ../sha256.c -lm
|
||||
|
||||
uep_diag: uep_diag.c uep.c bch_wrap.c ../bch.c ../sha256.c
|
||||
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ uep_diag.c uep.c bch_wrap.c ../bch.c ../sha256.c -lm
|
||||
|
||||
%.o: %.c
|
||||
$(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $@
|
||||
|
||||
clean:
|
||||
rm -f bench ldpc_diag pass2_diag uep_diag $(OBJS)
|
||||
rm -f bench ldpc_diag pass2_diag $(OBJS)
|
||||
|
||||
.PHONY: clean
|
||||
@@ -1,5 +1,10 @@
|
||||
# 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
|
||||
|
||||
+1
-12
@@ -37,8 +37,6 @@ 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);
|
||||
ecc_codec_t *polar_new(int rate_pct, int design_exp);
|
||||
ecc_codec_t *uep_new(int crit_bytes, int t_hi, int t_lo);
|
||||
|
||||
static ecc_codec_t *make_codec(const char *name)
|
||||
{
|
||||
@@ -52,14 +50,6 @@ static ecc_codec_t *make_codec(const char *name)
|
||||
return interleave_new(d, t);
|
||||
if (sscanf(name, "ldpc-r%d", &v) == 1)
|
||||
return ldpc_new(v);
|
||||
int dexp;
|
||||
if (sscanf(name, "polar-r%d-d%d", &v, &dexp) == 2)
|
||||
return polar_new(v, dexp);
|
||||
if (sscanf(name, "polar-r%d", &v) == 1)
|
||||
return polar_new(v, 2);
|
||||
int cb, th, tl;
|
||||
if (sscanf(name, "uep-c%d-h%d-l%d", &cb, &th, &tl) == 3)
|
||||
return uep_new(cb, th, tl);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
@@ -114,8 +104,7 @@ static void usage(void)
|
||||
" [--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"
|
||||
" polar-r{90,95} uep-c{1024,4096}-h{16,32}-l{2,4}\n");
|
||||
" intlv-d{16,32,64}-bch1k-t{8,16,32} ldpc-r{90,95}\n");
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
|
||||
-333
@@ -1,333 +0,0 @@
|
||||
/* polar.c - polar code codec for the experiments harness.
|
||||
*
|
||||
* N=4096, successive-cancellation (SC) decoding with the min-sum
|
||||
* f-function. Construction is Arikan's Bhattacharyya recursion for
|
||||
* the binary erasure channel with erasure probability equal to the
|
||||
* BSC's Bhattacharyya parameter Z = 2*sqrt(p(1-p)) at a design
|
||||
* crossover p (see polar_new: the codec name selects it, e.g.
|
||||
* polar-r90-d3 designs for p=1e-3; plain polar-r90 designs for
|
||||
* p=1e-2). The design point matters: designing for a much worse
|
||||
* channel than the operating point ranks the marginal channels
|
||||
* wrong and SC pays for it.
|
||||
*
|
||||
* polar-r90: K=3680 info bits (460 B), rate 0.89844, overhead 11.30%.
|
||||
* polar-r95: K=3888 info bits (486 B), rate 0.94922, overhead 5.35%.
|
||||
*
|
||||
* A blob is split into blocks of K data bytes; the last block is
|
||||
* zero-padded. Stored length per block is exactly N/8 = 512 bytes.
|
||||
*
|
||||
* Note: SC decoding always returns a codeword, so decode() cannot
|
||||
* detect failure by itself -- it returns 0 whenever decoding
|
||||
* completes, and the caller (bench / lzply's SHA-256) is the oracle
|
||||
* that decides whether the recovered data is correct. That matches
|
||||
* lzply's architecture: the entry SHA is the miscorrection guard.
|
||||
* Channel LLR uses a fixed nominal crossover p0 = 1e-3, same honest
|
||||
* setting as the LDPC codec.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <math.h>
|
||||
|
||||
#include "ecc_iface.h"
|
||||
|
||||
#define POLAR_N 4096
|
||||
#define POLAR_LOGN 12
|
||||
#define POLAR_P0 1e-3
|
||||
|
||||
typedef struct {
|
||||
int k; /* info bits */
|
||||
int kbytes; /* info bytes per block */
|
||||
double p_design; /* design crossover for the BEC construction */
|
||||
uint8_t frozen[POLAR_N]; /* 1 = frozen (0 bit) */
|
||||
float *llr; /* N, decode workspace */
|
||||
float *ws; /* N, SC scratch (bump-allocated down the tree) */
|
||||
uint8_t *bits; /* N, decoded info vector (leaf decisions) */
|
||||
uint8_t *psum; /* N, partial sums (re-encoded codeword) */
|
||||
} polar_t;
|
||||
|
||||
static void polar_build_frozen(polar_t *P)
|
||||
{
|
||||
/* BEC Bhattacharyya recursion: Z starts at eps, then per level
|
||||
the upper (bad) channel gets 2Z-Z^2 and the lower (good) one
|
||||
gets Z^2. z[] holds the values in bit-reversed order matching
|
||||
the standard construction; sorting by Z ascending gives the
|
||||
reliability order. */
|
||||
double eps = 2.0 * sqrt(P->p_design * (1.0 - P->p_design));
|
||||
double z[POLAR_N];
|
||||
for (int i = 0; i < POLAR_N; i++)
|
||||
z[i] = eps;
|
||||
for (int level = 0; level < POLAR_LOGN; level++) {
|
||||
int step = 1 << (level + 1);
|
||||
int half = 1 << level;
|
||||
for (int base = 0; base < POLAR_N; base += step) {
|
||||
for (int i = 0; i < half; i++) {
|
||||
double a = z[base + i];
|
||||
double b = z[base + half + i];
|
||||
/* upper (first half) is the worse channel */
|
||||
z[base + i] = 2 * a - a * a;
|
||||
z[base + half + i] = b * b;
|
||||
}
|
||||
}
|
||||
}
|
||||
/* The recursion above indexes channels in natural order only if
|
||||
the pairing is right; verify by construction: sort indices by
|
||||
Z and take the K smallest as information positions. */
|
||||
int idx[POLAR_N];
|
||||
for (int i = 0; i < POLAR_N; i++)
|
||||
idx[i] = i;
|
||||
/* simple insertion-free sort: qsort with a comparator on z */
|
||||
/* (z is captured via a file-scope pointer for the comparator) */
|
||||
extern double *polar_sort_z;
|
||||
polar_sort_z = z;
|
||||
/* qsort needs a comparator; defined below */
|
||||
extern int polar_cmp_idx(const void *, const void *);
|
||||
qsort(idx, POLAR_N, sizeof(int), polar_cmp_idx);
|
||||
memset(P->frozen, 1, POLAR_N);
|
||||
for (int i = 0; i < P->k; i++)
|
||||
P->frozen[idx[i]] = 0;
|
||||
}
|
||||
|
||||
double *polar_sort_z = NULL;
|
||||
int polar_cmp_idx(const void *a, const void *b)
|
||||
{
|
||||
int ia = *(const int *)a, ib = *(const int *)b;
|
||||
if (polar_sort_z[ia] < polar_sort_z[ib])
|
||||
return -1;
|
||||
if (polar_sort_z[ia] > polar_sort_z[ib])
|
||||
return 1;
|
||||
return ia - ib;
|
||||
}
|
||||
|
||||
/* polar transform: in-place butterfly, u ^= u shifted */
|
||||
static void polar_transform(uint8_t *u, int n)
|
||||
{
|
||||
for (int len = 1; len < n; len <<= 1) {
|
||||
for (int base = 0; base < n; base += 2 * len) {
|
||||
for (int i = 0; i < len; i++) {
|
||||
int a = base + i, b = base + len + i;
|
||||
u[a] ^= u[b];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 polar_encode(ecc_codec_t *c, const uint8_t *data, size_t len,
|
||||
uint8_t **out)
|
||||
{
|
||||
polar_t *P = (polar_t *)c->priv;
|
||||
size_t nblocks = (len + (size_t)P->kbytes - 1) / (size_t)P->kbytes;
|
||||
size_t slen = nblocks * (POLAR_N / 8);
|
||||
uint8_t *buf = (uint8_t *)calloc(slen ? slen : 1, 1);
|
||||
if (!buf)
|
||||
return 0;
|
||||
uint8_t *u = (uint8_t *)malloc(POLAR_N);
|
||||
if (!u) {
|
||||
free(buf);
|
||||
return 0;
|
||||
}
|
||||
for (size_t b = 0; b < nblocks; b++) {
|
||||
size_t dlen = len - b * (size_t)P->kbytes < (size_t)P->kbytes
|
||||
? len - b * (size_t)P->kbytes
|
||||
: (size_t)P->kbytes;
|
||||
memset(u, 0, POLAR_N);
|
||||
int dp = 0;
|
||||
for (int i = 0; i < POLAR_N; i++) {
|
||||
if (P->frozen[i])
|
||||
continue;
|
||||
if (dp < (int)dlen * 8)
|
||||
u[i] = (uint8_t)get_bit(data + b * (size_t)P->kbytes, dp);
|
||||
dp++;
|
||||
}
|
||||
polar_transform(u, POLAR_N);
|
||||
uint8_t *cw = buf + b * (POLAR_N / 8);
|
||||
for (int i = 0; i < POLAR_N; i++)
|
||||
set_bit(cw, i, u[i]);
|
||||
}
|
||||
free(u);
|
||||
c->overhead = len ? (double)slen / (double)len - 1.0 : 0.0;
|
||||
*out = buf;
|
||||
return slen;
|
||||
}
|
||||
|
||||
static inline float polar_f(float a, float b)
|
||||
{
|
||||
float m = fabsf(a) < fabsf(b) ? fabsf(a) : fabsf(b);
|
||||
int s = ((a < 0) ^ (b < 0)) ? -1 : 1;
|
||||
return s * m;
|
||||
}
|
||||
static inline float polar_g(float a, float b, int u)
|
||||
{
|
||||
return b + (u ? -a : a);
|
||||
}
|
||||
|
||||
static void sc_rec(polar_t *P, const float *llr, int off, int len,
|
||||
float *ws)
|
||||
{
|
||||
if (len == 1) {
|
||||
/* Leaf: the decision is the decoded info bit. The partial
|
||||
sum at a leaf is the bit itself. The two arrays must stay
|
||||
separate: the combine step below rewrites psum (it becomes
|
||||
the re-encoded codeword) and must not touch bits. */
|
||||
int b = 0;
|
||||
if (!P->frozen[off])
|
||||
b = llr[0] < 0 ? 1 : 0;
|
||||
P->bits[off] = (uint8_t)b;
|
||||
P->psum[off] = (uint8_t)b;
|
||||
return;
|
||||
}
|
||||
int half = len / 2;
|
||||
/* Scratch for this level lives in ws[0..half); children bump
|
||||
past it. Total scratch along any path is N floats. */
|
||||
float *tmp = ws;
|
||||
for (int i = 0; i < half; i++)
|
||||
tmp[i] = polar_f(llr[i], llr[half + i]);
|
||||
sc_rec(P, tmp, off, half, ws + half);
|
||||
for (int i = 0; i < half; i++)
|
||||
tmp[i] = polar_g(llr[i], llr[half + i], P->psum[off + i]);
|
||||
sc_rec(P, tmp, off + half, half, ws + half);
|
||||
for (int i = 0; i < half; i++)
|
||||
P->psum[off + i] ^= P->psum[off + half + i];
|
||||
}
|
||||
|
||||
static int polar_decode_block(polar_t *P, const uint8_t *cw_in,
|
||||
uint8_t *data_out, long *corrected_out)
|
||||
{
|
||||
float L0 = (float)log((1.0 - POLAR_P0) / POLAR_P0);
|
||||
for (int i = 0; i < POLAR_N; i++)
|
||||
P->llr[i] = get_bit(cw_in, i) ? -L0 : L0;
|
||||
sc_rec(P, P->llr, 0, POLAR_N, P->ws);
|
||||
/* psum now holds the decoded codeword; count corrected bits
|
||||
against the received codeword. */
|
||||
long corr = 0;
|
||||
for (int i = 0; i < POLAR_N; i++)
|
||||
if (P->psum[i] != get_bit(cw_in, i))
|
||||
corr++;
|
||||
if (corrected_out)
|
||||
*corrected_out = corr;
|
||||
/* data bits out: info positions in increasing index order */
|
||||
int dp = 0;
|
||||
memset(data_out, 0, (size_t)P->kbytes);
|
||||
for (int i = 0; i < POLAR_N; i++) {
|
||||
if (P->frozen[i])
|
||||
continue;
|
||||
set_bit(data_out, dp++, P->bits[i]);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int polar_decode(ecc_codec_t *c, const uint8_t *stored, size_t slen,
|
||||
size_t orig_len, uint8_t *out, long *corrected)
|
||||
{
|
||||
polar_t *P = (polar_t *)c->priv;
|
||||
size_t nblocks = (orig_len + (size_t)P->kbytes - 1) / (size_t)P->kbytes;
|
||||
if (slen != nblocks * (POLAR_N / 8))
|
||||
return -1;
|
||||
long corr = 0;
|
||||
for (size_t b = 0; b < nblocks; b++) {
|
||||
uint8_t *db = (uint8_t *)malloc((size_t)P->kbytes);
|
||||
if (!db)
|
||||
return -1;
|
||||
long bc = 0;
|
||||
polar_decode_block(P, stored + b * (POLAR_N / 8), db, &bc);
|
||||
corr += bc;
|
||||
size_t dlen = orig_len - b * (size_t)P->kbytes < (size_t)P->kbytes
|
||||
? orig_len - b * (size_t)P->kbytes
|
||||
: (size_t)P->kbytes;
|
||||
memcpy(out + b * (size_t)P->kbytes, db, dlen);
|
||||
free(db);
|
||||
}
|
||||
if (corrected)
|
||||
*corrected = corr;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void polar_destroy(ecc_codec_t *c)
|
||||
{
|
||||
polar_t *P = (polar_t *)c->priv;
|
||||
free(P->llr);
|
||||
free(P->ws);
|
||||
free(P->bits);
|
||||
free(P->psum);
|
||||
free(P);
|
||||
free((void *)c->name);
|
||||
free(c);
|
||||
}
|
||||
|
||||
ecc_codec_t *polar_new(int rate_pct, int design_exp)
|
||||
{
|
||||
int k;
|
||||
const char *tag;
|
||||
if (rate_pct == 90) {
|
||||
k = 3680;
|
||||
tag = "polar-r90";
|
||||
} else if (rate_pct == 95) {
|
||||
k = 3888;
|
||||
tag = "polar-r95";
|
||||
} else {
|
||||
return NULL;
|
||||
}
|
||||
polar_t *P = (polar_t *)calloc(1, sizeof(*P));
|
||||
if (!P)
|
||||
return NULL;
|
||||
P->k = k;
|
||||
P->kbytes = k / 8;
|
||||
P->p_design = pow(10.0, -(double)design_exp);
|
||||
P->llr = (float *)malloc((size_t)POLAR_N * sizeof(float));
|
||||
P->ws = (float *)malloc((size_t)POLAR_N * sizeof(float));
|
||||
P->bits = (uint8_t *)malloc((size_t)POLAR_N);
|
||||
P->psum = (uint8_t *)malloc((size_t)POLAR_N);
|
||||
if (!P->llr || !P->ws || !P->bits || !P->psum) {
|
||||
free(P->llr);
|
||||
free(P->ws);
|
||||
free(P->bits);
|
||||
free(P->psum);
|
||||
free(P);
|
||||
return NULL;
|
||||
}
|
||||
polar_build_frozen(P);
|
||||
ecc_codec_t *c = (ecc_codec_t *)calloc(1, sizeof(*c));
|
||||
if (!c) {
|
||||
free(P->llr);
|
||||
free(P->ws);
|
||||
free(P->bits);
|
||||
free(P->psum);
|
||||
free(P);
|
||||
return NULL;
|
||||
}
|
||||
char *name = (char *)malloc(24);
|
||||
if (!name) {
|
||||
free(P->llr);
|
||||
free(P->ws);
|
||||
free(P->bits);
|
||||
free(P->psum);
|
||||
free(P);
|
||||
free(c);
|
||||
return NULL;
|
||||
}
|
||||
if (design_exp == 2)
|
||||
snprintf(name, 24, "%s", tag);
|
||||
else
|
||||
snprintf(name, 24, "%s-d%d", tag, design_exp);
|
||||
c->name = name;
|
||||
c->desc = "polar code, successive-cancellation decoding";
|
||||
c->block_data = (size_t)P->kbytes;
|
||||
c->encode = polar_encode;
|
||||
c->decode = polar_decode;
|
||||
c->recover_verified = NULL;
|
||||
c->destroy = polar_destroy;
|
||||
c->priv = P;
|
||||
return c;
|
||||
}
|
||||
@@ -1,177 +0,0 @@
|
||||
/* uep.c - unequal error protection over small-block BCH.
|
||||
*
|
||||
* The blob is split into a critical prefix (the first C bytes -- the
|
||||
* lzip header and the start of the LZMA stream, where an error costs
|
||||
* the most) protected at BCH t_hi, and the remainder at t_lo, both
|
||||
* with m=13 small blocks. Stored = prefix_stored + rest_stored; the
|
||||
* split point is recomputed from C and orig_len, so no per-entry
|
||||
* metadata is needed beyond the codec parameters.
|
||||
*
|
||||
* Two things to know before judging it:
|
||||
* - Exact recovery is dominated by the WEAK tier: UEP cannot beat
|
||||
* uniform BCH at the same total overhead on whole-blob recovery,
|
||||
* because the weak tier fails first. The fair comparison is
|
||||
* t_lo == the uniform baseline t, with t_hi > t_lo costing only
|
||||
* a little extra overhead (the prefix is short).
|
||||
* - The win, if any, is graceful degradation: the prefix survives
|
||||
* when the rest does not. That only helps lzply if it gains a
|
||||
* salvage mode (today the entry SHA gates all-or-nothing
|
||||
* extraction), so prefix survival is reported separately by
|
||||
* uep_diag.c, not by bench.c.
|
||||
* Pass 2 is not wired: the recovery oracle is the whole-blob SHA,
|
||||
* which cannot verify a prefix candidate on its own.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "ecc_iface.h"
|
||||
#include "bch_wrap.h"
|
||||
#include "uep.h"
|
||||
|
||||
typedef struct {
|
||||
ecc_codec_t *hi; /* bch1k-t{t_hi} */
|
||||
ecc_codec_t *lo; /* bch1k-t{t_lo} */
|
||||
int crit_bytes;
|
||||
int t_hi, t_lo;
|
||||
} uep_priv_t;
|
||||
|
||||
/* Max data bytes per block under small-block BCH at t (pinned m=13
|
||||
poly, N=8191): floor((8191 - 13*t)/8). NOTE: this depends on t --
|
||||
971 for t=32 but 1010 for t=8. An earlier version hardcoded 971
|
||||
and broke every tier but t=32. */
|
||||
static size_t bch1k_max_data(int t)
|
||||
{
|
||||
return (8191 - (size_t)13 * (size_t)t) / 8;
|
||||
}
|
||||
|
||||
/* Stored length of dlen data bytes under small-block BCH at t:
|
||||
blocks of bch1k_max_data(t) bytes, ceil((8*dlen + t*13)/8) stored
|
||||
each. (Mirrors bch_block_stored_len for the pinned m=13 poly.) */
|
||||
static size_t bch1k_stored_len(size_t dlen, int t)
|
||||
{
|
||||
size_t maxd = bch1k_max_data(t);
|
||||
size_t total = 0;
|
||||
size_t r = (size_t)t * 13;
|
||||
while (dlen > 0) {
|
||||
size_t b = dlen < maxd ? dlen : maxd;
|
||||
total += (8 * b + r + 7) / 8;
|
||||
dlen -= b;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
static size_t uep_encode(ecc_codec_t *c, const uint8_t *data, size_t len,
|
||||
uint8_t **out)
|
||||
{
|
||||
uep_priv_t *p = (uep_priv_t *)c->priv;
|
||||
size_t clen = len < (size_t)p->crit_bytes ? len : (size_t)p->crit_bytes;
|
||||
uint8_t *hi = NULL, *lo = NULL;
|
||||
size_t hi_len = p->hi->encode(p->hi, data, clen, &hi);
|
||||
size_t lo_len = 0;
|
||||
if (hi_len)
|
||||
lo_len = p->lo->encode(p->lo, data + clen, len - clen, &lo);
|
||||
if (!hi_len || (len > clen && !lo_len)) {
|
||||
free(hi);
|
||||
free(lo);
|
||||
return 0;
|
||||
}
|
||||
uint8_t *buf = (uint8_t *)malloc(hi_len + lo_len);
|
||||
if (!buf) {
|
||||
free(hi);
|
||||
free(lo);
|
||||
return 0;
|
||||
}
|
||||
memcpy(buf, hi, hi_len);
|
||||
memcpy(buf + hi_len, lo, lo_len);
|
||||
free(hi);
|
||||
free(lo);
|
||||
c->overhead = len ? (double)(hi_len + lo_len) / (double)len - 1.0 : 0.0;
|
||||
*out = buf;
|
||||
return hi_len + lo_len;
|
||||
}
|
||||
|
||||
int uep_decode_parts(ecc_codec_t *c, const uint8_t *stored, size_t slen,
|
||||
size_t orig_len, uint8_t *out)
|
||||
{
|
||||
uep_priv_t *p = (uep_priv_t *)c->priv;
|
||||
size_t clen = orig_len < (size_t)p->crit_bytes
|
||||
? orig_len
|
||||
: (size_t)p->crit_bytes;
|
||||
size_t hi_len = bch1k_stored_len(clen, p->t_hi);
|
||||
size_t lo_len = bch1k_stored_len(orig_len - clen, p->t_lo);
|
||||
if (hi_len + lo_len != slen)
|
||||
return 0;
|
||||
int mask = 0;
|
||||
long corr = -1;
|
||||
if (p->hi->decode(p->hi, stored, hi_len, clen, out, &corr) == 0)
|
||||
mask |= 1;
|
||||
if (p->lo->decode(p->lo, stored + hi_len, lo_len, orig_len - clen,
|
||||
out + clen, &corr) == 0)
|
||||
mask |= 2;
|
||||
return mask;
|
||||
}
|
||||
|
||||
static int uep_decode(ecc_codec_t *c, const uint8_t *stored, size_t slen,
|
||||
size_t orig_len, uint8_t *out, long *corrected)
|
||||
{
|
||||
(void)corrected;
|
||||
return uep_decode_parts(c, stored, slen, orig_len, out) == 3 ? 0 : -1;
|
||||
}
|
||||
|
||||
static void uep_destroy(ecc_codec_t *c)
|
||||
{
|
||||
uep_priv_t *p = (uep_priv_t *)c->priv;
|
||||
if (p->hi)
|
||||
p->hi->destroy(p->hi);
|
||||
if (p->lo)
|
||||
p->lo->destroy(p->lo);
|
||||
free(p);
|
||||
free((void *)c->name);
|
||||
free(c);
|
||||
}
|
||||
|
||||
ecc_codec_t *uep_new(int crit_bytes, int t_hi, int t_lo)
|
||||
{
|
||||
ecc_codec_t *hi = bch_1k_new(t_hi);
|
||||
ecc_codec_t *lo = bch_1k_new(t_lo);
|
||||
if (!hi || !lo) {
|
||||
if (hi)
|
||||
hi->destroy(hi);
|
||||
if (lo)
|
||||
lo->destroy(lo);
|
||||
return NULL;
|
||||
}
|
||||
ecc_codec_t *c = (ecc_codec_t *)calloc(1, sizeof(*c));
|
||||
uep_priv_t *p = (uep_priv_t *)calloc(1, sizeof(*p));
|
||||
if (!c || !p) {
|
||||
free(c);
|
||||
free(p);
|
||||
hi->destroy(hi);
|
||||
lo->destroy(lo);
|
||||
return NULL;
|
||||
}
|
||||
char *name = (char *)malloc(32);
|
||||
if (!name) {
|
||||
free(c);
|
||||
free(p);
|
||||
hi->destroy(hi);
|
||||
lo->destroy(lo);
|
||||
return NULL;
|
||||
}
|
||||
snprintf(name, 32, "uep-c%d-h%d-l%d", crit_bytes, t_hi, t_lo);
|
||||
p->hi = hi;
|
||||
p->lo = lo;
|
||||
p->crit_bytes = crit_bytes;
|
||||
p->t_hi = t_hi;
|
||||
p->t_lo = t_lo;
|
||||
c->name = name;
|
||||
c->desc = "unequal error protection over small-block BCH";
|
||||
c->block_data = bch1k_max_data(t_lo); /* bulk tier's block size */
|
||||
c->encode = uep_encode;
|
||||
c->decode = uep_decode;
|
||||
c->recover_verified = NULL;
|
||||
c->destroy = uep_destroy;
|
||||
c->priv = p;
|
||||
return c;
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
/* uep.h - UEP codec plus the part-wise decode helper used by uep_diag. */
|
||||
#ifndef EXP_UEP_H
|
||||
#define EXP_UEP_H
|
||||
|
||||
#include "ecc_iface.h"
|
||||
|
||||
ecc_codec_t *uep_new(int crit_bytes, int t_hi, int t_lo);
|
||||
|
||||
/* Decode and report per-part success: bit 1 = critical prefix decoded,
|
||||
bit 2 = remainder decoded. Returns the bitmask (0..3). */
|
||||
int uep_decode_parts(ecc_codec_t *c, const uint8_t *stored, size_t slen,
|
||||
size_t orig_len, uint8_t *out);
|
||||
|
||||
#endif /* EXP_UEP_H */
|
||||
-125
@@ -1,125 +0,0 @@
|
||||
/* uep_diag.c - diagnostic for the UEP codec (NOT part of bench).
|
||||
* Reports BOTH whole-blob exact recovery AND critical-prefix survival
|
||||
* per corruption setting, so the graceful-degradation claim can be
|
||||
* judged: a prefix that survives while the rest fails is only useful
|
||||
* with a salvage mode, but it is the metric UEP exists for.
|
||||
* Usage: uep_diag <codec> <blob> <size> <trials> (--ber X | --burst L,C)
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdint.h>
|
||||
#include "ecc_iface.h"
|
||||
#include "uep.h"
|
||||
|
||||
static uint64_t rs = 0x13579bdf2468aceULL;
|
||||
static inline uint64_t xr(void)
|
||||
{
|
||||
rs ^= rs << 13;
|
||||
rs ^= rs >> 7;
|
||||
rs ^= rs << 17;
|
||||
return rs;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
if (argc < 6) {
|
||||
fprintf(stderr,
|
||||
"usage: uep_diag <codec> <blob> <size> <trials> "
|
||||
"(--ber X | --burst L,C)\n");
|
||||
return 2;
|
||||
}
|
||||
const char *codec_name = argv[1];
|
||||
const char *blob_path = argv[2];
|
||||
size_t win_size = (size_t)strtoull(argv[3], NULL, 0);
|
||||
long trials = strtol(argv[4], NULL, 0);
|
||||
double ber = 0;
|
||||
long burst_len = 0, burst_count = 0;
|
||||
int is_burst = 0;
|
||||
if (!strcmp(argv[5], "--ber") && argc > 6)
|
||||
ber = strtod(argv[6], NULL);
|
||||
else if (!strcmp(argv[5], "--burst") && argc > 6) {
|
||||
is_burst = 1;
|
||||
burst_len = strtol(argv[6], NULL, 0);
|
||||
char *comma = strchr(argv[6], ',');
|
||||
burst_count = comma ? strtol(comma + 1, NULL, 0) : 1;
|
||||
} else {
|
||||
fprintf(stderr, "uep_diag: need --ber X or --burst L,C\n");
|
||||
return 2;
|
||||
}
|
||||
FILE *f = fopen(blob_path, "rb");
|
||||
if (!f) {
|
||||
fprintf(stderr, "uep_diag: cannot open %s\n", blob_path);
|
||||
return 2;
|
||||
}
|
||||
fseek(f, 0, SEEK_END);
|
||||
long file_len = ftell(f);
|
||||
fseek(f, 0, SEEK_SET);
|
||||
uint8_t *file = (uint8_t *)malloc((size_t)file_len);
|
||||
if (!file || fread(file, 1, (size_t)file_len, f) != (size_t)file_len)
|
||||
return 2;
|
||||
fclose(f);
|
||||
|
||||
ecc_codec_t *c = NULL;
|
||||
/* parse the codec name the same way bench does */
|
||||
int cb, th, tl;
|
||||
if (sscanf(codec_name, "uep-c%d-h%d-l%d", &cb, &th, &tl) != 3) {
|
||||
fprintf(stderr, "uep_diag: bad codec %s\n", codec_name);
|
||||
return 2;
|
||||
}
|
||||
c = uep_new(cb, th, tl);
|
||||
if (!c) {
|
||||
fprintf(stderr, "uep_diag: uep_new failed\n");
|
||||
return 2;
|
||||
}
|
||||
uint8_t *win = (uint8_t *)malloc(win_size);
|
||||
uint8_t *out = (uint8_t *)malloc(win_size);
|
||||
uint8_t *stored = NULL, *rx = NULL;
|
||||
long whole = 0, prefix = 0;
|
||||
uint64_t ber_thr = (uint64_t)(ber * 18446744073709551616.0);
|
||||
for (long tr = 0; tr < trials; tr++) {
|
||||
size_t off = (size_t)(xr() % ((size_t)file_len - win_size + 1));
|
||||
memcpy(win, file + off, win_size);
|
||||
size_t slen = c->encode(c, win, win_size, &stored);
|
||||
if (!slen) {
|
||||
fprintf(stderr, "uep_diag: encode failed\n");
|
||||
return 2;
|
||||
}
|
||||
if (tr == 0) {
|
||||
rx = (uint8_t *)malloc(slen);
|
||||
if (!rx)
|
||||
return 2;
|
||||
}
|
||||
memcpy(rx, stored, slen);
|
||||
if (is_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);
|
||||
}
|
||||
} else {
|
||||
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;
|
||||
}
|
||||
}
|
||||
int mask = uep_decode_parts(c, rx, slen, win_size, out);
|
||||
if (mask == 3 && memcmp(out, win, win_size) == 0)
|
||||
whole++;
|
||||
if (mask & 1)
|
||||
prefix++;
|
||||
free(stored);
|
||||
stored = NULL;
|
||||
}
|
||||
printf("%s %s trials=%ld whole=%.4f prefix=%.4f overhead=%.2f%%\n",
|
||||
codec_name, is_burst ? "burst" : "ber", trials,
|
||||
(double)whole / (double)trials, (double)prefix / (double)trials,
|
||||
c->overhead * 100.0);
|
||||
return 0;
|
||||
}
|
||||
@@ -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
|
||||
@@ -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.
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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]);
|
||||
}
|
||||
@@ -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)
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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);
|
||||
@@ -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;
|
||||
}
|
||||
Whitespace-only changes.
|
|
@@ -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
|
||||
|
@@ -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
|
||||
|
@@ -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
|
||||
|
@@ -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
|
||||
|
@@ -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
|
||||
|
@@ -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
|
||||
|
@@ -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
|
||||
|
@@ -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
|
||||
|
@@ -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
|
||||
|
@@ -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
|
||||
|
@@ -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
|
||||
|
@@ -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
|
||||
|
@@ -105,7 +105,9 @@
|
||||
#include <unistd.h>
|
||||
|
||||
#include "bch.h"
|
||||
#include "deep_repair.h"
|
||||
#include "lzply_lib.h"
|
||||
#include "repair_cmd.h"
|
||||
|
||||
|
||||
|
||||
@@ -504,6 +506,7 @@ static int write_entries(FILE *f, entry_list_t *list, int level,
|
||||
h.orig_size = 0;
|
||||
h.stored_size = 0;
|
||||
h.blob_size = 0;
|
||||
h.crc16 = crc16_of(NULL, 0); /* empty blob: 0xFFFF */
|
||||
lzply_sha256((const uint8_t *)"", 0, h.sha);
|
||||
if (write_entry_header(f, &h) != 0)
|
||||
return -1;
|
||||
@@ -517,7 +520,7 @@ static int write_entries(FILE *f, entry_list_t *list, int level,
|
||||
}
|
||||
if (entry_encode(raw, raw_len, level, ecc,
|
||||
&stored, &stored_len, &blob_len, &poly_id, &is_bch,
|
||||
&eff_level, h.sha) != 0) {
|
||||
&eff_level, h.sha, &h.crc16) != 0) {
|
||||
fprintf(stderr, "%s: failed to encode %s\n", lzply_progname, e->full);
|
||||
free(raw);
|
||||
return -1;
|
||||
@@ -640,7 +643,7 @@ static int cmd_create(const char **inputs, int ninputs, const char *output_arg,
|
||||
rc = EXIT_IO;
|
||||
goto done;
|
||||
}
|
||||
/* The format is v4, always. */
|
||||
/* The format is v5, always. */
|
||||
f = fopen(out_path, "wb");
|
||||
if (!f) {
|
||||
fprintf(stderr, "%s: cannot create %s: %s\n", lzply_progname, out_path,
|
||||
@@ -782,7 +785,7 @@ static int cmd_append(const char *archive, const char **inputs, int ninputs,
|
||||
for (j = 0; j < old.len; j++)
|
||||
if (replaced[j])
|
||||
nrep++;
|
||||
(void)old_version; /* the format is v4, always */
|
||||
(void)old_version; /* the format is v5, always */
|
||||
new_count = (uint32_t)(old.len - nrep + list.len);
|
||||
if (!has_dup) {
|
||||
/* True incremental append: stage the new entries to a temp
|
||||
@@ -1011,11 +1014,25 @@ static int open_archive(const char *path, FILE **f_out, uint32_t *count_out,
|
||||
fclose(f);
|
||||
return EXIT_IO;
|
||||
}
|
||||
if (read_global_header(f, count_out) != 0) {
|
||||
fprintf(stderr, "%s: %s is not an lzply archive (bad magic/version)\n",
|
||||
lzply_progname, path);
|
||||
fclose(f);
|
||||
return EXIT_CORRUPT;
|
||||
{
|
||||
int ver = 0;
|
||||
int ghr = read_global_header_full(f, &ver, count_out);
|
||||
if (ghr != 0) {
|
||||
if (ghr == -2 && ver == 4)
|
||||
fprintf(stderr, "%s: %s is an LZPL v4 archive, which "
|
||||
"predates the CRC16 migration (v5); re-create it "
|
||||
"with lzply -c -- it cannot be read by this version\n",
|
||||
lzply_progname, path);
|
||||
else if (ghr == -2)
|
||||
fprintf(stderr, "%s: %s is an LZPL archive of unsupported "
|
||||
"version %d (this version reads v%d only)\n",
|
||||
lzply_progname, path, ver, LZPLY_VERSION);
|
||||
else
|
||||
fprintf(stderr, "%s: %s is not an lzply archive (bad magic/version)\n",
|
||||
lzply_progname, path);
|
||||
fclose(f);
|
||||
return EXIT_CORRUPT;
|
||||
}
|
||||
}
|
||||
*f_out = f;
|
||||
*size_out = st.st_size;
|
||||
@@ -1035,7 +1052,7 @@ static int cmd_list(const char *archive, const char **selectors, int nselectors,
|
||||
uint32_t seen = 0;
|
||||
if (rc != 0)
|
||||
return rc;
|
||||
printf("%-40s %12s %12s lvl ecc\n", "path", "original", "stored");
|
||||
printf("%-40s %12s %12s lvl ecc crc16\n", "path", "original", "stored");
|
||||
for (;;) {
|
||||
ehdr_t h;
|
||||
int r = read_entry_header(f, &h);
|
||||
@@ -1064,10 +1081,10 @@ static int cmd_list(const char *archive, const char **selectors, int nselectors,
|
||||
(unsigned)(h.rs_level | ((unsigned)h.reserved << 8)));
|
||||
else
|
||||
snprintf(ecc, sizeof ecc, "-");
|
||||
printf("%-40s %12s %12s %d %-8s\n", h.path,
|
||||
printf("%-40s %12s %12s %d %-8s %04x\n", h.path,
|
||||
human_size(h.orig_size, b1, sizeof b1),
|
||||
human_size(h.stored_size, b2, sizeof b2),
|
||||
h.level, ecc);
|
||||
h.level, ecc, (unsigned)h.crc16);
|
||||
if (fseeko(f, (off_t)h.stored_size, SEEK_CUR) != 0) {
|
||||
fprintf(stderr, "%s: truncated archive\n", lzply_progname);
|
||||
free(h.path);
|
||||
@@ -1177,7 +1194,7 @@ static int cmd_extract(const char *archive, const char *dest_arg,
|
||||
int dr = entry_decode(stored, (size_t)h.stored_size, h.level,
|
||||
is_bch, poly_id,
|
||||
h.sha, (size_t)h.blob_size,
|
||||
&raw, &raw_len, &corrected);
|
||||
&raw, &raw_len, &corrected, h.crc16);
|
||||
free(stored);
|
||||
if (dr != 0) {
|
||||
fprintf(stderr, "%s: %s: corrupt or unrecoverable data\n",
|
||||
@@ -1263,9 +1280,9 @@ static int cmd_inspect(const char *archive, const char **selectors,
|
||||
uint32_t seen = 0, ndirs = 0, nfiles = 0;
|
||||
if (rc != 0)
|
||||
return rc;
|
||||
printf("%-40s %-10s %-4s %-11s %-20s %12s %12s %3s %-8s\n",
|
||||
printf("%-40s %-10s %-4s %-11s %-20s %12s %12s %3s %-8s %6s\n",
|
||||
"path", "type", "perm", "symbolic", "mtime (UTC)",
|
||||
"original", "stored", "lvl", "ecc");
|
||||
"original", "stored", "lvl", "ecc", "crc16");
|
||||
for (;;) {
|
||||
ehdr_t h;
|
||||
int r = read_entry_header(f, &h);
|
||||
@@ -1298,13 +1315,13 @@ static int cmd_inspect(const char *archive, const char **selectors,
|
||||
(unsigned)(h.rs_level | ((unsigned)h.reserved << 8)));
|
||||
else
|
||||
snprintf(ecc, sizeof ecc, "-");
|
||||
printf("%-40s %-10s %04o %-11s %-20s %12s %12s %3u %-8s\n",
|
||||
printf("%-40s %-10s %04o %-11s %-20s %12s %12s %3u %-8s %04x\n",
|
||||
h.path, is_dir ? "directory" : "file",
|
||||
(unsigned)(h.mode & 07777), perm, mt,
|
||||
human_size(h.orig_size, b1, sizeof b1),
|
||||
human_size(h.stored_size, b2, sizeof b2),
|
||||
(unsigned)h.level,
|
||||
ecc);
|
||||
ecc, (unsigned)h.crc16);
|
||||
if (fseeko(f, (off_t)h.stored_size, SEEK_CUR) != 0) {
|
||||
fprintf(stderr, "%s: truncated archive\n", lzply_progname);
|
||||
free(h.path);
|
||||
@@ -1556,7 +1573,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 [options] <input> [output] [selectors...]\n"
|
||||
"Usage: %s -c|-d|-l|-t|-a|-i|-tr|-r [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"
|
||||
@@ -1579,6 +1596,15 @@ 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"
|
||||
@@ -1633,16 +1659,18 @@ 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_APPEND, MODE_INSPECT, MODE_TREE, MODE_REPAIR };
|
||||
|
||||
/* 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
|
||||
@@ -1681,6 +1709,11 @@ 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;
|
||||
@@ -1729,6 +1762,64 @@ 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) {
|
||||
@@ -1916,6 +2007,22 @@ 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;
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
/* lzply_deep_repair.c - repair entries past the BCH limit t.
|
||||
*
|
||||
* Usage:
|
||||
* lzply_deep_repair [-l max-level] [--time-budget seconds] [-v]
|
||||
* [-o outdir] [--entry name] archive
|
||||
*
|
||||
* Reads an LZPL v5 or LZRS v1 archive and attempts, per entry, the
|
||||
* escalating repair ladder from deep_repair.h (L0 standard decode
|
||||
* to t, L1 Chase-1 flips, L2 Chase-2 flips, L3 cross-block list
|
||||
* decoding), with the entry's CRC16 as the fast oracle and SHA-256
|
||||
* as the final oracle. Recovered entries are written under outdir
|
||||
* (default ./repaired), preserving their stored paths. Nothing is
|
||||
* ever written unless it passes both oracles.
|
||||
*
|
||||
* Per entry it reports the level the repair landed at and the
|
||||
* per-level timing -- the "time of arrival": how long each level
|
||||
* took, how many candidates were tried, how many the CRC rejected,
|
||||
* 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 <getopt.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "deep_repair.h"
|
||||
#include "lzply_lib.h"
|
||||
#include "repair_cmd.h"
|
||||
|
||||
static const char *prog = "lzply_deep_repair";
|
||||
|
||||
static void usage(void)
|
||||
{
|
||||
fprintf(stderr,
|
||||
"Usage: %s [-l max-level 0..3] [--time-budget seconds] [-v]\n"
|
||||
" [-o outdir] [--entry name] archive\n"
|
||||
" -l N highest repair level to attempt (default 3)\n"
|
||||
" --time-budget S wall-clock budget per entry, seconds (default %.0f)\n"
|
||||
" -v verbose: per-level trial counts\n"
|
||||
" -o DIR output directory for recovered files (default ./repaired)\n"
|
||||
" --entry NAME repair only the entry with this stored path\n"
|
||||
"Levels: L0 standard decode to t, L1 Chase-1 flips,\n"
|
||||
"L2 Chase-2 flips, L3 cross-block list decoding.\n",
|
||||
prog, DEEP_DEFAULT_BUDGET_SEC);
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
int max_level = DEEP_MAX_LEVEL;
|
||||
double budget = DEEP_DEFAULT_BUDGET_SEC;
|
||||
int verbose = 0;
|
||||
const char *outdir = "./repaired";
|
||||
const char *only_entry = NULL;
|
||||
const char *archive = NULL;
|
||||
int opt;
|
||||
static struct option long_opts[] = {
|
||||
{ "time-budget", required_argument, NULL, 1000 },
|
||||
{ "entry", required_argument, NULL, 1001 },
|
||||
{ "help", no_argument, NULL, 'h' },
|
||||
{ NULL, 0, NULL, 0 }
|
||||
};
|
||||
|
||||
lzply_set_progname(prog);
|
||||
while ((opt = getopt_long(argc, argv, "l:vo:h", long_opts, NULL)) != -1) {
|
||||
switch (opt) {
|
||||
case 'l':
|
||||
max_level = atoi(optarg);
|
||||
if (max_level < 0 || max_level > DEEP_MAX_LEVEL) {
|
||||
fprintf(stderr, "%s: level must be 0..%d\n",
|
||||
prog, DEEP_MAX_LEVEL);
|
||||
return EXIT_USAGE;
|
||||
}
|
||||
break;
|
||||
case 'v':
|
||||
verbose = 1;
|
||||
break;
|
||||
case 'o':
|
||||
outdir = optarg;
|
||||
break;
|
||||
case 1000:
|
||||
budget = atof(optarg);
|
||||
if (budget <= 0) {
|
||||
fprintf(stderr, "%s: --time-budget must be > 0\n", prog);
|
||||
return EXIT_USAGE;
|
||||
}
|
||||
break;
|
||||
case 1001:
|
||||
only_entry = optarg;
|
||||
break;
|
||||
case 'h':
|
||||
usage();
|
||||
return 0;
|
||||
default:
|
||||
usage();
|
||||
return EXIT_USAGE;
|
||||
}
|
||||
}
|
||||
if (optind + 1 != argc) {
|
||||
usage();
|
||||
return EXIT_USAGE;
|
||||
}
|
||||
archive = argv[optind];
|
||||
|
||||
return repair_archive(prog, archive, outdir, max_level, budget,
|
||||
only_entry, verbose);
|
||||
}
|
||||
+168
-51
@@ -8,19 +8,20 @@
|
||||
* format. (v3 archives are rejected outright; the format changed
|
||||
* in v4.)
|
||||
*
|
||||
* Archive format v4 (all integers little-endian):
|
||||
* Archive format v5 (all integers little-endian):
|
||||
* global header (16 bytes):
|
||||
* magic "LZPL", version u8 (=4), flags u8, entry_count u32,
|
||||
* magic "LZPL", version u8 (=5), flags u8, entry_count u32,
|
||||
* reserved u64
|
||||
* entries, each:
|
||||
* 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,
|
||||
* u32 mode, u64 mtime, u16 crc16, u32 header_crc32,
|
||||
* path[path_len], data[stored_size]
|
||||
* (header_crc32 covers the 74 bytes before it; blob_size is the
|
||||
* (header_crc32 covers the 76 bytes before it; blob_size is the
|
||||
* length of the compressed stream before error-correction parity
|
||||
* was added; mtime is the source file's modification time,
|
||||
* seconds since the epoch, UTC)
|
||||
* seconds since the epoch, UTC; crc16 is CRC-16/CCITT-FALSE of
|
||||
* the blob)
|
||||
* end marker: u16 path_len == 0
|
||||
* Flags: bit 0 is unused (it was used by v3), bit 1 =
|
||||
* directory, bit 2 = BCH mode.
|
||||
@@ -163,6 +164,39 @@ uint32_t crc32_of(const uint8_t *p, size_t n){
|
||||
return c ^ 0xFFFFFFFFu;
|
||||
}
|
||||
|
||||
/* CRC-16/CCITT-FALSE (polynomial 0x1021, init 0xFFFF, refin=false,
|
||||
* refout=false, xorout 0x0000). Check value: crc16_of("123456789")
|
||||
* == 0x29B1; crc16_of(NULL, 0) == 0xFFFF. Table-driven, same shape
|
||||
* as the CRC-32 above. */
|
||||
static uint16_t crc16_table[256];
|
||||
|
||||
static int crc16_ready = 0;
|
||||
|
||||
void crc16_init(void)
|
||||
{
|
||||
uint16_t i;
|
||||
int j;
|
||||
for (i = 0; i < 256; i++) {
|
||||
uint16_t c = (uint16_t)(i << 8);
|
||||
for (j = 0; j < 8; j++)
|
||||
c = (c & 0x8000u) ? (uint16_t)((c << 1) ^ 0x1021u)
|
||||
: (uint16_t)(c << 1);
|
||||
crc16_table[i] = c;
|
||||
}
|
||||
crc16_ready = 1;
|
||||
}
|
||||
|
||||
uint16_t crc16_of(const uint8_t *p, size_t n){
|
||||
uint16_t c = 0xFFFFu;
|
||||
size_t i;
|
||||
if (!crc16_ready)
|
||||
crc16_init();
|
||||
for (i = 0; i < n; i++)
|
||||
c = (uint16_t)((c << 8) ^
|
||||
crc16_table[((c >> 8) ^ p[i]) & 0xff]);
|
||||
return c;
|
||||
}
|
||||
|
||||
/* Dictionary size / match-length limit per level, matching the lzip
|
||||
* command-line tool's own table (verified by comparing output with
|
||||
* `lzip -N` on the same input). */
|
||||
@@ -331,7 +365,7 @@ int entry_encode(const uint8_t *raw, size_t raw_len, int level,
|
||||
uint8_t **stored, size_t *stored_len,
|
||||
size_t *blob_len_out, uint16_t *poly_id_out,
|
||||
int *is_bch_out, int *level_out,
|
||||
uint8_t sha_out[32])
|
||||
uint8_t sha_out[32], uint16_t *crc16_out)
|
||||
{
|
||||
uint8_t *comp = NULL, *blob = NULL, *ecout = NULL;
|
||||
size_t comp_len = 0, blob_len = 0, ec_len = 0;
|
||||
@@ -377,6 +411,12 @@ int entry_encode(const uint8_t *raw, size_t raw_len, int level,
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
/* The CRC16 covers the blob (the pre-ECC stream). Compute it now:
|
||||
* the blob is freed inside the BCH branch below (or handed to the
|
||||
* caller as the stored bytes when there is no BCH layer), so this
|
||||
* is the last point where it is uniformly available. */
|
||||
if (crc16_out)
|
||||
*crc16_out = crc16_of(blob, blob_len);
|
||||
if (poly) {
|
||||
ec_len = bch_encoded_len(blob_len, poly);
|
||||
ecout = xmalloc(ec_len ? ec_len : 1);
|
||||
@@ -428,35 +468,72 @@ static uint8_t *blob_to_raw_checked(const uint8_t *blob, size_t blob_len,
|
||||
|
||||
/* Entry decode: stored bytes -> raw file bytes.
|
||||
* Return values: 0 ok, -1 corrupt (BCH uncorrectable, lzip error,
|
||||
* SHA-256 mismatch). `corrected` receives the number of bit errors
|
||||
* corrected (BCH). `is_bch` / `poly_id` come from the entry header;
|
||||
* a non-BCH entry has no error correction. A level-0 entry is stored
|
||||
* uncompressed: the blob is copied verbatim, no lzip decode.
|
||||
* CRC16 mismatch, SHA-256 mismatch). `corrected` receives the number
|
||||
* of bit errors corrected (BCH). `is_bch` / `poly_id` come from the
|
||||
* entry header; a non-BCH entry has no error correction. A level-0
|
||||
* entry is stored uncompressed: the blob is copied verbatim, no
|
||||
* lzip decode.
|
||||
*
|
||||
* CRC16 gate: the decoded blob is checked against want_crc16 (the
|
||||
* entry header's CRC16) BEFORE decompression, in every path. A
|
||||
* mismatch is a clean failure, never a misdecode, and a specific
|
||||
* message is printed (stored 0000 means the archive predates the
|
||||
* CRC16 migration, or the data is corrupt).
|
||||
*
|
||||
* Two-pass silent repair (BCH entries only):
|
||||
* Pass 1 (fast path, unchanged): standard BCH decode, then
|
||||
* decompress + SHA-256. If the hash passes, return immediately.
|
||||
* No extra cost in the common case.
|
||||
* Pass 2 (recovery, only when pass 1 fails): the hash failure means
|
||||
* the decoder miscorrected or could not correct. Try alternative
|
||||
* BCH decodings (bch_decode_candidates) and accept the FIRST
|
||||
* candidate whose decompressed output hashes correctly. If none
|
||||
* passes, return -1 (loud failure). No data is ever returned unless
|
||||
* it passes the SHA-256 check, in either pass -- a silent failure
|
||||
* (wrong data returned as if correct) is impossible by construction.
|
||||
* Pass 1 (fast path, unchanged): standard BCH decode, then CRC,
|
||||
* decompress + SHA-256. If all pass, return immediately. No extra
|
||||
* cost in the common case.
|
||||
* Pass 2 (recovery, only when pass 1 fails): the CRC/hash failure
|
||||
* means the decoder miscorrected or could not correct. Try
|
||||
* alternative BCH decodings (bch_decode_candidates); each
|
||||
* candidate is CRC-checked first (cheap: no decompression) and
|
||||
* only CRC-passing candidates go to decompress + SHA-256. Accept
|
||||
* the FIRST candidate whose decompressed output hashes correctly.
|
||||
* If none passes, return -1 (loud failure). No data is ever
|
||||
* returned unless it passes the CRC16 and SHA-256 checks, in
|
||||
* either pass -- a silent failure (wrong data returned as if
|
||||
* correct) is impossible by construction.
|
||||
*/
|
||||
|
||||
/* Print the specific CRC16 failure message once decoding has
|
||||
* definitively failed. Stored 0000 is the pre-migration marker
|
||||
* (writers before the CRC16 migration stored 0), so say so; any
|
||||
* other mismatch is corruption. Called once per failed entry, not
|
||||
* once per candidate. */
|
||||
static void crc_fail_report(uint16_t want, uint16_t got)
|
||||
{
|
||||
if (want == 0)
|
||||
fprintf(stderr, "%s: entry CRC16 is 0000 but the decoded blob "
|
||||
"computes to %04x: this archive predates the CRC16 "
|
||||
"migration, or the data is corrupt; re-create it\n",
|
||||
lzply_progname, (unsigned)got);
|
||||
else
|
||||
fprintf(stderr, "%s: entry CRC16 mismatch (stored %04x, "
|
||||
"computed %04x): data corrupt\n",
|
||||
lzply_progname, (unsigned)want, (unsigned)got);
|
||||
}
|
||||
|
||||
int entry_decode(const uint8_t *stored, size_t stored_len, int level,
|
||||
int is_bch, uint16_t poly_id,
|
||||
const uint8_t want_sha[32], size_t blob_size,
|
||||
uint8_t **raw, size_t *raw_len, int *corrected)
|
||||
uint8_t **raw, size_t *raw_len, int *corrected,
|
||||
uint16_t want_crc16)
|
||||
{
|
||||
*corrected = 0;
|
||||
*raw = NULL;
|
||||
*raw_len = 0;
|
||||
if (!is_bch) {
|
||||
/* No error correction: the stored data is the blob itself. */
|
||||
/* No error correction: the stored data is the blob itself.
|
||||
* CRC-check it before decompressing anything. */
|
||||
uint16_t got;
|
||||
if (stored_len != blob_size)
|
||||
return -1;
|
||||
got = crc16_of(stored, stored_len);
|
||||
if (got != want_crc16) {
|
||||
crc_fail_report(want_crc16, got);
|
||||
return -1;
|
||||
}
|
||||
size_t out_len = 0;
|
||||
uint8_t *out = blob_to_raw_checked(stored, stored_len, level,
|
||||
want_sha, &out_len);
|
||||
@@ -471,22 +548,32 @@ int entry_decode(const uint8_t *stored, size_t stored_len, int level,
|
||||
return -1;
|
||||
uint8_t *blob = xmalloc(blob_size ? blob_size : 1);
|
||||
int corr = 0;
|
||||
/* Pass 1: standard BCH decode, then decompress + hash. */
|
||||
/* Set when any CRC comparison ran, with the last computed value,
|
||||
* so the failure message can name the computed CRC. */
|
||||
int crc_checked = 0;
|
||||
uint16_t last_computed = 0;
|
||||
/* Pass 1: standard BCH decode, then CRC + decompress + hash. */
|
||||
if (bch_decode(stored, stored_len, blob_size, poly, blob, &corr) == 0) {
|
||||
*corrected = corr;
|
||||
size_t out_len = 0;
|
||||
uint8_t *out = blob_to_raw_checked(blob, blob_size, level,
|
||||
want_sha, &out_len);
|
||||
if (out) {
|
||||
*raw = out;
|
||||
*raw_len = out_len;
|
||||
free(blob);
|
||||
return 0;
|
||||
last_computed = crc16_of(blob, blob_size);
|
||||
crc_checked = 1;
|
||||
if (last_computed == want_crc16) {
|
||||
size_t out_len = 0;
|
||||
uint8_t *out = blob_to_raw_checked(blob, blob_size, level,
|
||||
want_sha, &out_len);
|
||||
if (out) {
|
||||
*raw = out;
|
||||
*raw_len = out_len;
|
||||
free(blob);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
/* Pass-1 blob failed decompress/hash: fall through to pass 2. */
|
||||
/* Pass-1 blob failed CRC / decompress / hash: fall through
|
||||
* to pass 2. */
|
||||
}
|
||||
/* Pass 2: try alternative BCH decodings; accept the first whose
|
||||
* decompressed output hashes correctly. */
|
||||
/* Pass 2: try alternative BCH decodings; CRC-check each candidate
|
||||
* first (cheap) and accept the first whose decompressed output
|
||||
* hashes correctly. */
|
||||
{
|
||||
size_t candsize = blob_size ? blob_size : 1;
|
||||
uint8_t *cands = malloc((size_t)BCH_PASS2_MAX_CANDS * candsize);
|
||||
@@ -497,10 +584,15 @@ int entry_decode(const uint8_t *stored, size_t stored_len, int level,
|
||||
int nc = bch_decode_candidates(stored, stored_len, blob_size, poly,
|
||||
cands, BCH_PASS2_MAX_CANDS);
|
||||
for (int i = 0; i < nc; i++) {
|
||||
const uint8_t *cand = cands + (size_t)i * candsize;
|
||||
size_t out_len = 0;
|
||||
uint8_t *out = blob_to_raw_checked(cands + (size_t)i * candsize,
|
||||
blob_size, level,
|
||||
want_sha, &out_len);
|
||||
uint8_t *out;
|
||||
last_computed = crc16_of(cand, blob_size);
|
||||
crc_checked = 1;
|
||||
if (last_computed != want_crc16)
|
||||
continue; /* CRC rejects this candidate: cheap */
|
||||
out = blob_to_raw_checked(cand, blob_size, level,
|
||||
want_sha, &out_len);
|
||||
if (out) {
|
||||
*raw = out;
|
||||
*raw_len = out_len;
|
||||
@@ -512,6 +604,8 @@ int entry_decode(const uint8_t *stored, size_t stored_len, int level,
|
||||
free(cands);
|
||||
}
|
||||
free(blob);
|
||||
if (crc_checked)
|
||||
crc_fail_report(want_crc16, last_computed);
|
||||
return -1;
|
||||
}
|
||||
|
||||
@@ -532,7 +626,8 @@ char *parent_dir(const char *path){
|
||||
|
||||
/* rs_level + reserved: for a BCH entry (flags & FLAG_BCH) this is the
|
||||
* poly id, poly_id = rs_level | (reserved << 8). For an entry with
|
||||
* no error correction both are 0. */
|
||||
* no error correction both are 0. crc16 is CRC-16/CCITT-FALSE of the
|
||||
* blob (0xFFFF for a directory entry, whose blob is empty). */
|
||||
|
||||
int write_entry_header(FILE *f, const ehdr_t *h){
|
||||
uint8_t buf[LZPLY_EHDR_SIZE];
|
||||
@@ -551,7 +646,8 @@ int write_entry_header(FILE *f, const ehdr_t *h){
|
||||
memcpy(buf + 30, h->sha, 32);
|
||||
put32le(buf + 62, h->mode);
|
||||
put64le(buf + 66, h->mtime);
|
||||
put32le(buf + 74, crc32_of(buf, 74));
|
||||
put16le(buf + 74, h->crc16);
|
||||
put32le(buf + 76, crc32_of(buf, 76));
|
||||
if (fwrite(buf, 1, sizeof buf, f) != sizeof buf)
|
||||
return -1;
|
||||
if (plen > 0 && fwrite(h->path, 1, plen, f) != plen)
|
||||
@@ -572,10 +668,10 @@ int read_entry_header(FILE *f, ehdr_t *h){
|
||||
return 1;
|
||||
if (fread(buf + 2, 1, LZPLY_EHDR_SIZE - 2, f) != LZPLY_EHDR_SIZE - 2)
|
||||
return -1;
|
||||
want_crc = get32le(buf + 74);
|
||||
put32le(buf + 74, 0);
|
||||
got_crc = crc32_of(buf, 74);
|
||||
put32le(buf + 74, want_crc);
|
||||
want_crc = get32le(buf + 76);
|
||||
put32le(buf + 76, 0);
|
||||
got_crc = crc32_of(buf, 76);
|
||||
put32le(buf + 76, want_crc);
|
||||
if (got_crc != want_crc)
|
||||
return -1;
|
||||
h->level = buf[2];
|
||||
@@ -588,6 +684,7 @@ int read_entry_header(FILE *f, ehdr_t *h){
|
||||
memcpy(h->sha, buf + 30, 32);
|
||||
h->mode = get32le(buf + 62);
|
||||
h->mtime = get64le(buf + 66);
|
||||
h->crc16 = get16le(buf + 74);
|
||||
if (h->level > 9)
|
||||
return -1;
|
||||
if (h->flags & FLAG_BCH) {
|
||||
@@ -619,8 +716,10 @@ int read_global_header(FILE *f, uint32_t *count_out){
|
||||
uint8_t buf[LZPLY_HDR_SIZE];
|
||||
if (fread(buf, 1, sizeof buf, f) != sizeof buf)
|
||||
return -1;
|
||||
if (memcmp(buf, LZPLY_MAGIC, 4) != 0 || buf[4] != LZPLY_VERSION)
|
||||
if (memcmp(buf, LZPLY_MAGIC, 4) != 0)
|
||||
return -1;
|
||||
if (buf[4] != LZPLY_VERSION)
|
||||
return -2; /* right magic, wrong version (e.g. v4) */
|
||||
*count_out = get32le(buf + 6);
|
||||
return 0;
|
||||
}
|
||||
@@ -796,15 +895,20 @@ void scan_list_free(scan_list_t *l){
|
||||
}
|
||||
|
||||
/* Read the 16-byte global header, returning version and count.
|
||||
* Returns 0 on success, -1 if the file is not an lzply archive. */
|
||||
* Returns 0 on success, -1 if the file is not an lzply archive,
|
||||
* -2 if the magic is right but the version is wrong. On -2
|
||||
* *version_out still holds the version byte found, so the caller
|
||||
* can name it. */
|
||||
int read_global_header_full(FILE *f, int *version_out, uint32_t *count_out)
|
||||
{
|
||||
uint8_t buf[LZPLY_HDR_SIZE];
|
||||
if (fread(buf, 1, sizeof buf, f) != sizeof buf)
|
||||
return -1;
|
||||
if (memcmp(buf, LZPLY_MAGIC, 4) != 0 || buf[4] != LZPLY_VERSION)
|
||||
if (memcmp(buf, LZPLY_MAGIC, 4) != 0)
|
||||
return -1;
|
||||
*version_out = buf[4];
|
||||
if (buf[4] != LZPLY_VERSION)
|
||||
return -2;
|
||||
*count_out = get32le(buf + 6);
|
||||
return 0;
|
||||
}
|
||||
@@ -832,11 +936,24 @@ int scan_archive(const char *path, int *version_out, uint
|
||||
fclose(f);
|
||||
return -1;
|
||||
}
|
||||
if (read_global_header_full(f, version_out, count_out) != 0) {
|
||||
fprintf(stderr, "%s: %s is not an lzply archive (bad magic/version)\n",
|
||||
lzply_progname, path);
|
||||
fclose(f);
|
||||
return -1;
|
||||
{
|
||||
int ghr = read_global_header_full(f, version_out, count_out);
|
||||
if (ghr != 0) {
|
||||
if (ghr == -2 && *version_out == 4)
|
||||
fprintf(stderr, "%s: %s is an LZPL v4 archive, which "
|
||||
"predates the CRC16 migration (v5); re-create it "
|
||||
"with lzply -c -- it cannot be read by this version\n",
|
||||
lzply_progname, path);
|
||||
else if (ghr == -2)
|
||||
fprintf(stderr, "%s: %s is an LZPL archive of unsupported "
|
||||
"version %d (this version reads v%d only)\n",
|
||||
lzply_progname, path, *version_out, LZPLY_VERSION);
|
||||
else
|
||||
fprintf(stderr, "%s: %s is not an lzply archive (bad magic/version)\n",
|
||||
lzply_progname, path);
|
||||
fclose(f);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
memset(entries, 0, sizeof *entries);
|
||||
for (;;) {
|
||||
|
||||
+66
-27
@@ -1,26 +1,28 @@
|
||||
/* lzply_lib.h - shared core of the lzply archiver and lzply_mount.
|
||||
*
|
||||
* Everything both programs need: the v4 archive format, the per-entry
|
||||
* Everything both programs need: the v5 archive format, the per-entry
|
||||
* pipeline (lzip compress -> BCH encode, and the reverse), the header
|
||||
* I/O, the archive scan, and the date / selector filters. The
|
||||
* command-line tool (lzply.c) and the FUSE filesystem (lzply_mount.c)
|
||||
* both link lzply_lib.c. There is no legacy support: v4 is the only
|
||||
* format. (v3 archives are rejected outright; the format changed
|
||||
* in v4.)
|
||||
* both link lzply_lib.c. There is no legacy support: v5 is the only
|
||||
* format. (v4 archives are rejected outright with a message telling
|
||||
* the user to re-create them; the format changed in v5 to add the
|
||||
* per-entry CRC16.)
|
||||
*
|
||||
* Archive format v4 (all integers little-endian):
|
||||
* Archive format v5 (all integers little-endian):
|
||||
* global header (16 bytes):
|
||||
* magic "LZPL", version u8 (=4), flags u8, entry_count u32,
|
||||
* magic "LZPL", version u8 (=5), flags u8, entry_count u32,
|
||||
* reserved u64
|
||||
* entries, each:
|
||||
* 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,
|
||||
* u32 mode, u64 mtime, u16 crc16, u32 header_crc32,
|
||||
* path[path_len], data[stored_size]
|
||||
* (header_crc32 covers the 74 bytes before it; blob_size is the
|
||||
* (header_crc32 covers the 76 bytes before it; blob_size is the
|
||||
* length of the compressed stream before error-correction parity
|
||||
* was added; mtime is the source file's modification time,
|
||||
* seconds since the epoch, UTC)
|
||||
* seconds since the epoch, UTC; crc16 is CRC-16/CCITT-FALSE of
|
||||
* the blob -- see below)
|
||||
* end marker: u16 path_len == 0
|
||||
* Level is the lzip level (1..9) of the blob, or 0 for a stored
|
||||
* (uncompressed) entry: when the compressed blob would be no smaller
|
||||
@@ -30,6 +32,21 @@
|
||||
* Flags: bit 0 is unused (it was used by v3), bit 1 =
|
||||
* directory, bit 2 = BCH mode. Bit 0 is deliberately not renumbered.
|
||||
* For a BCH entry, poly_id = rs_level | (reserved << 8).
|
||||
*
|
||||
* CRC16 (v5; also LZRS v1, which has the same field): crc16 is
|
||||
* CRC-16/CCITT-FALSE (poly 0x1021, init 0xFFFF, no reflection,
|
||||
* xorout 0; check value crc16_of("123456789") == 0x29B1) of the
|
||||
* blob -- the compressed stream before BCH/RS parity was added
|
||||
* (for a stored entry the blob is the raw bytes; for a directory
|
||||
* entry the blob is empty, so crc16 == 0xFFFF). Writers compute and
|
||||
* store it; readers verify it after error-correction decoding and
|
||||
* before decompression. A mismatch is a clean failure, never a
|
||||
* misdecode: the SHA-256 check remains the final oracle. The CRC16
|
||||
* is also the fast oracle for deep repair (docs/deep-repair.md):
|
||||
* candidate blobs are CRC-checked before the expensive
|
||||
* decompress + SHA-256 step, so most wrong candidates are rejected
|
||||
* cheaply. Expected residual false-accept is ~2^-16 per candidate
|
||||
* at the CRC stage (the SHA-256 stage then gates acceptance).
|
||||
*/
|
||||
#ifndef LZPLY_LIB_H
|
||||
#define LZPLY_LIB_H
|
||||
@@ -42,9 +59,9 @@
|
||||
#include "sha256.h"
|
||||
|
||||
#define LZPLY_MAGIC "LZPL"
|
||||
#define LZPLY_VERSION 4 /* the only format version */
|
||||
#define LZPLY_VERSION 5 /* the only format version */
|
||||
#define LZPLY_HDR_SIZE 16
|
||||
#define LZPLY_EHDR_SIZE 78
|
||||
#define LZPLY_EHDR_SIZE 80
|
||||
#define LZPLY_END_MARKER 0
|
||||
|
||||
#define FLAG_ISDIR 0x02
|
||||
@@ -90,6 +107,13 @@ uint64_t get64le(const uint8_t *p);
|
||||
void crc32_init(void);
|
||||
uint32_t crc32_of(const uint8_t *p, size_t n);
|
||||
|
||||
/* CRC-16/CCITT-FALSE (polynomial 0x1021, init 0xFFFF, no reflection,
|
||||
* xorout 0x0000). Check value: crc16_of("123456789", 9) == 0x29B1;
|
||||
* crc16_of(NULL, 0) == 0xFFFF (the value stored for directory
|
||||
* entries, whose blob is empty). */
|
||||
void crc16_init(void);
|
||||
uint16_t crc16_of(const uint8_t *p, size_t n);
|
||||
|
||||
/* Parent directory of path (everything before the last '/'; "." if
|
||||
* none). */
|
||||
char *parent_dir(const char *path);
|
||||
@@ -115,30 +139,39 @@ typedef struct {
|
||||
} ecc_opt_t;
|
||||
|
||||
/* Entry encode: raw file bytes -> stored bytes.
|
||||
* Fills sha_out with SHA-256 of the raw bytes. *poly_id_out /
|
||||
* *is_bch_out describe the error correction actually used, for the
|
||||
* entry header. *level_out is the level actually stored: the
|
||||
* requested level, or 0 when the entry is stored uncompressed
|
||||
* (level 0 requested, or the compressed blob was no smaller than
|
||||
* the original). BCH applies to the stored blob either way.
|
||||
* Fills sha_out with SHA-256 of the raw bytes, and (when crc16_out
|
||||
* is non-NULL) *crc16_out with CRC-16/CCITT-FALSE of the blob (the
|
||||
* compressed stream before BCH parity; for a stored entry, the raw
|
||||
* bytes). *poly_id_out / *is_bch_out describe the error correction
|
||||
* actually used, for the entry header. *level_out is the level
|
||||
* actually stored: the requested level, or 0 when the entry is
|
||||
* stored uncompressed (level 0 requested, or the compressed blob
|
||||
* was no smaller than the original). BCH applies to the stored blob
|
||||
* either way.
|
||||
* Returns 0 on success. */
|
||||
int entry_encode(const uint8_t *raw, size_t raw_len, int level,
|
||||
const ecc_opt_t *ecc,
|
||||
uint8_t **stored, size_t *stored_len,
|
||||
size_t *blob_len_out, uint16_t *poly_id_out,
|
||||
int *is_bch_out, int *level_out,
|
||||
uint8_t sha_out[32]);
|
||||
uint8_t sha_out[32], uint16_t *crc16_out);
|
||||
|
||||
/* Entry decode: stored bytes -> raw file bytes.
|
||||
* Return values: 0 ok, -1 corrupt (BCH uncorrectable, lzip error,
|
||||
* SHA-256 mismatch). `corrected` receives the number of bit errors
|
||||
* corrected (BCH). `is_bch` / `poly_id` come from the entry header;
|
||||
* a non-BCH entry has no error correction. A level-0 entry is stored
|
||||
* uncompressed: the blob is copied verbatim, no lzip decode. */
|
||||
* CRC16 mismatch, SHA-256 mismatch). `corrected` receives the number
|
||||
* of bit errors corrected (BCH). `is_bch` / `poly_id` come from the
|
||||
* entry header; a non-BCH entry has no error correction. A level-0
|
||||
* entry is stored uncompressed: the blob is copied verbatim, no
|
||||
* lzip decode. `want_crc16` is the CRC16 from the entry header: the
|
||||
* decoded blob is CRC-checked against it before decompression, so
|
||||
* a blob that fails the CRC is never decompressed or returned. A
|
||||
* mismatch prints a specific message (stored 0000 means the archive
|
||||
* predates the CRC16 migration, or the data is corrupt). */
|
||||
int entry_decode(const uint8_t *stored, size_t stored_len, int level,
|
||||
int is_bch, uint16_t poly_id,
|
||||
const uint8_t want_sha[32], size_t blob_size,
|
||||
uint8_t **raw, size_t *raw_len, int *corrected);
|
||||
uint8_t **raw, size_t *raw_len, int *corrected,
|
||||
uint16_t want_crc16);
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Archive header I/O */
|
||||
@@ -151,10 +184,12 @@ typedef struct {
|
||||
uint8_t sha[32];
|
||||
uint32_t mode;
|
||||
uint64_t mtime; /* source mtime, seconds since epoch (UTC) */
|
||||
uint16_t crc16; /* CRC-16/CCITT-FALSE of the blob */
|
||||
} ehdr_t;
|
||||
/* rs_level + reserved: for a BCH entry (flags & FLAG_BCH) this is the
|
||||
* poly id, poly_id = rs_level | (reserved << 8). For an entry with
|
||||
* no error correction both are 0. */
|
||||
* no error correction both are 0. crc16 covers the blob (see above);
|
||||
* for a directory entry (empty blob) it is 0xFFFF. */
|
||||
|
||||
int write_entry_header(FILE *f, const ehdr_t *h);
|
||||
/* Returns 0 = entry read, 1 = end marker, -1 = error/truncated. */
|
||||
@@ -162,7 +197,11 @@ int read_entry_header(FILE *f, ehdr_t *h);
|
||||
int read_global_header(FILE *f, uint32_t *count_out);
|
||||
void write_global_header(FILE *f, uint32_t count, int version);
|
||||
/* Read the 16-byte global header, returning version and count.
|
||||
* Returns 0 on success, -1 if the file is not an lzply archive. */
|
||||
* Returns 0 on success, -1 if the file is not an lzply archive,
|
||||
* -2 if the magic is right but the version is wrong (e.g. a v4
|
||||
* archive, which predates the CRC16 migration). On -2 *version_out
|
||||
* still holds the version byte found, so the caller can say which
|
||||
* version it was. */
|
||||
int read_global_header_full(FILE *f, int *version_out,
|
||||
uint32_t *count_out);
|
||||
|
||||
@@ -213,8 +252,8 @@ void fmt_perm(int is_dir, uint32_t mode, char *buf);
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/* One entry found by scanning an archive: its stored path, its file
|
||||
* offset (start of the 78-byte header), and its total on-disk length
|
||||
* (78 + path_len + stored_size). */
|
||||
* offset (start of the 80-byte header), and its total on-disk length
|
||||
* (80 + path_len + stored_size). */
|
||||
typedef struct {
|
||||
char *path;
|
||||
off_t offset;
|
||||
|
||||
+4
-2
@@ -411,7 +411,8 @@ static int load_content(lzply_mount_state_t *st, fs_node_t *n)
|
||||
poly_id = (uint16_t)(n->hdr.rs_level | ((uint16_t)n->hdr.reserved << 8));
|
||||
rc = entry_decode(stored, (size_t)n->hdr.stored_size, n->hdr.level,
|
||||
is_bch, poly_id, n->hdr.sha,
|
||||
(size_t)n->hdr.blob_size, &raw, &raw_len, &corrected);
|
||||
(size_t)n->hdr.blob_size, &raw, &raw_len, &corrected,
|
||||
n->hdr.crc16);
|
||||
free(stored);
|
||||
if (rc != 0)
|
||||
return -EIO; /* corrupt: BCH uncorrectable / SHA mismatch */
|
||||
@@ -538,6 +539,7 @@ static int repack_archive(lzply_mount_state_t *st)
|
||||
h.orig_size = 0;
|
||||
h.stored_size = 0;
|
||||
h.blob_size = 0;
|
||||
h.crc16 = crc16_of(NULL, 0); /* empty blob: 0xFFFF */
|
||||
lzply_sha256((const uint8_t *)"", 0, h.sha);
|
||||
entry_off = ftello(out);
|
||||
if (write_entry_header(out, &h) != 0) {
|
||||
@@ -580,7 +582,7 @@ static int repack_archive(lzply_mount_state_t *st)
|
||||
if (entry_encode(n->content, n->content_len, st->level,
|
||||
&st->ecc,
|
||||
&stored, &stored_len, &blob_len, &poly_id,
|
||||
&is_bch, &eff_level, h.sha) != 0)
|
||||
&is_bch, &eff_level, h.sha, &h.crc16) != 0)
|
||||
goto fail;
|
||||
h.level = (uint8_t)eff_level; /* 0 when stored uncompressed */
|
||||
}
|
||||
|
||||
+349
@@ -0,0 +1,349 @@
|
||||
/* lzrs_lib.c - LZRS v1 archive format and per-entry pipeline.
|
||||
*
|
||||
* The entry pipeline is lzply v4 with one more layer on the
|
||||
* outside: raw -> lzip compress (or store) -> BCH encode -> RS
|
||||
* encode. RS is the outer layer because it corrects whole-byte
|
||||
* and burst errors, which is what a damaged block looks like
|
||||
* after the inner layers have done their work; BCH stays
|
||||
* responsible for scattered bit errors. Decode runs the layers
|
||||
* in reverse (RS, then BCH with its two-pass hash-gated repair,
|
||||
* then lzip), and the SHA-256 check at the end is the oracle for
|
||||
* the whole stack: no data is returned unless it hashes.
|
||||
*
|
||||
* Format: see lzrs_lib.h. The entry header is the v5 80-byte
|
||||
* layout plus bch_poly_id before the header CRC, which covers the
|
||||
* 78 bytes before it. The BCH poly id needed its own field because
|
||||
* rs_level now means the RS level (0..4), not the low byte of the
|
||||
* poly id.
|
||||
*/
|
||||
#define _FILE_OFFSET_BITS 64
|
||||
#define _DEFAULT_SOURCE
|
||||
|
||||
#include "lzrs_lib.h"
|
||||
|
||||
#include <errno.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "bch.h"
|
||||
#include "sha256.h"
|
||||
|
||||
/* Entry encode: raw file bytes -> stored bytes.
|
||||
* Runs the lzply v4 entry_encode (lzip -> BCH), then RS-encodes
|
||||
* the result when rs_level > 0. blob_len_out is the compressed
|
||||
* stream length before BCH and RS, exactly as in v4, so a decoder
|
||||
* can reconstruct every layer length from the header alone:
|
||||
* BCH length from blob_size + poly id, RS length from the BCH
|
||||
* length + parity. Returns 0 on success. */
|
||||
int lzrs_entry_encode(const uint8_t *raw, size_t raw_len, int level,
|
||||
const ecc_opt_t *ecc, int rs_level,
|
||||
uint8_t **stored, size_t *stored_len,
|
||||
size_t *blob_len_out, uint16_t *poly_id_out,
|
||||
int *is_bch_out, int *level_out,
|
||||
uint8_t sha_out[32], uint16_t *crc16_out)
|
||||
{
|
||||
uint8_t *bch_stored = NULL, *rs_out = NULL;
|
||||
size_t bch_len = 0, blob_len = 0, rs_len = 0;
|
||||
int parity;
|
||||
if (rs_level < 0 || rs_level > 4)
|
||||
return -1;
|
||||
parity = rs_parity_for_level(rs_level);
|
||||
if (entry_encode(raw, raw_len, level, ecc,
|
||||
&bch_stored, &bch_len, &blob_len, poly_id_out,
|
||||
is_bch_out, level_out, sha_out, crc16_out) != 0)
|
||||
return -1;
|
||||
if (parity == 0) {
|
||||
*stored = bch_stored;
|
||||
*stored_len = bch_len;
|
||||
*blob_len_out = blob_len;
|
||||
return 0;
|
||||
}
|
||||
rs_len = rs_encoded_len(bch_len, parity);
|
||||
rs_out = xmalloc(rs_len ? rs_len : 1);
|
||||
if (rs_encode(bch_stored, bch_len, parity, rs_out) != rs_len) {
|
||||
free(bch_stored);
|
||||
free(rs_out);
|
||||
return -1;
|
||||
}
|
||||
free(bch_stored);
|
||||
*stored = rs_out;
|
||||
*stored_len = rs_len;
|
||||
*blob_len_out = blob_len;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Entry decode: stored bytes -> raw file bytes.
|
||||
* RS-decodes first (when rs_level > 0), then hands the result to
|
||||
* the v4 entry_decode (BCH two-pass + lzip + SHA-256). The BCH
|
||||
* length is reconstructed from blob_size + poly id, and the RS
|
||||
* length is checked against it, so a truncated or mis-sized
|
||||
* entry fails here instead of decoding garbage. Returns 0 on
|
||||
* success, -1 on any failure. */
|
||||
int lzrs_entry_decode(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,
|
||||
uint8_t **raw, size_t *raw_len,
|
||||
int *corrected_rs, int *corrected_bch,
|
||||
uint16_t want_crc16)
|
||||
{
|
||||
const bch_poly_t *poly = NULL;
|
||||
size_t bch_len;
|
||||
int parity, corr_rs = 0, corr_bch = 0, rc;
|
||||
*corrected_rs = 0;
|
||||
*corrected_bch = 0;
|
||||
*raw = NULL;
|
||||
*raw_len = 0;
|
||||
if (rs_level < 0 || rs_level > 4)
|
||||
return -1;
|
||||
parity = rs_parity_for_level(rs_level);
|
||||
if (is_bch) {
|
||||
poly = bch_poly_by_id(poly_id);
|
||||
if (!poly)
|
||||
return -1;
|
||||
bch_len = bch_encoded_len(blob_size, poly);
|
||||
} else {
|
||||
bch_len = blob_size;
|
||||
}
|
||||
if (parity == 0) {
|
||||
if (stored_len != bch_len)
|
||||
return -1;
|
||||
rc = entry_decode(stored, stored_len, level,
|
||||
is_bch, poly_id, want_sha, blob_size,
|
||||
raw, raw_len, &corr_bch, want_crc16);
|
||||
if (rc != 0)
|
||||
return -1;
|
||||
*corrected_bch = corr_bch;
|
||||
return 0;
|
||||
}
|
||||
if (stored_len != rs_encoded_len(bch_len, parity))
|
||||
return -1;
|
||||
{
|
||||
uint8_t *bch_stored = xmalloc(bch_len ? bch_len : 1);
|
||||
if (rs_decode(stored, stored_len, bch_len, parity,
|
||||
bch_stored, &corr_rs) != 0) {
|
||||
free(bch_stored);
|
||||
return -1;
|
||||
}
|
||||
rc = entry_decode(bch_stored, bch_len, level,
|
||||
is_bch, poly_id, want_sha, blob_size,
|
||||
raw, raw_len, &corr_bch, want_crc16);
|
||||
free(bch_stored);
|
||||
if (rc != 0)
|
||||
return -1;
|
||||
*corrected_rs = corr_rs;
|
||||
*corrected_bch = corr_bch;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* Entry header I/O. Layout (82 bytes, little-endian):
|
||||
* 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, u16 bch_poly_id, u16 crc16,
|
||||
* u32 header_crc32 (covers the 78 bytes before it).
|
||||
* crc16 is CRC-16/CCITT-FALSE of the blob (0xFFFF for a directory
|
||||
* entry, whose blob is empty). */
|
||||
|
||||
int lzrs_write_entry_header(FILE *f, const lzrs_ehdr_t *h)
|
||||
{
|
||||
uint8_t buf[LZRS_EHDR_SIZE];
|
||||
size_t plen = strlen(h->path);
|
||||
if (plen > 65535)
|
||||
return -1;
|
||||
memset(buf, 0, sizeof buf);
|
||||
put16le(buf + 0, (uint16_t)plen);
|
||||
buf[2] = h->level;
|
||||
buf[3] = h->rs_level;
|
||||
buf[4] = h->flags;
|
||||
buf[5] = h->reserved;
|
||||
put64le(buf + 6, h->orig_size);
|
||||
put64le(buf + 14, h->stored_size);
|
||||
put64le(buf + 22, h->blob_size);
|
||||
memcpy(buf + 30, h->sha, 32);
|
||||
put32le(buf + 62, h->mode);
|
||||
put64le(buf + 66, h->mtime);
|
||||
put16le(buf + 74, h->bch_poly_id);
|
||||
put16le(buf + 76, h->crc16);
|
||||
put32le(buf + 78, crc32_of(buf, 78));
|
||||
if (fwrite(buf, 1, sizeof buf, f) != sizeof buf)
|
||||
return -1;
|
||||
if (plen > 0 && fwrite(h->path, 1, plen, f) != plen)
|
||||
return -1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Returns 0 = entry read, 1 = end marker, -1 = error/truncated. */
|
||||
int lzrs_read_entry_header(FILE *f, lzrs_ehdr_t *h)
|
||||
{
|
||||
uint8_t buf[LZRS_EHDR_SIZE];
|
||||
uint16_t plen;
|
||||
uint32_t want_crc, got_crc;
|
||||
memset(h, 0, sizeof *h);
|
||||
if (fread(buf, 1, 2, f) != 2)
|
||||
return -1;
|
||||
plen = get16le(buf);
|
||||
if (plen == 0)
|
||||
return 1;
|
||||
if (fread(buf + 2, 1, LZRS_EHDR_SIZE - 2, f) != LZRS_EHDR_SIZE - 2)
|
||||
return -1;
|
||||
want_crc = get32le(buf + 78);
|
||||
put32le(buf + 78, 0);
|
||||
got_crc = crc32_of(buf, 78);
|
||||
put32le(buf + 78, want_crc);
|
||||
if (got_crc != want_crc)
|
||||
return -1;
|
||||
h->level = buf[2];
|
||||
h->rs_level = buf[3];
|
||||
h->flags = buf[4];
|
||||
h->reserved = buf[5];
|
||||
h->orig_size = get64le(buf + 6);
|
||||
h->stored_size = get64le(buf + 14);
|
||||
h->blob_size = get64le(buf + 22);
|
||||
memcpy(h->sha, buf + 30, 32);
|
||||
h->mode = get32le(buf + 62);
|
||||
h->mtime = get64le(buf + 66);
|
||||
h->bch_poly_id = get16le(buf + 74);
|
||||
h->crc16 = get16le(buf + 76);
|
||||
if (h->level > 9)
|
||||
return -1;
|
||||
if (h->rs_level > 4)
|
||||
return -1;
|
||||
if (h->flags & FLAG_BCH) {
|
||||
if (!bch_poly_by_id(h->bch_poly_id))
|
||||
return -1;
|
||||
} else if (h->bch_poly_id != 0) {
|
||||
return -1;
|
||||
}
|
||||
/* crc16 is the blob CRC16 (see lzrs_lib.h). It is verified at
|
||||
* decode time by entry_decode / lzrs_entry_decode, not here:
|
||||
* header-only readers (-l / -i) must work without the data. */
|
||||
h->path = xmalloc((size_t)plen + 1);
|
||||
if (fread(h->path, 1, plen, f) != plen) {
|
||||
free(h->path);
|
||||
h->path = NULL;
|
||||
return -1;
|
||||
}
|
||||
h->path[plen] = 0;
|
||||
/* Reject paths that would escape the destination directory. */
|
||||
if (h->path[0] == 0x2f /* slash, written hex: a quoted char literal cannot pass through the ssh heredoc */ || strstr(h->path, "/../") != NULL ||
|
||||
strcmp(h->path, "..") == 0 ||
|
||||
(plen >= 3 && strcmp(h->path + plen - 3, "/..") == 0)) {
|
||||
free(h->path);
|
||||
h->path = NULL;
|
||||
return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int lzrs_read_global_header(FILE *f, uint32_t *count_out)
|
||||
{
|
||||
uint8_t buf[LZRS_HDR_SIZE];
|
||||
if (fread(buf, 1, sizeof buf, f) != sizeof buf)
|
||||
return -1;
|
||||
if (memcmp(buf, LZRS_MAGIC, 4) != 0 || buf[4] != LZRS_VERSION)
|
||||
return -1;
|
||||
*count_out = get32le(buf + 6);
|
||||
return 0;
|
||||
}
|
||||
|
||||
void lzrs_write_global_header(FILE *f, uint32_t count, int version)
|
||||
{
|
||||
uint8_t buf[LZRS_HDR_SIZE];
|
||||
memset(buf, 0, sizeof buf);
|
||||
memcpy(buf, LZRS_MAGIC, 4);
|
||||
buf[4] = (uint8_t)version;
|
||||
buf[5] = 0;
|
||||
put32le(buf + 6, count);
|
||||
fwrite(buf, 1, sizeof buf, f);
|
||||
}
|
||||
|
||||
int lzrs_read_global_header_full(FILE *f, int *version_out,
|
||||
uint32_t *count_out)
|
||||
{
|
||||
uint8_t buf[LZRS_HDR_SIZE];
|
||||
if (fread(buf, 1, sizeof buf, f) != sizeof buf)
|
||||
return -1;
|
||||
if (memcmp(buf, LZRS_MAGIC, 4) != 0 || buf[4] != LZRS_VERSION)
|
||||
return -1;
|
||||
*version_out = buf[4];
|
||||
*count_out = get32le(buf + 6);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Scan an LZRS archive and record every entry. Same contract as
|
||||
* scan_archive: on success *end_off_out is the file offset of the
|
||||
* 2-byte end marker (which must be the last 2 bytes of the file).
|
||||
* Returns -1 (with a message) if the file is not a valid LZRS
|
||||
* archive, an entry header is corrupt, or there are trailing
|
||||
* bytes after the end marker. */
|
||||
int lzrs_scan_archive(const char *path, int *version_out,
|
||||
uint32_t *count_out, off_t *size_out,
|
||||
scan_list_t *entries, off_t *end_off_out)
|
||||
{
|
||||
struct stat st;
|
||||
FILE *f = fopen(path, "rb");
|
||||
off_t end_off;
|
||||
if (!f) {
|
||||
fprintf(stderr, "%s: cannot open %s: %s\n", lzply_progname, path,
|
||||
strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
if (fstat(fileno(f), &st) != 0) {
|
||||
fclose(f);
|
||||
return -1;
|
||||
}
|
||||
if (lzrs_read_global_header_full(f, version_out, count_out) != 0) {
|
||||
fprintf(stderr, "%s: %s is not an lz_rs archive (bad magic/version)\n",
|
||||
lzply_progname, path);
|
||||
fclose(f);
|
||||
return -1;
|
||||
}
|
||||
memset(entries, 0, sizeof *entries);
|
||||
for (;;) {
|
||||
off_t off = ftello(f);
|
||||
lzrs_ehdr_t h;
|
||||
int r = lzrs_read_entry_header(f, &h);
|
||||
if (r == 1) { /* end marker */
|
||||
end_off = off;
|
||||
break;
|
||||
}
|
||||
if (r < 0) {
|
||||
fprintf(stderr, "%s: %s is truncated or has a corrupt entry header\n",
|
||||
lzply_progname, path);
|
||||
scan_list_free(entries);
|
||||
fclose(f);
|
||||
return -1;
|
||||
}
|
||||
if (entries->len == entries->cap) {
|
||||
entries->cap = entries->cap ? entries->cap * 2 : 64;
|
||||
entries->v = xrealloc(entries->v,
|
||||
entries->cap * sizeof(scan_entry_t));
|
||||
}
|
||||
entries->v[entries->len].path = h.path; /* take ownership */
|
||||
entries->v[entries->len].offset = off;
|
||||
entries->v[entries->len].total_len =
|
||||
LZRS_EHDR_SIZE + (uint64_t)strlen(h.path) + h.stored_size;
|
||||
entries->v[entries->len].is_dir = (h.flags & FLAG_ISDIR) != 0;
|
||||
entries->len++;
|
||||
if (fseeko(f, (off_t)h.stored_size, SEEK_CUR) != 0) {
|
||||
fprintf(stderr, "%s: %s is truncated\n", lzply_progname, path);
|
||||
scan_list_free(entries);
|
||||
fclose(f);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
if (end_off != (off_t)st.st_size - 2 || ftello(f) != st.st_size) {
|
||||
fprintf(stderr, "%s: %s has trailing bytes after the end marker\n",
|
||||
lzply_progname, path);
|
||||
scan_list_free(entries);
|
||||
fclose(f);
|
||||
return -1;
|
||||
}
|
||||
*size_out = st.st_size;
|
||||
*end_off_out = end_off;
|
||||
fclose(f);
|
||||
return 0;
|
||||
}
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
/* lzrs_lib.h - LZRS v1 archive format and per-entry pipeline.
|
||||
*
|
||||
* lz_rs is lzply plus a Reed-Solomon layer. The pipeline per entry
|
||||
* is: raw bytes -> lzip compress (or store) -> BCH encode -> RS
|
||||
* encode. On decode the layers run in reverse: RS decode (fixes
|
||||
* whole-byte and burst errors), then BCH decode (fixes scattered
|
||||
* bit errors, two-pass, hash-gated), then lzip decompress, then a
|
||||
* SHA-256 check. No data is ever returned unless it hashes
|
||||
* correctly, exactly like lzply.
|
||||
*
|
||||
* LZRS v1 format (all integers little-endian). It is a NEW format:
|
||||
* the magic differs from lzply v4, so an old .lzply file is never
|
||||
* misread as LZRS (and lzply rejects .lzrs files). There is no
|
||||
* legacy support: v1 is the only LZRS version.
|
||||
* global header (16 bytes):
|
||||
* magic "LZRS", version u8 (=1), flags u8, entry_count u32,
|
||||
* reserved u64
|
||||
* entries, each:
|
||||
* 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, u16 bch_poly_id, u16 crc16, u32 header_crc32,
|
||||
* path[path_len], data[stored_size]
|
||||
* (header_crc32 covers the 78 bytes before it; blob_size is the
|
||||
* length of the compressed stream before BCH and RS parity was
|
||||
* added; mtime is the source file modification time, seconds
|
||||
* since the epoch, UTC; the entry header is 82 bytes; crc16 is
|
||||
* CRC-16/CCITT-FALSE of the blob -- see below)
|
||||
* end marker: u16 path_len == 0
|
||||
* Level is the lzip level (1..9) of the blob, or 0 for a stored
|
||||
* (uncompressed) entry, exactly as in lzply v5. Flags: bit 1 =
|
||||
* directory, bit 2 = BCH mode (same bits as v5).
|
||||
* rs_level is the RS level (0..4): 0 = no RS parity, 1..4 = 8, 16,
|
||||
* 24, 32 parity symbols per 255-byte block (see rs.h). bch_poly_id
|
||||
* is the BCH polynomial id (0 when the entry has no BCH layer).
|
||||
* crc16 is CRC-16/CCITT-FALSE (poly 0x1021, init 0xFFFF, no
|
||||
* reflection, xorout 0; check value crc16_of("123456789") == 0x29B1)
|
||||
* of the blob -- the compressed stream before BCH and RS parity
|
||||
* was added (for a stored entry the blob is the raw bytes; for a
|
||||
* directory entry the blob is empty, so crc16 == 0xFFFF). Writers
|
||||
* compute and store it; readers verify it after RS/BCH decoding
|
||||
* and before decompression. A mismatch is a clean failure, never a
|
||||
* misdecode; the SHA-256 check remains the final oracle. Archives
|
||||
* written before the CRC16 migration stored 0 here and are
|
||||
* rejected with a specific message (docs/lzrs-format.md).
|
||||
*/
|
||||
#ifndef LZRS_LIB_H
|
||||
#define LZRS_LIB_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
|
||||
#include "lzply_lib.h"
|
||||
#include "rs.h"
|
||||
|
||||
#define LZRS_MAGIC "LZRS"
|
||||
#define LZRS_VERSION 1 /* the only LZRS format version */
|
||||
#define LZRS_HDR_SIZE 16
|
||||
#define LZRS_EHDR_SIZE 82
|
||||
#define LZRS_END_MARKER 0
|
||||
|
||||
/* Entry header. rs_level is the RS level (0..4), not a BCH poly
|
||||
* id: the BCH poly id lives in bch_poly_id. crc16 is
|
||||
* CRC-16/CCITT-FALSE of the blob (see above). */
|
||||
typedef struct {
|
||||
char *path;
|
||||
uint8_t level, rs_level, flags, reserved;
|
||||
uint64_t orig_size, stored_size, blob_size;
|
||||
uint8_t sha[32];
|
||||
uint32_t mode;
|
||||
uint64_t mtime;
|
||||
uint16_t bch_poly_id;
|
||||
uint16_t crc16; /* CRC-16/CCITT-FALSE of the blob */
|
||||
} lzrs_ehdr_t;
|
||||
|
||||
int lzrs_write_entry_header(FILE *f, const lzrs_ehdr_t *h);
|
||||
/* Returns 0 = entry read, 1 = end marker, -1 = error/truncated. */
|
||||
int lzrs_read_entry_header(FILE *f, lzrs_ehdr_t *h);
|
||||
int lzrs_read_global_header(FILE *f, uint32_t *count_out);
|
||||
void lzrs_write_global_header(FILE *f, uint32_t count, int version);
|
||||
/* Read the 16-byte global header, returning version and count.
|
||||
* Returns 0 on success, -1 if the file is not an LZRS archive. */
|
||||
int lzrs_read_global_header_full(FILE *f, int *version_out,
|
||||
uint32_t *count_out);
|
||||
|
||||
/* Entry encode: raw file bytes -> stored bytes (lzip -> BCH -> RS).
|
||||
* Fills sha_out with SHA-256 of the raw bytes, and (when crc16_out
|
||||
* is non-NULL) *crc16_out with CRC-16/CCITT-FALSE of the blob.
|
||||
* *poly_id_out / *is_bch_out describe the BCH layer actually used,
|
||||
* for the entry header; *level_out is the level actually stored (0
|
||||
* when stored uncompressed). rs_level is the RS level (0..4).
|
||||
* Returns 0 on success. */
|
||||
int lzrs_entry_encode(const uint8_t *raw, size_t raw_len, int level,
|
||||
const ecc_opt_t *ecc, int rs_level,
|
||||
uint8_t **stored, size_t *stored_len,
|
||||
size_t *blob_len_out, uint16_t *poly_id_out,
|
||||
int *is_bch_out, int *level_out,
|
||||
uint8_t sha_out[32], uint16_t *crc16_out);
|
||||
|
||||
/* Entry decode: stored bytes -> raw file bytes (RS -> BCH -> lzip).
|
||||
* Return values: 0 ok, -1 corrupt (RS uncorrectable, BCH
|
||||
* uncorrectable, CRC16 mismatch, lzip error, SHA-256 mismatch).
|
||||
* *corrected_rs receives the number of RS symbols corrected,
|
||||
* *corrected_bch the number of BCH bits corrected. `is_bch` /
|
||||
* `poly_id` / `rs_level` come from the entry header. `want_crc16`
|
||||
* is the CRC16 from the entry header: the decoded blob is
|
||||
* CRC-checked against it before decompression (see entry_decode). */
|
||||
int lzrs_entry_decode(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,
|
||||
uint8_t **raw, size_t *raw_len,
|
||||
int *corrected_rs, int *corrected_bch,
|
||||
uint16_t want_crc16);
|
||||
|
||||
/* Scan an LZRS archive and record every entry. Same contract as
|
||||
* scan_archive (see lzply_lib.h): returns 0 on success, -1 (with
|
||||
* a message) if the file is not a valid LZRS archive, an entry
|
||||
* header is corrupt, or there are trailing bytes after the end
|
||||
* marker. */
|
||||
int lzrs_scan_archive(const char *path, int *version_out,
|
||||
uint32_t *count_out, off_t *size_out,
|
||||
scan_list_t *entries, off_t *end_off_out);
|
||||
|
||||
#endif /* LZRS_LIB_H */
|
||||
@@ -0,0 +1,43 @@
|
||||
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
|
||||
@@ -0,0 +1,138 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,259 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,438 @@
|
||||
# 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).
|
||||
@@ -0,0 +1,170 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,316 @@
|
||||
/* 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;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/* 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 */
|
||||
@@ -0,0 +1,541 @@
|
||||
// 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;
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
/* 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;
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
#!/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())
|
||||
@@ -0,0 +1,64 @@
|
||||
== 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 ==
|
||||
@@ -0,0 +1,67 @@
|
||||
{
|
||||
"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
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
{
|
||||
"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
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
{
|
||||
"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
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
{
|
||||
"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
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
{
|
||||
"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
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
{
|
||||
"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
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
{
|
||||
"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
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
{
|
||||
"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
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
{
|
||||
"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
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
{
|
||||
"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
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
/* 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;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
# 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)
|
||||
@@ -0,0 +1,451 @@
|
||||
#!/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()
|
||||
@@ -0,0 +1,22 @@
|
||||
# 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
|
||||
Executable
+30
@@ -0,0 +1,30 @@
|
||||
#!/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/
|
||||
Executable
+35
@@ -0,0 +1,35 @@
|
||||
#!/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 =="
|
||||
Executable
+15
@@ -0,0 +1,15 @@
|
||||
#!/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
|
||||
Executable
+80
@@ -0,0 +1,80 @@
|
||||
#!/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")"
|
||||
@@ -0,0 +1,85 @@
|
||||
+ 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
|
||||
@@ -0,0 +1,72 @@
|
||||
#!/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()
|
||||
@@ -0,0 +1,135 @@
|
||||
#!/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
@@ -0,0 +1,756 @@
|
||||
/* 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
File diff suppressed because it is too large.
Load diff
Loaded 100 of 403 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user