Compare commits
34
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
88d1e3b183 | ||
|
|
c6e06a0d48 | ||
|
|
cd338d4fc0 | ||
|
|
da291f0f9a | ||
|
|
a2ecebb5e6 | ||
|
|
2d98c4aad3 | ||
|
|
902d10d0e7 | ||
|
|
38edbb9ac1 | ||
|
|
5362ad35b0 | ||
|
|
2dac37b40c | ||
|
|
fe512e6df2 | ||
|
|
e00f9af438 | ||
|
|
b47d472fe3 | ||
|
|
f32323eff8 | ||
|
|
368644a392 | ||
|
|
8e40d15470 | ||
|
|
c6a13f189c | ||
|
|
fddd00c784 | ||
|
|
0f2cb105fc | ||
|
|
e53455bf07 | ||
|
|
f60ca9fd73 | ||
|
|
bf8efab2b7 | ||
|
|
1239bd9c64 | ||
|
|
2932575441 | ||
|
|
4c32b542ba | ||
|
|
c07d986cd9 | ||
|
|
0022cd76e0 | ||
|
|
40d4d996d6 | ||
|
|
acedd368df | ||
|
|
8d268167f8 | ||
|
|
5c65f3cd89 | ||
|
|
fe90ef37b2 | ||
|
|
73e333f6f3 | ||
|
|
911b3c998f |
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
|
||||
@@ -28,3 +28,10 @@ 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,6 +3,65 @@ CFLAGS = -O2 -Wall -Wextra
|
||||
LDLIBS = -llz
|
||||
PREFIX = /usr/local
|
||||
|
||||
# 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
|
||||
|
||||
# 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
|
||||
@@ -10,7 +69,7 @@ all: lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyp
|
||||
# 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,28 @@ 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).
|
||||
@@ -102,16 +212,16 @@ liblzrs.a: lzrs_lib.o rs.o
|
||||
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
|
||||
$(CC) $(CFLAGS) -o $@ lz_rs.o liblzrs.a liblzply.a $(LDLIBS)
|
||||
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
|
||||
$(CC) $(CFLAGS) -o $@ crc16_test.c liblzply.a $(LDLIBS)
|
||||
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
|
||||
@@ -119,11 +229,15 @@ crc16_test: crc16_test.c liblzply.a
|
||||
deep_repair.o: deep_repair.c deep_repair.h lzply_lib.h lzrs_lib.h bch.h rs.h sha256.h
|
||||
$(CC) $(CFLAGS) -c -o $@ deep_repair.c
|
||||
|
||||
lzply_deep_repair.o: lzply_deep_repair.c deep_repair.h lzply_lib.h lzrs_lib.h bch.h
|
||||
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 deep_repair.o liblzrs.a liblzply.a
|
||||
$(CC) $(CFLAGS) -o $@ lzply_deep_repair.o deep_repair.o liblzrs.a liblzply.a $(LDLIBS)
|
||||
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
|
||||
@@ -169,6 +283,21 @@ test: testdata bch_test rs_test crc16_test lzply lzply_mount lzply_stat lzply_he
|
||||
elif [ -x ../tests/run_hyper_tests.sh ]; then \
|
||||
../tests/run_hyper_tests.sh ./lzply_hyper; \
|
||||
else echo "run_hyper_tests.sh not found"; exit 1; fi
|
||||
if [ -x ./tests/run_integration_tests.sh ]; then \
|
||||
./tests/run_integration_tests.sh; \
|
||||
elif [ -x ../tests/run_integration_tests.sh ]; then \
|
||||
../tests/run_integration_tests.sh; \
|
||||
else echo "run_integration_tests.sh not found"; exit 1; fi
|
||||
|
||||
# Integrated experiment winners (docs/INTEGRATION.md): the ECC harness
|
||||
# (interleave d64, small-block BCH, LDPC r90) and the compression
|
||||
# prototypes (rANS core, dict transform). Not part of `all`: the archive
|
||||
# format is unchanged (LZPL v5); these are standalone tools.
|
||||
exp:
|
||||
$(MAKE) -C exp bench ldpc_diag pass2_diag
|
||||
|
||||
experiments:
|
||||
$(MAKE) -C experiments
|
||||
|
||||
install: lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyper lz_rs lzply_deep_repair
|
||||
mkdir -p $(PREFIX)/bin
|
||||
@@ -184,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 lz_rs lzply_deep_repair bch_test rs_test crc16_test *.o liblzply.a liblzrs.a
|
||||
rm -f lzply lzply_mount lzply_stat lzply_heal lzply_check lzply_refresh lzply_hyper lz_rs lzply_deep_repair bch_test rs_test crc16_test 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
|
||||
@@ -191,7 +191,8 @@ is the only LZRS format.
|
||||
|
||||
## Deep repair — past the BCH limit
|
||||
|
||||
`lzply_deep_repair` recovers entries whose bit errors exceed the
|
||||
`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):
|
||||
@@ -227,7 +228,9 @@ 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), so beyond-t repair of large blocks is bounded
|
||||
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
|
||||
@@ -236,10 +239,37 @@ 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`. Tests: `tests/run_deep_repair_tests.sh`
|
||||
`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
|
||||
@@ -438,6 +468,36 @@ Set `LZPLY_TEST_ROOT` to point the suite at a different tree root
|
||||
(default: the parent of the `tests/` directory, so it works both
|
||||
from the repo layout `~/workspace/lzply` and from `/opt/lzply/src`).
|
||||
|
||||
## Integrated experiments — interleaving, small-block BCH, LDPC, dict
|
||||
|
||||
The open-ended research branches (`experiments/baseline`,
|
||||
`experiments/ecc`, `experiments/comp`) were merged onto current main
|
||||
on `experiments/integration`. Four winners, measured numbers only,
|
||||
full write-up in `docs/INTEGRATION.md`:
|
||||
|
||||
* **Byte interleaving d64 over small-block BCH** (`exp/`): zero extra
|
||||
parity; a 256 B burst that kills uninterleaved BCH (0.00 recovery)
|
||||
is recovered 1.00. Same 5.40% overhead as the BCH underneath.
|
||||
* **Small-block BCH, 1 KiB blocks** (`exp/`): `bch1k-t32` survives
|
||||
BER 1e-3 at 1.00 where as-shipped `bch-t32` scores 0.00, at 5.40%
|
||||
overhead vs 0.12%.
|
||||
* **Regular LDPC r90** (`exp/`): 1.00 at BER 1e-3, 0.97 at 3e-3
|
||||
where `bch1k-t32` scores 0.01; 10.94% overhead, ~4x slower decode.
|
||||
* **Dictionary transform, code-only** (`experiments/`): -2.1% vs
|
||||
plain lzip -6 on code; worse everywhere else, so opt-in only.
|
||||
The rANS core is kept as supporting infrastructure.
|
||||
|
||||
Rejected with numbers (code not carried over): polar SC (0.00 at
|
||||
BER 1e-3), UEP (whole-file recovery dominated by the weak tier),
|
||||
LZ77+rANS, BWT, and PPM order-2 — none beats lzip on ratio.
|
||||
|
||||
The archive format is unchanged (LZPL v5); the winners are
|
||||
standalone tools, built with `make exp` / `make experiments` and
|
||||
smoke-tested by `tests/run_integration_tests.sh` as part of
|
||||
`make test`.
|
||||
|
||||
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
|
||||
@@ -729,5 +789,16 @@ nonlinear CRC hybrids), scored on d_min / burst length / cost
|
||||
against CRC-16, shortened BCH, and RS. Full report:
|
||||
`randfec/RANDFEC.md`. Headline: random CRC polynomials beat
|
||||
shortened BCH at n<=32 and at n=64 when searched at the target
|
||||
size; ROT/XOR, product, and nonlinear families do not. Research
|
||||
only — nothing integrated into lzply core.
|
||||
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.
|
||||
@@ -42,6 +42,41 @@
|
||||
#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 */
|
||||
/* ------------------------------------------------------------------ */
|
||||
@@ -614,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)
|
||||
@@ -643,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)
|
||||
@@ -1290,6 +1339,28 @@ static int compute_syndrome(const uint8_t *in, size_t in_len, size_t data_len,
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Public syndrome accessor, for the CUDA Chase scan (and any other
|
||||
* caller that needs S without a full decode). Same return codes as
|
||||
* compute_syndrome: 0 with S filled, 1 if the remainder is zero
|
||||
* (clean word), -1 on bad input. */
|
||||
int bch_block_syndrome(const uint8_t *in, size_t in_len, size_t data_len,
|
||||
const bch_poly_t *p, uint32_t *S)
|
||||
{
|
||||
if (!in || !p || !S)
|
||||
return -1;
|
||||
bch_ctx_t *ctx = bch_ctx_new(p);
|
||||
if (!ctx)
|
||||
return -1;
|
||||
const gf_tables_t *tab = gf_tables_for(p->m);
|
||||
if (!tab) {
|
||||
bch_ctx_free(ctx);
|
||||
return -1;
|
||||
}
|
||||
int rc = compute_syndrome(in, in_len, data_len, p, ctx, tab, S);
|
||||
bch_ctx_free(ctx);
|
||||
return rc;
|
||||
}
|
||||
|
||||
/* Column of the parity-check matrix for bit position pos:
|
||||
* col_j = alpha^(j*(nbits-1-pos)), j = 1..2t. Fills col[0..2t-1]. */
|
||||
static void col_at(size_t pos, size_t nbits, int t, const gf_tables_t *tab,
|
||||
|
||||
@@ -157,6 +157,12 @@ int bch_remainder_bruteforce(const uint8_t *data, size_t data_len,
|
||||
/* weight-(t+2) pattern. The list is what buys the rate. */
|
||||
/* ------------------------------------------------------------------ */
|
||||
|
||||
/* Syndrome S_1..S_2t of the received word (for the CUDA Chase scan).
|
||||
* Returns 0 with S filled, 1 if the remainder is zero (clean word),
|
||||
* -1 on bad input. S must hold 2*t uint32_t. */
|
||||
int bch_block_syndrome(const uint8_t *in, size_t in_len, size_t data_len,
|
||||
const bch_poly_t *p, uint32_t *S);
|
||||
|
||||
/* Maximum distinct candidate blocks returned per chase call. */
|
||||
#define BCH_CHASE_MAX_CANDS 64
|
||||
/* Maximum suspect positions considered by chase2. */
|
||||
|
||||
+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;
|
||||
}
|
||||
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;
|
||||
}
|
||||
+56
-3
@@ -23,6 +23,16 @@
|
||||
#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). */
|
||||
@@ -139,6 +149,42 @@ static void pool_free(block_pool_t *pool, size_t *pool_bytes)
|
||||
pool->dlen = 0;
|
||||
}
|
||||
|
||||
/* Chase-1 for one block: the CUDA scan when a device is present,
|
||||
* the CPU scan otherwise. Same candidate contract as
|
||||
* bch_chase1_block (suspects first, then ascending positions;
|
||||
* candidates in scan order, so the L1 direct-try order is
|
||||
* unchanged). *used_cuda is set to 1 when the GPU scan ran.
|
||||
* The GPU scan has no deadline (it runs the full scan in ~0.35 s
|
||||
* on a 524 KiB block); when the deadline is already past, the CPU
|
||||
* scan runs instead and reports partial as usual. A -2 from the
|
||||
* GPU scan (not t=8, or CUDA failed) also falls back to CPU. */
|
||||
static int chase1_block(const uint8_t *in, size_t in_len, size_t data_len,
|
||||
const bch_poly_t *p, uint8_t *cands, int max_cands,
|
||||
const size_t *suspects, int nsuspects,
|
||||
bch_chase_stats_t *stats, double deadline,
|
||||
int *used_cuda)
|
||||
{
|
||||
*used_cuda = 0;
|
||||
if (chase_cuda_available && chase_cuda_available() &&
|
||||
(deadline < 0 || bch_now() < deadline)) {
|
||||
long trials = 0, split_pass = 0, codewords = 0;
|
||||
int ncc = chase_cuda_scan1(in, in_len, data_len, p, cands,
|
||||
max_cands, suspects, nsuspects,
|
||||
&trials, &split_pass, &codewords);
|
||||
if (ncc >= 0) {
|
||||
stats->trials = trials;
|
||||
stats->split_pass = split_pass;
|
||||
stats->codewords = codewords;
|
||||
stats->candidates = ncc;
|
||||
stats->partial = 0;
|
||||
*used_cuda = 1;
|
||||
return ncc;
|
||||
}
|
||||
}
|
||||
return bch_chase1_block(in, in_len, data_len, p, cands, max_cands,
|
||||
suspects, nsuspects, stats, deadline);
|
||||
}
|
||||
|
||||
int deep_repair_entry(const uint8_t *stored, size_t stored_len, int level,
|
||||
int is_bch, uint16_t poly_id, int rs_level,
|
||||
const uint8_t want_sha[32], size_t blob_size,
|
||||
@@ -372,7 +418,8 @@ int deep_repair_entry(const uint8_t *stored, size_t stored_len, int level,
|
||||
free(bc);
|
||||
}
|
||||
added1 = pools[bi].n; /* pool size after pass-2 */
|
||||
/* Chase-1 candidates (suspects first, then scan). */
|
||||
/* 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);
|
||||
@@ -389,10 +436,16 @@ int deep_repair_entry(const uint8_t *stored, size_t stored_len, int level,
|
||||
bslen[bi], bdlen[bi],
|
||||
poly, susp,
|
||||
BCH_CHASE_MAX_SUSPECTS);
|
||||
ncc = bch_chase1_block(bch_stored + s_off,
|
||||
{
|
||||
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);
|
||||
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;
|
||||
|
||||
@@ -67,6 +67,7 @@ typedef struct {
|
||||
long blocks_total; /* BCH blocks in the blob */
|
||||
long blocks_failed; /* blocks failing standard decode */
|
||||
int partial; /* a level stopped early on its budget */
|
||||
int chase_cuda_used; /* L1 ran on the GPU (CUDA Chase-1 scan) */
|
||||
char fail_stage[24]; /* "ok", "rs", "len", "crc", "sha",
|
||||
"budget", "noecc", "nocand" */
|
||||
} deep_stats_t;
|
||||
|
||||
@@ -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.
|
||||
+56
-5
@@ -1,11 +1,13 @@
|
||||
# Deep repair — past the BCH limit t
|
||||
|
||||
`lzply_deep_repair` recovers archive entries whose bit errors exceed
|
||||
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). The CRC16 is the oracle: every
|
||||
beyond-t candidate is CRC-verified before acceptance, then
|
||||
decompressed and SHA-256-checked.
|
||||
at which level the repair landed). 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
|
||||
|
||||
@@ -37,6 +39,43 @@ decompressed and SHA-256-checked.
|
||||
holds its true data in the pool but neither single-block
|
||||
variation passes the CRC.
|
||||
|
||||
## The CUDA Chase-1 scan (L1 on the GPU)
|
||||
|
||||
On a CUDA build (nvcc present at build time -- `make` links
|
||||
`chase_cuda.o` into `lzply` and `lzply_deep_repair` automatically;
|
||||
without nvcc the build is CPU-only and nothing changes), the L1
|
||||
Chase-1 scan runs on the GPU when a CUDA device is present. The
|
||||
dispatch is automatic: there is no flag. The scan is the same
|
||||
algorithm as the CPU one (one thread per trial position:
|
||||
Berlekamp-Massey + the lambda-splits test, Chien search in
|
||||
parallel for survivors, host syndrome-zero verification), and
|
||||
produces the same candidates in the same order -- verified
|
||||
bit-identical across the 5-pattern validation and a 24-pattern
|
||||
sweep (10/10 CPU/CUDA hash agreements, zero mismatches).
|
||||
|
||||
Measured on hot_house (RTX 3080 Ti), one 524 KiB block (m=22,
|
||||
t=8, -e4), 4,194,296 trials: **171.571 s CPU -> 0.335-0.379 s
|
||||
CUDA (453-512x on the timed scan, ~190x end to end)**; the
|
||||
extended sweep runs 453-562x. A beyond-t repair of a 524 KiB
|
||||
block that took ~8 minutes at L1 now lands in under a second.
|
||||
`-v` marks the L1 line `(CUDA)` when the GPU scan ran.
|
||||
|
||||
Fallback: the CPU scan runs whenever the GPU scan cannot -- no
|
||||
CUDA device, a CPU-only build, a non-t=8 poly (the kernel is
|
||||
t=8 only), a CUDA failure, or a deadline already past when the
|
||||
scan would start. The symbols are referenced weakly, so a
|
||||
CPU-only build links and runs unchanged.
|
||||
|
||||
Limits: the kernel is t=8 only; Chase-2 is not ported (L2 stays
|
||||
on the CPU). The GPU scan has no deadline -- it runs the full
|
||||
scan, then truncates at `BCH_CHASE_MAX_CANDS` (the CPU scan
|
||||
stops early at the cap when the budget hits); the candidate set
|
||||
still matches. On small blocks the ~0.115 s CUDA first-touch
|
||||
cost dominates -- a 512-byte block repairs in ~0.11 s on the GPU
|
||||
vs ~0.04 s on the CPU -- so the win is on large blocks.
|
||||
|
||||
Full write-up: https://www.lzply.com/cuda-chase-500x-deep-repair/
|
||||
|
||||
## Why the suspect set does not help Chase-2 (much)
|
||||
|
||||
With hard-decision input there is no channel reliability, so
|
||||
@@ -98,6 +137,16 @@ 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:
|
||||
|
||||
```
|
||||
@@ -168,7 +217,9 @@ wrong-but-valid candidates per trial and the CRC rejects all
|
||||
`bch_test` 7,975 checks still pass). A full Chase-1 scan of a
|
||||
524 KiB block (4,194,296 trials) takes **471.9 s** (measured,
|
||||
probe5: RECOVERED at L1 in 471.918 s, trials 4,194,296,
|
||||
split 126, codewords 126). The tool scans fully before trying
|
||||
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
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
bench
|
||||
ldpc_diag
|
||||
pass2_diag
|
||||
*.o
|
||||
corpora/
|
||||
results/
|
||||
@@ -0,0 +1,26 @@
|
||||
# exp/Makefile - build the ECC experiments harness (bench).
|
||||
# Links the real lzply BCH + SHA-256 from the repo root.
|
||||
CC ?= gcc
|
||||
CFLAGS ?= -O2 -Wall -Wextra -march=native
|
||||
CPPFLAGS ?= -I. -I..
|
||||
|
||||
SRCS = bench.c bch_wrap.c interleave.c ldpc.c \
|
||||
../bch.c ../sha256.c
|
||||
OBJS = $(SRCS:.c=.o)
|
||||
|
||||
bench: $(OBJS)
|
||||
$(CC) $(CFLAGS) -o $@ $(OBJS) -lm
|
||||
|
||||
ldpc_diag: ldpc_diag.c ldpc.c
|
||||
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ ldpc_diag.c ldpc.c -lm
|
||||
|
||||
pass2_diag: pass2_diag.c ../bch.c ../sha256.c
|
||||
$(CC) $(CFLAGS) $(CPPFLAGS) -o $@ pass2_diag.c ../bch.c ../sha256.c -lm
|
||||
|
||||
%.o: %.c
|
||||
$(CC) $(CFLAGS) $(CPPFLAGS) -c $< -o $@
|
||||
|
||||
clean:
|
||||
rm -f bench ldpc_diag pass2_diag $(OBJS)
|
||||
|
||||
.PHONY: clean
|
||||
+206
@@ -0,0 +1,206 @@
|
||||
# lzply ECC experiments (branch `experiments/ecc`)
|
||||
|
||||
> Integrated onto current main (`experiments/integration`, LZPL v5):
|
||||
> the winners here are interleaving d64, small-block BCH 1 KiB, and
|
||||
> LDPC r90. Polar and UEP were measured, rejected, and their code was
|
||||
> NOT carried over — see `docs/INTEGRATION.md`.
|
||||
|
||||
Open-ended error-correction research on top of lzply's BCH baseline.
|
||||
Each family implements `ecc_iface.h` (whole-blob encode/decode) and is
|
||||
measured by `bench.c` on the same corpora, same corruption matrix, same
|
||||
success criterion (exact recovery, memcmp + SHA-256).
|
||||
|
||||
## How to run
|
||||
|
||||
```
|
||||
./bench --codec bch-t32 --blob corpora/text.lz --size 65536 \
|
||||
--trials 200 --ber 1e-3 --nopass2 --out results/x.csv
|
||||
./bench --codec ldpc-r90 --blob corpora/text.lz --burst 256,1 --trials 200
|
||||
./bench --codec bch-t32 --blob corpora/text.lz --speed
|
||||
./ldpc_diag r90 40 50 # single-block error-count sweep
|
||||
./uep_diag uep-c1024-h32-l8 corpora/text.lz 65536 50 --ber 1e-3
|
||||
```
|
||||
|
||||
Modes: `--ber X` (independent bit flips), `--burst LEN,COUNT`
|
||||
(COUNT randomized-byte bursts of LEN bytes), `--clean`, `--speed`.
|
||||
`--nopass2` skips the (slow) second-chance recovery hook so the matrix
|
||||
stays fast; `run_pass2.sh` measures rescue rates separately.
|
||||
`run_matrix.sh <corpus> <size> <trials> <out.csv> <codec...>` runs the
|
||||
full matrix (5 BERs + 5 burst settings + clean), parallel over cores.
|
||||
|
||||
Corpora (`mkcorpora.sh`, generated, not committed): `text.lz` /
|
||||
`bin.lz` / `rand.lz` — lzip -9 of 4 MiB text, binaries, seeded random
|
||||
bytes (the compressed blob is what lzply protects); `*.raw` — the
|
||||
stored-entry case. Default window is 64 KiB.
|
||||
|
||||
## Families
|
||||
|
||||
| codec | what it is |
|
||||
|---|---|
|
||||
| `bch-t{2,4,8,16,32}` | Baseline: BCH exactly as lzply ships it (auto-pick poly for the whole blob; pass 2 via `recover_verified`). |
|
||||
| `bch1k-t{8,16,32}` | Same BCH, forced m=13 blocks (971 data bytes/block) — the "spend real redundancy" point. |
|
||||
| `intlv-d{D}-bch1k-t{T}` | Byte interleaver (depth D) over bch1k-t{T}. Zero extra parity; bursts spread across blocks. Groups merge the short tail (see below). |
|
||||
| `ldpc-r{90,95}` | Regular LDPC, PEG construction, min-sum belief propagation. |
|
||||
| `polar-r{90,95}[-d{2,3,4}]` | Polar code, SC decoding. `-dN` is the design crossover 1e-N (default d2 = 1e-2). The design point matters enormously (see below). |
|
||||
| `uep-c{C}-h{H}-l{L}` | Unequal error protection: first C bytes at BCH t=H, rest at t=L (small blocks). |
|
||||
|
||||
## Results (text.lz, 64 KiB windows, 200 trials/setting, hot_newyork)
|
||||
|
||||
Recovery rate = fraction of trials exactly recovered. Overhead is
|
||||
measured (stored/data - 1). Pass-2 rescue rates are in
|
||||
results/pass2-text.csv (separate, 25 trials/setting).
|
||||
|
||||
### Baseline: what lzply ships is nearly unprotected
|
||||
|
||||
| codec | ovh | BER 1e-5 | 1e-4 | 1e-3 | 3e-3 | 1e-2 | burst 256 B |
|
||||
|---|---|---|---|---|---|---|---|
|
||||
| bch-t2 | 0.01% | 0.11 | 0 | 0 | 0 | 0 | 0 |
|
||||
| bch-t8 | 0.03% | 0.88 | 0 | 0 | 0 | 0 | 0 |
|
||||
| bch-t16 | 0.06% | 1.00 | 0 | 0 | 0 | 0 | 0 |
|
||||
| bch-t32 | 0.12% | 1.00 | 0.01 | 0 | 0 | 0 | 0 |
|
||||
|
||||
One 64 KiB blob is a single BCH block (m=20, 80 parity bytes), so
|
||||
t=32 corrects 32 bit errors per 64 KiB. At BER 1e-4 the blob already
|
||||
carries ~52 errors: the cliff is between 1e-5 and 1e-4.
|
||||
|
||||
Pass 2 (hash-gated candidates) rescues nothing in practice:
|
||||
the repo's own bch_test reports t+1 recovered 0/100 and t+2
|
||||
recovered 0/100; this harness's pass2 matrix (35 rows, 875 trials,
|
||||
all BCH codecs) shows rescued=0 in every setting, and a targeted
|
||||
sweep (pass2_diag, m=13 t=16, k=t+1..t+8) rescues 0/50 at every k. Its mechanism (residual-BM)
|
||||
addresses pass-1 miscorrection, which essentially never happens
|
||||
for random errors (pass 1 fails rather than miscorrecting), and
|
||||
the flip-and-redecode fallback does not reach the true codeword.
|
||||
Its demonstrated value is the loud-failure guarantee: 0 silent
|
||||
miscorrections in 7813 checks. The matrix numbers above are
|
||||
therefore the true lzply numbers with or without pass 2.
|
||||
|
||||
### Spending redundancy: small-block BCH
|
||||
|
||||
| codec | ovh | BER 1e-4 | 1e-3 | 3e-3 |
|
||||
|---|---|---|---|---|
|
||||
| bch1k-t8 | 1.29% | 1.00 | 0 | 0 |
|
||||
| bch1k-t16 | 2.62% | 1.00 | 0.73 | 0 |
|
||||
| bch1k-t32 | 5.40% | 1.00 | 1.00 | 0.01 |
|
||||
|
||||
Same code, 1 KiB blocks: t=32 buys survival to BER 1e-3 at 5.4%
|
||||
overhead. Bursts still kill it (256 B burst: 0.00 at every t).
|
||||
|
||||
### Interleaving: zero-overhead burst protection (WINNER)
|
||||
|
||||
Byte interleave over bch1k-t32, 5.40% overhead (unchanged):
|
||||
|
||||
| codec | burst 16 B | 64 B | 256 B | 1024 B | 4x64 B |
|
||||
|---|---|---|---|---|---|
|
||||
| bch1k-t32 (no intlv) | 0 | 0 | 0 | 0 | 0 |
|
||||
| intlv-d16-t32 | 1.00 | 1.00 | 0 | 0 | 0.10 |
|
||||
| intlv-d32-t32 | 1.00 | 1.00 | 0 | 0 | 0.80 |
|
||||
| intlv-d64-t32 | 1.00 | 1.00 | 1.00 | 0 | 1.00 |
|
||||
|
||||
Random-error performance is unchanged by construction (same BCH
|
||||
underneath). Even at 1.29% overhead, intlv-d64-bch1k-t8 survives
|
||||
64 B bursts at 1.00. Gotcha fixed en route: a short tail group
|
||||
(4 blocks of 68) was the weak point and measured 0.94 on 64 B
|
||||
bursts; groups now merge the tail.
|
||||
|
||||
### LDPC: the random-error winner (WINNER at ~11% overhead)
|
||||
|
||||
| codec | ovh | BER 1e-3 | 3e-3 | 1e-2 | burst 16 B |
|
||||
|---|---|---|---|---|---|
|
||||
| ldpc-r90 | 10.94% | 1.00 | 0.97 | 0 | 0.24 |
|
||||
| ldpc-r95 | 6.25% | 0.32 | 0 | 0 | 0 |
|
||||
|
||||
At BER 3e-3, ldpc-r90 recovers 0.97 where bch1k-t32 recovers 0.01
|
||||
— the iterative decoder's cliff sits a decade higher in BER. But
|
||||
bursts kill it (a 16 B burst is ~64 errors in one 1 KiB block),
|
||||
and r95 is weak: the regular (3,64) code starts failing at 6
|
||||
errors/block (ldpc_diag). Irregular LDPC would be the follow-up;
|
||||
LDPC+interleave would fix bursts.
|
||||
|
||||
### Polar SC: dominated, rejected (honest negative)
|
||||
|
||||
Designing for p=1e-2 gives 0.00 at BER 1e-4; designing for the
|
||||
operating point (d3/d4) gives 0.90/0.95 at 1e-4 — but every variant
|
||||
is 0.00 at BER 1e-3. SC at N=4096/R=0.9 is far weaker than
|
||||
bch1k-t32 (1.00 at 1e-3, half the overhead) and ldpc-r90 (1.00 at
|
||||
1e-3, same overhead). Two real bugs were fixed en route (SC partial
|
||||
sums overwrote the leaf decisions; see polar.c). SCL list decoding
|
||||
is the follow-up that could rescue polar; SC as measured is a reject.
|
||||
|
||||
### UEP: graceful degradation, conditional
|
||||
|
||||
Exact recovery is dominated by the weak tier (uep-c1024-h32-l8 at
|
||||
1e-3: 0.00, same as uniform bch1k-t8). The prefix tells another
|
||||
story (uep_diag, 50 trials):
|
||||
|
||||
| codec | BER 1e-3 whole | BER 1e-3 prefix | burst 256 B prefix |
|
||||
|---|---|---|---|
|
||||
| uep-c1024-h32-l8 | 0.00 | 1.00 | 1.00 |
|
||||
| uep-c4096-h32-l8 | 0.00 | 1.00 | 0.94 |
|
||||
|
||||
The first 1-4 KiB (lzip header + stream start) survives when the
|
||||
file is lost. Only useful if lzply gains a salvage mode; today the
|
||||
entry SHA gates all-or-nothing extraction.
|
||||
|
||||
## Speed and memory (isolated, sequential, 64 KiB blob, clean)
|
||||
|
||||
`--speed` mode, 5 reps each. RSS is the bench process peak (harness
|
||||
+ buffers ~6.5 MB); the codec delta is what matters.
|
||||
|
||||
| codec | enc MB/s | dec MB/s | RSS KB | ovh |
|
||||
|---|---|---|---|---|
|
||||
| bch-t32 | 6.46 | 3.44 | 6564 | 0.12% |
|
||||
| bch1k-t8 | 9.98 | 5.87 | 6560 | 1.29% |
|
||||
| bch1k-t16 | 5.39 | 3.14 | 6492 | 2.62% |
|
||||
| bch1k-t32 | 2.97 | 1.55 | 6652 | 5.40% |
|
||||
| intlv-d64-t32 | 3.39 | 1.73 | 6720 | 5.40% |
|
||||
| intlv-d64-t8 | 11.11 | 5.80 | 6572 | 1.29% |
|
||||
| ldpc-r90 | 3.34 | 0.91 | 7776 | 10.94% |
|
||||
| ldpc-r95 | 5.18 | 1.16 | 7652 | 6.25% |
|
||||
| polar-r90-d4 | 4.82 | 0.58 | 7252 | 11.72% |
|
||||
| uep-c1024-h32-l8 | 9.96 | 4.80 | 6612 | 1.43% |
|
||||
|
||||
Interleaving costs nothing measurable (same speed and memory as
|
||||
the BCH underneath; it is a permutation). LDPC pays a one-time
|
||||
~1.8 s init (PEG + Gauss-Jordan) and decodes ~4x slower than
|
||||
bch1k-t32; polar decodes slowest of all (0.58 MB/s). Failed BCH
|
||||
decodes are far slower than clean ones (pass 2 dominates; matrix
|
||||
rows for failed whole-blob blocks read 0.02-0.10 MB/s).
|
||||
|
||||
## Generalization
|
||||
|
||||
Cross-corpus check (bin.lz, rand.lz, 100 trials/setting, headline
|
||||
codecs, BER 1e-4/1e-3 + 256 B burst + clean) reproduces text.lz
|
||||
exactly for every codec and setting: bch1k-t32 1.00/1.00/0.00,
|
||||
intlv-d64-t32 1.00/1.00/1.00, ldpc-r90 1.00/1.00/0.00,
|
||||
polar-r90-d4 0.94/0.00/0.00, uep-c1024 1.00/0.00/0.00. Clean
|
||||
round-trips are bit-identical everywhere (all clean rows 1.00).
|
||||
|
||||
## Test totals
|
||||
|
||||
- BCH matrix (text.lz): 143 rows x 200 trials = 28,600 trials
|
||||
- LDPC matrix: 22 rows x 200 = 4,400
|
||||
- Polar matrix: 33 rows x 200 = 6,600
|
||||
- UEP matrix: 33 rows x 200 = 6,600
|
||||
- Pass-2 matrix: 35 rows x 25 = 875 (rescued 0)
|
||||
- Cross-corpus: 48 rows x 100 = 4,800
|
||||
- Diagnostics: ldpc_diag single-block sweeps, uep_diag prefix
|
||||
survival (50 trials/setting), pass2_diag targeted sweep
|
||||
(t+1..t+8, 50 trials each)
|
||||
- Total matrix trials: 51,875 (+ diagnostics)
|
||||
- hot_chicago verification: BLOCKED — the old-VPS tunnel's SSH
|
||||
leg to 104.225.223.162 failed 4 times over ~1.5 h (banner-exchange
|
||||
timeout on the last attempt). Snapshot zips are staged on the
|
||||
old VPS (/tmp/lzply-*.zip) for a retry when the tunnel recovers.
|
||||
|
||||
## Rules of this branch
|
||||
|
||||
- Never touch `main` or the other coordinator's branches/checkouts.
|
||||
- No Reed-Solomon (the other job's territory).
|
||||
- No legacy support; the format may change freely.
|
||||
- Do not break the existing `-r` levels.
|
||||
- Honest negatives count: a family that loses on every axis is killed
|
||||
early and its numbers recorded.
|
||||
- After every push: zip snapshot to /root/git-backups/lzply/ on both
|
||||
servers (newest 7 kept); use /root/scripts/git-push-snapshot.sh
|
||||
when present, else temp-clone + zip + copy manually.
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
/* bch_wrap.c - BCH baseline codecs for the experiments harness.
|
||||
*
|
||||
* Two operating points of the same code, so the harness can show the
|
||||
* overhead/correction tradeoff honestly:
|
||||
*
|
||||
* bch-t<N> - exactly what lzply ships: bch_poly_for_data(blob, t)
|
||||
* picks the smallest parent covering the WHOLE blob, so a
|
||||
* 64 KiB blob is a single huge block (m=20, t=32 -> 80
|
||||
* parity bytes, 0.12% overhead, 32 correctable bits per
|
||||
* 64 KiB). Pass 2 (hash-gated candidates) is wired to
|
||||
* recover_verified, matching entry_decode().
|
||||
* bch1k-t<N> - same code, forced small blocks: pinned m=13 poly, so a
|
||||
* block holds 971 data bytes (t=32 -> 5.4% overhead).
|
||||
* This is the "what if we spent real redundancy" point.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "ecc_iface.h"
|
||||
#include "bch.h"
|
||||
#include "bch_polys.h"
|
||||
#include "sha256.h"
|
||||
|
||||
typedef struct {
|
||||
int t;
|
||||
const bch_poly_t *pinned; /* NULL = auto-pick (as-shipped) */
|
||||
} bch_priv_t;
|
||||
|
||||
static const bch_poly_t *poly_by_mt(int m, int t)
|
||||
{
|
||||
for (int i = 0; i < BCH_NPOLYS; i++)
|
||||
if (bch_polys[i].m == m && bch_polys[i].t == t)
|
||||
return &bch_polys[i];
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static size_t bch_encode_fn(ecc_codec_t *c, const uint8_t *data, size_t len,
|
||||
uint8_t **out)
|
||||
{
|
||||
bch_priv_t *p = (bch_priv_t *)c->priv;
|
||||
const bch_poly_t *poly = p->pinned;
|
||||
if (!poly)
|
||||
poly = bch_poly_for_data(len, p->t);
|
||||
if (!poly)
|
||||
return 0;
|
||||
size_t slen = bch_encoded_len(len, poly);
|
||||
uint8_t *buf = (uint8_t *)malloc(slen ? slen : 1);
|
||||
if (!buf)
|
||||
return 0;
|
||||
if (bch_encode(data, len, poly, buf) != slen) {
|
||||
free(buf);
|
||||
return 0;
|
||||
}
|
||||
c->overhead = len ? (double)slen / (double)len - 1.0 : 0.0;
|
||||
*out = buf;
|
||||
return slen;
|
||||
}
|
||||
|
||||
static int bch_decode_fn(ecc_codec_t *c, const uint8_t *stored, size_t slen,
|
||||
size_t orig_len, uint8_t *out, long *corrected)
|
||||
{
|
||||
bch_priv_t *p = (bch_priv_t *)c->priv;
|
||||
const bch_poly_t *poly = p->pinned;
|
||||
if (!poly)
|
||||
poly = bch_poly_for_data(orig_len, p->t);
|
||||
if (!poly)
|
||||
return -1;
|
||||
if (slen != bch_encoded_len(orig_len, poly))
|
||||
return -1;
|
||||
int corr = 0;
|
||||
int rc = bch_decode(stored, slen, orig_len, poly, out, &corr);
|
||||
if (corrected)
|
||||
*corrected = rc == 0 ? corr : -1;
|
||||
return rc;
|
||||
}
|
||||
|
||||
static int bch_recover_fn(ecc_codec_t *c, const uint8_t *stored, size_t slen,
|
||||
size_t orig_len, const uint8_t want_sha[32],
|
||||
uint8_t *out)
|
||||
{
|
||||
bch_priv_t *p = (bch_priv_t *)c->priv;
|
||||
const bch_poly_t *poly = p->pinned;
|
||||
if (!poly)
|
||||
poly = bch_poly_for_data(orig_len, p->t);
|
||||
if (!poly)
|
||||
return -1;
|
||||
if (slen != bch_encoded_len(orig_len, poly))
|
||||
return -1;
|
||||
uint8_t *cands = (uint8_t *)malloc((size_t)BCH_PASS2_MAX_CANDS * orig_len);
|
||||
if (!cands)
|
||||
return -1;
|
||||
int nc = bch_decode_candidates(stored, slen, orig_len, poly, cands,
|
||||
BCH_PASS2_MAX_CANDS);
|
||||
int found = -1;
|
||||
for (int i = 0; i < nc && found < 0; i++) {
|
||||
uint8_t h[32];
|
||||
lzply_sha256(cands + (size_t)i * orig_len, orig_len, h);
|
||||
if (memcmp(h, want_sha, 32) == 0)
|
||||
found = i;
|
||||
}
|
||||
if (found >= 0)
|
||||
memcpy(out, cands + (size_t)found * orig_len, orig_len);
|
||||
free(cands);
|
||||
return found >= 0 ? 0 : -1;
|
||||
}
|
||||
|
||||
static void bch_destroy(ecc_codec_t *c)
|
||||
{
|
||||
free(c->priv);
|
||||
free((void *)c->name);
|
||||
free(c);
|
||||
}
|
||||
|
||||
static ecc_codec_t *bch_new(int t, const bch_poly_t *pinned, const char *name)
|
||||
{
|
||||
ecc_codec_t *c = (ecc_codec_t *)calloc(1, sizeof(*c));
|
||||
bch_priv_t *p = (bch_priv_t *)calloc(1, sizeof(*p));
|
||||
if (!c || !p) {
|
||||
free(c);
|
||||
free(p);
|
||||
return NULL;
|
||||
}
|
||||
p->t = t;
|
||||
p->pinned = pinned;
|
||||
c->name = name;
|
||||
c->desc = pinned ? "BCH, forced 1 KiB blocks" : "BCH as shipped in lzply";
|
||||
c->block_data = pinned ? bch_max_data(pinned) : 0;
|
||||
c->encode = bch_encode_fn;
|
||||
c->decode = bch_decode_fn;
|
||||
c->recover_verified = bch_recover_fn;
|
||||
c->destroy = bch_destroy;
|
||||
c->priv = p;
|
||||
return c;
|
||||
}
|
||||
|
||||
/* As-shipped: auto-pick poly for the whole blob. */
|
||||
ecc_codec_t *bch_ship_new(int t)
|
||||
{
|
||||
char *name = (char *)malloc(32);
|
||||
if (!name)
|
||||
return NULL;
|
||||
snprintf(name, 32, "bch-t%d", t);
|
||||
return bch_new(t, NULL, name);
|
||||
}
|
||||
|
||||
/* Forced small blocks: pinned m=13 poly (971 data bytes/block at any t). */
|
||||
ecc_codec_t *bch_1k_new(int t)
|
||||
{
|
||||
const bch_poly_t *poly = poly_by_mt(13, t);
|
||||
if (!poly)
|
||||
return NULL;
|
||||
char *name = (char *)malloc(32);
|
||||
if (!name)
|
||||
return NULL;
|
||||
snprintf(name, 32, "bch1k-t%d", t);
|
||||
return bch_new(t, poly, name);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
/* bch_wrap.h - constructors for the BCH baseline codecs (bch_wrap.c). */
|
||||
#ifndef EXP_BCH_WRAP_H
|
||||
#define EXP_BCH_WRAP_H
|
||||
|
||||
#include "ecc_iface.h"
|
||||
|
||||
ecc_codec_t *bch_ship_new(int t);
|
||||
ecc_codec_t *bch_1k_new(int t);
|
||||
|
||||
#endif /* EXP_BCH_WRAP_H */
|
||||
+338
@@ -0,0 +1,338 @@
|
||||
/* bench.c - corruption-matrix harness for the lzply ECC experiments.
|
||||
*
|
||||
* One invocation = one codec x one corruption setting x N trials.
|
||||
* Each trial: take a window of the corpus blob, encode it, corrupt the
|
||||
* stored bytes (random bit flips at a BER, or randomized byte bursts),
|
||||
* decode, and check exact recovery (memcmp + SHA-256). On decode
|
||||
* failure, the codec's recover_verified hook (if any) gets one shot
|
||||
* with the expected SHA -- that is how BCH pass 2 is credited.
|
||||
*
|
||||
* Usage:
|
||||
* bench --codec NAME --blob FILE [--size N] [--trials N] [--seed S]
|
||||
* (--ber X | --burst LEN,COUNT | --clean | --speed)
|
||||
* [--out results.csv]
|
||||
*
|
||||
* CSV (appended to --out, or stdout if omitted):
|
||||
* codec,corpus,blob_size,trials,mode,param,success,rescued,rate,
|
||||
* enc_MBps,dec_MBps,peak_rss_kb,overhead_pct
|
||||
*
|
||||
* Exit 0 on a completed run (even if recovery is 0 -- that is data),
|
||||
* 2 on usage/codec errors.
|
||||
*/
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdint.h>
|
||||
#include <inttypes.h>
|
||||
#include <time.h>
|
||||
#include <libgen.h>
|
||||
#include <sys/resource.h>
|
||||
|
||||
#include "ecc_iface.h"
|
||||
#include "sha256.h"
|
||||
|
||||
/* ---- codec factory (one constructor per family file) ---- */
|
||||
ecc_codec_t *bch_ship_new(int t);
|
||||
ecc_codec_t *bch_1k_new(int t);
|
||||
ecc_codec_t *interleave_new(int depth, int t);
|
||||
ecc_codec_t *ldpc_new(int rate_pct);
|
||||
|
||||
static ecc_codec_t *make_codec(const char *name)
|
||||
{
|
||||
int v;
|
||||
if (sscanf(name, "bch-t%d", &v) == 1)
|
||||
return bch_ship_new(v);
|
||||
if (sscanf(name, "bch1k-t%d", &v) == 1)
|
||||
return bch_1k_new(v);
|
||||
int d, t;
|
||||
if (sscanf(name, "intlv-d%d-bch1k-t%d", &d, &t) == 2)
|
||||
return interleave_new(d, t);
|
||||
if (sscanf(name, "ldpc-r%d", &v) == 1)
|
||||
return ldpc_new(v);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* ---- xorshift64* RNG ---- */
|
||||
static uint64_t rs = 0x12345678abcdefULL;
|
||||
static inline uint64_t xr(void)
|
||||
{
|
||||
rs ^= rs << 13;
|
||||
rs ^= rs >> 7;
|
||||
rs ^= rs << 17;
|
||||
return rs;
|
||||
}
|
||||
|
||||
static double now_s(void)
|
||||
{
|
||||
struct timespec ts;
|
||||
clock_gettime(CLOCK_MONOTONIC, &ts);
|
||||
return ts.tv_sec + ts.tv_nsec * 1e-9;
|
||||
}
|
||||
|
||||
static uint8_t *read_file(const char *path, size_t *len_out)
|
||||
{
|
||||
FILE *f = fopen(path, "rb");
|
||||
if (!f)
|
||||
return NULL;
|
||||
fseek(f, 0, SEEK_END);
|
||||
long n = ftell(f);
|
||||
fseek(f, 0, SEEK_SET);
|
||||
if (n <= 0) {
|
||||
fclose(f);
|
||||
return NULL;
|
||||
}
|
||||
uint8_t *buf = (uint8_t *)malloc((size_t)n);
|
||||
if (!buf) {
|
||||
fclose(f);
|
||||
return NULL;
|
||||
}
|
||||
if (fread(buf, 1, (size_t)n, f) != (size_t)n) {
|
||||
free(buf);
|
||||
fclose(f);
|
||||
return NULL;
|
||||
}
|
||||
fclose(f);
|
||||
*len_out = (size_t)n;
|
||||
return buf;
|
||||
}
|
||||
|
||||
static void usage(void)
|
||||
{
|
||||
fprintf(stderr,
|
||||
"usage: bench --codec NAME --blob FILE [--size N] [--trials N]\n"
|
||||
" [--seed S] (--ber X | --burst LEN,COUNT | --clean | --speed)\n"
|
||||
" [--out results.csv]\n"
|
||||
" codecs: bch-t{2,4,8,16,32} bch1k-t{8,16,32}\n"
|
||||
" intlv-d{16,32,64}-bch1k-t{8,16,32} ldpc-r{90,95}\n");
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
const char *codec_name = NULL, *blob_path = NULL, *out_path = NULL;
|
||||
size_t win_size = 65536;
|
||||
long trials = 200;
|
||||
uint64_t seed = 0x12345678abcdefULL;
|
||||
enum { M_BER, M_BURST, M_CLEAN, M_SPEED } mode = M_BER;
|
||||
double ber = 1e-3;
|
||||
long burst_len = 256, burst_count = 1;
|
||||
int nopass2 = 0;
|
||||
|
||||
for (int i = 1; i < argc; i++) {
|
||||
if (!strcmp(argv[i], "--codec") && i + 1 < argc)
|
||||
codec_name = argv[++i];
|
||||
else if (!strcmp(argv[i], "--blob") && i + 1 < argc)
|
||||
blob_path = argv[++i];
|
||||
else if (!strcmp(argv[i], "--out") && i + 1 < argc)
|
||||
out_path = argv[++i];
|
||||
else if (!strcmp(argv[i], "--size") && i + 1 < argc)
|
||||
win_size = (size_t)strtoull(argv[++i], NULL, 0);
|
||||
else if (!strcmp(argv[i], "--trials") && i + 1 < argc)
|
||||
trials = strtol(argv[++i], NULL, 0);
|
||||
else if (!strcmp(argv[i], "--seed") && i + 1 < argc)
|
||||
seed = strtoull(argv[++i], NULL, 0);
|
||||
else if (!strcmp(argv[i], "--ber") && i + 1 < argc) {
|
||||
mode = M_BER;
|
||||
ber = strtod(argv[++i], NULL);
|
||||
} else if (!strcmp(argv[i], "--burst") && i + 1 < argc) {
|
||||
mode = M_BURST;
|
||||
char *a = argv[++i];
|
||||
burst_len = strtol(a, NULL, 0);
|
||||
char *comma = strchr(a, ',');
|
||||
burst_count = comma ? strtol(comma + 1, NULL, 0) : 1;
|
||||
} else if (!strcmp(argv[i], "--nopass2")) {
|
||||
nopass2 = 1;
|
||||
} else if (!strcmp(argv[i], "--clean")) {
|
||||
mode = M_CLEAN;
|
||||
} else if (!strcmp(argv[i], "--speed")) {
|
||||
mode = M_SPEED;
|
||||
} else {
|
||||
usage();
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
if (!codec_name || !blob_path) {
|
||||
usage();
|
||||
return 2;
|
||||
}
|
||||
|
||||
size_t file_len = 0;
|
||||
uint8_t *file = read_file(blob_path, &file_len);
|
||||
if (!file || file_len <= win_size) {
|
||||
fprintf(stderr, "bench: cannot read blob %s (need > %zu bytes)\n",
|
||||
blob_path, win_size);
|
||||
return 2;
|
||||
}
|
||||
rs = seed ^ 0x9e3779b97f4a7c15ULL;
|
||||
|
||||
double t0 = now_s();
|
||||
ecc_codec_t *c = make_codec(codec_name);
|
||||
double init_s = now_s() - t0;
|
||||
if (!c) {
|
||||
fprintf(stderr, "bench: unknown codec %s\n", codec_name);
|
||||
return 2;
|
||||
}
|
||||
|
||||
const char *corpus = strrchr(blob_path, '/');
|
||||
corpus = corpus ? corpus + 1 : blob_path;
|
||||
|
||||
uint8_t *win = (uint8_t *)malloc(win_size);
|
||||
uint8_t *stored = NULL, *rx = NULL, *out = NULL;
|
||||
uint8_t want_sha[32];
|
||||
if (!win) return 2;
|
||||
out = (uint8_t *)malloc(win_size);
|
||||
if (!out) return 2;
|
||||
|
||||
long success = 0, rescued = 0;
|
||||
double enc_s = 0, dec_s = 0;
|
||||
double overhead = 0;
|
||||
int have_overhead = 0;
|
||||
|
||||
if (mode == M_SPEED) {
|
||||
/* encode/decode the whole file in windows, 5 passes */
|
||||
long passes = 5;
|
||||
size_t nw = file_len / win_size;
|
||||
double te0 = now_s();
|
||||
for (long p = 0; p < passes; p++)
|
||||
for (size_t w = 0; w < nw; w++) {
|
||||
free(stored);
|
||||
stored = NULL;
|
||||
size_t sl = c->encode(c, file + w * win_size, win_size, &stored);
|
||||
if (!sl) {
|
||||
fprintf(stderr, "bench: encode failed in speed mode\n");
|
||||
return 2;
|
||||
}
|
||||
if (!have_overhead) {
|
||||
overhead = c->overhead;
|
||||
have_overhead = 1;
|
||||
}
|
||||
}
|
||||
double te1 = now_s();
|
||||
double td0 = now_s();
|
||||
for (long p = 0; p < passes; p++)
|
||||
for (size_t w = 0; w < nw; w++) {
|
||||
size_t sl = c->encode(c, file + w * win_size, win_size, &stored);
|
||||
long corr = -1;
|
||||
if (c->decode(c, stored, sl, win_size, out, &corr) != 0 ||
|
||||
memcmp(out, file + w * win_size, win_size) != 0) {
|
||||
fprintf(stderr, "bench: speed-mode roundtrip FAILED\n");
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
double td1 = now_s();
|
||||
double bytes = (double)passes * nw * win_size;
|
||||
double enc_mb = bytes / (te1 - te0) / 1e6;
|
||||
double dec_mb = bytes / (td1 - td0) / 1e6;
|
||||
struct rusage ru;
|
||||
getrusage(RUSAGE_SELF, &ru);
|
||||
fprintf(stderr,
|
||||
"SPEED %-28s corpus=%s win=%zu init=%.2fs enc=%.1f MB/s "
|
||||
"dec=%.1f MB/s rss=%ld KiB overhead=%.2f%%\n",
|
||||
codec_name, corpus, win_size, init_s, enc_mb, dec_mb,
|
||||
ru.ru_maxrss, overhead * 100.0);
|
||||
FILE *f = out_path ? fopen(out_path, "a") : stdout;
|
||||
if (f) {
|
||||
fprintf(f, "%s,%s,%zu,%ld,speed,init=%.2fs,0,0,1.000,"
|
||||
"%.2f,%.2f,%ld,%.4f\n",
|
||||
codec_name, corpus, win_size, passes, init_s, enc_mb,
|
||||
dec_mb, ru.ru_maxrss, overhead * 100.0);
|
||||
if (f != stdout)
|
||||
fclose(f);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* corruption trials */
|
||||
uint64_t ber_thr = (uint64_t)(ber * 18446744073709551616.0);
|
||||
rx = (uint8_t *)malloc(1 << 20); /* grown below if needed */
|
||||
for (long tr = 0; tr < trials; tr++) {
|
||||
size_t off = (size_t)(xr() % (file_len - win_size + 1));
|
||||
memcpy(win, file + off, win_size);
|
||||
lzply_sha256(win, win_size, want_sha);
|
||||
|
||||
double te0 = now_s();
|
||||
size_t slen = c->encode(c, win, win_size, &stored);
|
||||
double te1 = now_s();
|
||||
if (!slen) {
|
||||
fprintf(stderr, "bench: encode failed trial %ld\n", tr);
|
||||
return 2;
|
||||
}
|
||||
if (!have_overhead) {
|
||||
overhead = c->overhead;
|
||||
have_overhead = 1;
|
||||
}
|
||||
if (tr == 0) {
|
||||
free(rx);
|
||||
rx = (uint8_t *)malloc(slen);
|
||||
if (!rx)
|
||||
return 2;
|
||||
}
|
||||
memcpy(rx, stored, slen);
|
||||
|
||||
/* corrupt the stored bytes */
|
||||
if (mode == M_BER) {
|
||||
for (size_t i = 0; i < slen; i++) {
|
||||
uint8_t m = 0;
|
||||
for (int b = 0; b < 8; b++)
|
||||
if (xr() < ber_thr)
|
||||
m |= (uint8_t)(1u << b);
|
||||
rx[i] ^= m;
|
||||
}
|
||||
} else if (mode == M_BURST) {
|
||||
for (long b = 0; b < burst_count; b++) {
|
||||
if ((size_t)burst_len >= slen)
|
||||
continue;
|
||||
size_t start = (size_t)(xr() % (slen - (size_t)burst_len + 1));
|
||||
for (long k = 0; k < burst_len; k++)
|
||||
rx[start + k] = (uint8_t)(xr() & 0xff);
|
||||
}
|
||||
}
|
||||
|
||||
double td0 = now_s();
|
||||
long corr = -1;
|
||||
int rc = c->decode(c, rx, slen, win_size, out, &corr);
|
||||
int ok = (rc == 0 && memcmp(out, win, win_size) == 0);
|
||||
if (!ok && !nopass2 && c->recover_verified) {
|
||||
if (c->recover_verified(c, rx, slen, win_size, want_sha, out) == 0) {
|
||||
ok = 1;
|
||||
rescued++;
|
||||
}
|
||||
}
|
||||
double td1 = now_s();
|
||||
enc_s += te1 - te0;
|
||||
dec_s += td1 - td0;
|
||||
if (ok)
|
||||
success++;
|
||||
free(stored);
|
||||
stored = NULL;
|
||||
}
|
||||
|
||||
struct rusage ru;
|
||||
getrusage(RUSAGE_SELF, &ru);
|
||||
double rate = trials ? (double)success / (double)trials : 0;
|
||||
double enc_mb = enc_s > 0 ? (double)trials * win_size / enc_s / 1e6 : 0;
|
||||
double dec_mb = dec_s > 0 ? (double)trials * win_size / dec_s / 1e6 : 0;
|
||||
char param[64];
|
||||
if (mode == M_BER)
|
||||
snprintf(param, sizeof param, "ber=%g", ber);
|
||||
else if (mode == M_BURST)
|
||||
snprintf(param, sizeof param, "burst=%ldx%ld", burst_len, burst_count);
|
||||
else
|
||||
snprintf(param, sizeof param, "clean");
|
||||
const char *mname =
|
||||
mode == M_BER ? "ber" : mode == M_BURST ? "burst" : "clean";
|
||||
FILE *f = out_path ? fopen(out_path, "a") : stdout;
|
||||
if (f) {
|
||||
fprintf(f, "%s,%s,%zu,%ld,%s,%s,%ld,%ld,%.4f,%.2f,%.2f,%ld,%.4f\n",
|
||||
codec_name, corpus, win_size, trials, mname, param, success,
|
||||
rescued, rate, enc_mb, dec_mb, ru.ru_maxrss,
|
||||
overhead * 100.0);
|
||||
if (f != stdout)
|
||||
fclose(f);
|
||||
}
|
||||
fprintf(stderr, "%-28s %-12s %-14s %4ld trials rate=%.3f rescued=%ld "
|
||||
"enc=%.0fMB/s dec=%.0fMB/s ovh=%.2f%% rss=%ldKiB\n",
|
||||
codec_name, corpus, param, trials, rate, rescued, enc_mb, dec_mb,
|
||||
overhead * 100.0, ru.ru_maxrss);
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/* ecc_iface.h - generic error-correction codec interface for the lzply
|
||||
* experiments harness (exp/). Every family under test implements this
|
||||
* interface so bench.c measures them all the same way: encode a blob,
|
||||
* corrupt the stored bytes, decode, and check exact recovery (SHA-256).
|
||||
*
|
||||
* A codec is a whole-blob transform: encode(data) -> stored bytes,
|
||||
* decode(stored) -> data or failure. Block structure inside is the
|
||||
* codec's business; the harness only sees blob in / blob out.
|
||||
*/
|
||||
#ifndef EXP_ECC_IFACE_H
|
||||
#define EXP_ECC_IFACE_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
typedef struct ecc_codec ecc_codec_t;
|
||||
struct ecc_codec {
|
||||
const char *name; /* short id, e.g. "bch-t32" (used in CSV output) */
|
||||
const char *desc; /* human-readable description */
|
||||
size_t block_data; /* nominal data bytes per code block (0 = whole blob) */
|
||||
/* encode data[0..len) -> malloc'd *out; return stored length, 0 on error.
|
||||
Sets c->overhead = stored/len - 1. */
|
||||
size_t (*encode)(ecc_codec_t *c, const uint8_t *data, size_t len,
|
||||
uint8_t **out);
|
||||
/* decode stored[0..slen) -> out[0..orig_len); 0 = exact recovery,
|
||||
-1 = failure. *corrected = bits/symbols corrected if known, else -1. */
|
||||
int (*decode)(ecc_codec_t *c, const uint8_t *stored, size_t slen,
|
||||
size_t orig_len, uint8_t *out, long *corrected);
|
||||
/* Optional second-chance recovery: given the expected SHA-256 of the
|
||||
original data, try harder (e.g. BCH pass-2 candidates) and use the
|
||||
first candidate that verifies. 0 = rescued, -1 = not. May be NULL. */
|
||||
int (*recover_verified)(ecc_codec_t *c, const uint8_t *stored,
|
||||
size_t slen, size_t orig_len,
|
||||
const uint8_t want_sha[32], uint8_t *out);
|
||||
double overhead; /* from the last encode() call */
|
||||
void (*destroy)(ecc_codec_t *c);
|
||||
void *priv;
|
||||
};
|
||||
|
||||
#endif /* EXP_ECC_IFACE_H */
|
||||
@@ -0,0 +1,253 @@
|
||||
/* interleave.c - byte interleaver over small-block BCH.
|
||||
*
|
||||
* The encoded stream (bch1k-t{T}: blocks of ~1 KiB data, t parity bits
|
||||
* each) is permuted before it hits the channel: the stream is cut into
|
||||
* groups of D consecutive blocks, each group written row-wise into a
|
||||
* D-row matrix (row j = block j) and read out column-wise. A burst of
|
||||
* L consecutive bytes in the channel then hits any one block at most
|
||||
* ceil(L/D) bytes -- about 4*L/D bit errors, since a randomized byte
|
||||
* flips ~4 bits -- instead of all L bytes landing in one block and
|
||||
* killing it outright. Zero extra parity: the interleaver is a pure
|
||||
* permutation, inverted on decode, so overhead is exactly the BCH
|
||||
* overhead and random-error performance is unchanged. The win is
|
||||
* purely burst tolerance, roughly a factor D in burst length.
|
||||
*
|
||||
* Groups are self-delimiting: block boundaries are recomputed from
|
||||
* orig_len, so the decoder knows every group's shape. The final group
|
||||
* may be short and the final block short; the column traversal simply
|
||||
* skips missing cells, which keeps the permutation exact with no
|
||||
* padding and no length change.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "ecc_iface.h"
|
||||
#include "bch.h"
|
||||
#include "bch_wrap.h"
|
||||
|
||||
typedef struct {
|
||||
ecc_codec_t *inner; /* bch1k-t{T} */
|
||||
int depth; /* blocks per interleave group */
|
||||
int t;
|
||||
} intlv_priv_t;
|
||||
|
||||
/* Permute the encoded stream (forward = interleave).
|
||||
* blocks[] holds the stored length of each block; nblocks total.
|
||||
* out must hold the same total length.
|
||||
*
|
||||
* Groups: blocks are cut into groups of `depth`, EXCEPT the final
|
||||
* partial group is merged into the previous one instead of standing
|
||||
* alone. A tiny tail group is the weak point: a burst landing in a
|
||||
* 4-block tail hits each of its blocks with L/4 bytes instead of
|
||||
* L/64, which is exactly why the first measurement showed 0.94
|
||||
* instead of 1.00 on 64-byte bursts (the 68-block blob ends in a
|
||||
* 4-block tail). Merging makes every group >= depth (the last may
|
||||
* exceed it); when nblocks <= depth there is a single group. */
|
||||
static void permute(const uint8_t *in, uint8_t *out, const size_t *blocks,
|
||||
size_t nblocks, int depth, int forward)
|
||||
{
|
||||
size_t *start = (size_t *)malloc((nblocks + 1) * sizeof(size_t));
|
||||
if (!start)
|
||||
return;
|
||||
start[0] = 0;
|
||||
for (size_t i = 0; i < nblocks; i++)
|
||||
start[i + 1] = start[i] + blocks[i];
|
||||
|
||||
/* group boundaries: groups of `depth`, last partial group merged
|
||||
into the previous one */
|
||||
size_t g0 = 0;
|
||||
while (g0 < nblocks) {
|
||||
size_t remain = nblocks - g0;
|
||||
size_t g = remain < (size_t)depth ? remain : (size_t)depth;
|
||||
/* If this would leave a short tail after this group, extend
|
||||
this group to absorb the tail. (Invariant: a short tail
|
||||
never survives an iteration, so no group is ever < depth
|
||||
except when the whole blob is.) */
|
||||
if (remain > (size_t)depth && remain - (size_t)depth < (size_t)depth)
|
||||
g = remain;
|
||||
size_t maxlen = 0;
|
||||
for (size_t j = 0; j < g; j++)
|
||||
if (blocks[g0 + j] > maxlen)
|
||||
maxlen = blocks[g0 + j];
|
||||
size_t goff = start[g0];
|
||||
size_t pos = 0;
|
||||
for (size_t c = 0; c < maxlen; c++) {
|
||||
for (size_t j = 0; j < g; j++) {
|
||||
if (c >= blocks[g0 + j])
|
||||
continue;
|
||||
size_t src = start[g0 + j] + c;
|
||||
size_t dst = goff + pos;
|
||||
if (forward)
|
||||
out[dst] = in[src];
|
||||
else
|
||||
out[src] = in[dst];
|
||||
pos++;
|
||||
}
|
||||
}
|
||||
g0 += g;
|
||||
}
|
||||
free(start);
|
||||
}
|
||||
|
||||
static size_t intlv_encode(ecc_codec_t *c, const uint8_t *data, size_t len,
|
||||
uint8_t **out)
|
||||
{
|
||||
intlv_priv_t *p = (intlv_priv_t *)c->priv;
|
||||
uint8_t *enc = NULL;
|
||||
size_t slen = p->inner->encode(p->inner, data, len, &enc);
|
||||
if (!slen)
|
||||
return 0;
|
||||
/* block layout of the inner encoding */
|
||||
size_t bd = p->inner->block_data;
|
||||
size_t nblocks = (len + bd - 1) / bd;
|
||||
size_t *blocks = (size_t *)malloc(nblocks * sizeof(size_t));
|
||||
if (!blocks) {
|
||||
free(enc);
|
||||
return 0;
|
||||
}
|
||||
/* stored length of block i: full blocks first, last may be short.
|
||||
The inner codec is bch_encode with a pinned poly, so stored
|
||||
length is a pure function of the block's data length. Recover
|
||||
it by splitting slen: all full blocks share one length. */
|
||||
size_t off = 0;
|
||||
for (size_t i = 0; i < nblocks; i++) {
|
||||
size_t dlen = len - i * bd < bd ? len - i * bd : bd;
|
||||
/* stored bytes for dlen data bytes under the pinned poly:
|
||||
ceil((8*dlen + r)/8); r = t*13 for m=13 */
|
||||
size_t r = (size_t)p->t * 13;
|
||||
blocks[i] = (8 * dlen + r + 7) / 8;
|
||||
off += blocks[i];
|
||||
}
|
||||
if (off != slen) { /* should not happen; bail out cleanly */
|
||||
free(blocks);
|
||||
free(enc);
|
||||
return 0;
|
||||
}
|
||||
uint8_t *buf = (uint8_t *)malloc(slen);
|
||||
if (!buf) {
|
||||
free(blocks);
|
||||
free(enc);
|
||||
return 0;
|
||||
}
|
||||
permute(enc, buf, blocks, nblocks, p->depth, 1);
|
||||
free(blocks);
|
||||
free(enc);
|
||||
c->overhead = p->inner->overhead;
|
||||
*out = buf;
|
||||
return slen;
|
||||
}
|
||||
|
||||
static int intlv_decode(ecc_codec_t *c, const uint8_t *stored, size_t slen,
|
||||
size_t orig_len, uint8_t *out, long *corrected)
|
||||
{
|
||||
intlv_priv_t *p = (intlv_priv_t *)c->priv;
|
||||
size_t bd = p->inner->block_data;
|
||||
size_t nblocks = (orig_len + bd - 1) / bd;
|
||||
size_t *blocks = (size_t *)malloc(nblocks * sizeof(size_t));
|
||||
if (!blocks)
|
||||
return -1;
|
||||
size_t off = 0;
|
||||
for (size_t i = 0; i < nblocks; i++) {
|
||||
size_t dlen = orig_len - i * bd < bd ? orig_len - i * bd : bd;
|
||||
size_t r = (size_t)p->t * 13;
|
||||
blocks[i] = (8 * dlen + r + 7) / 8;
|
||||
off += blocks[i];
|
||||
}
|
||||
if (off != slen) {
|
||||
free(blocks);
|
||||
return -1;
|
||||
}
|
||||
uint8_t *deint = (uint8_t *)malloc(slen);
|
||||
if (!deint) {
|
||||
free(blocks);
|
||||
return -1;
|
||||
}
|
||||
permute(stored, deint, blocks, nblocks, p->depth, 0);
|
||||
free(blocks);
|
||||
int rc = p->inner->decode(p->inner, deint, slen, orig_len, out,
|
||||
corrected);
|
||||
free(deint);
|
||||
return rc;
|
||||
}
|
||||
|
||||
static int intlv_recover(ecc_codec_t *c, const uint8_t *stored, size_t slen,
|
||||
size_t orig_len, const uint8_t want_sha[32],
|
||||
uint8_t *out)
|
||||
{
|
||||
intlv_priv_t *p = (intlv_priv_t *)c->priv;
|
||||
size_t bd = p->inner->block_data;
|
||||
size_t nblocks = (orig_len + bd - 1) / bd;
|
||||
size_t *blocks = (size_t *)malloc(nblocks * sizeof(size_t));
|
||||
if (!blocks)
|
||||
return -1;
|
||||
size_t off = 0;
|
||||
for (size_t i = 0; i < nblocks; i++) {
|
||||
size_t dlen = orig_len - i * bd < bd ? orig_len - i * bd : bd;
|
||||
size_t r = (size_t)p->t * 13;
|
||||
blocks[i] = (8 * dlen + r + 7) / 8;
|
||||
off += blocks[i];
|
||||
}
|
||||
if (off != slen) {
|
||||
free(blocks);
|
||||
return -1;
|
||||
}
|
||||
uint8_t *deint = (uint8_t *)malloc(slen);
|
||||
if (!deint) {
|
||||
free(blocks);
|
||||
return -1;
|
||||
}
|
||||
permute(stored, deint, blocks, nblocks, p->depth, 0);
|
||||
free(blocks);
|
||||
int rc = p->inner->recover_verified
|
||||
? p->inner->recover_verified(p->inner, deint, slen, orig_len,
|
||||
want_sha, out)
|
||||
: -1;
|
||||
free(deint);
|
||||
return rc;
|
||||
}
|
||||
|
||||
static void intlv_destroy(ecc_codec_t *c)
|
||||
{
|
||||
intlv_priv_t *p = (intlv_priv_t *)c->priv;
|
||||
if (p->inner)
|
||||
p->inner->destroy(p->inner);
|
||||
free(p);
|
||||
free((void *)c->name);
|
||||
free(c);
|
||||
}
|
||||
|
||||
ecc_codec_t *interleave_new(int depth, int t)
|
||||
{
|
||||
ecc_codec_t *inner = bch_1k_new(t);
|
||||
if (!inner)
|
||||
return NULL;
|
||||
ecc_codec_t *c = (ecc_codec_t *)calloc(1, sizeof(*c));
|
||||
intlv_priv_t *p = (intlv_priv_t *)calloc(1, sizeof(*p));
|
||||
if (!c || !p) {
|
||||
free(c);
|
||||
free(p);
|
||||
inner->destroy(inner);
|
||||
return NULL;
|
||||
}
|
||||
char *name = (char *)malloc(32);
|
||||
if (!name) {
|
||||
free(c);
|
||||
free(p);
|
||||
inner->destroy(inner);
|
||||
return NULL;
|
||||
}
|
||||
snprintf(name, 32, "intlv-d%d-bch1k-t%d", depth, t);
|
||||
p->inner = inner;
|
||||
p->depth = depth;
|
||||
p->t = t;
|
||||
c->name = name;
|
||||
c->desc = "byte interleaver over small-block BCH";
|
||||
c->block_data = inner->block_data;
|
||||
c->encode = intlv_encode;
|
||||
c->decode = intlv_decode;
|
||||
c->recover_verified = intlv_recover;
|
||||
c->destroy = intlv_destroy;
|
||||
c->priv = p;
|
||||
return c;
|
||||
}
|
||||
+565
@@ -0,0 +1,565 @@
|
||||
/* ldpc.c - regular LDPC codec for the experiments harness.
|
||||
*
|
||||
* Two operating points, both n=8192 bits, column weight 3:
|
||||
* ldpc-r90: m=768 checks, row weight 32, k=7424 bits (928 B),
|
||||
* rate 0.90625, overhead 10.34%.
|
||||
* ldpc-r95: m=384 checks, row weight 64, k=7808 bits (976 B),
|
||||
* rate 0.953125, overhead 4.92%.
|
||||
*
|
||||
* Construction: random regular parity-check matrix (configuration
|
||||
* model with 4-cycle rejection), fixed seed, so the code is identical
|
||||
* on every run and every server. Systematic encoding by Gauss-Jordan
|
||||
* reduction of H to [I | P] (one-time, at codec creation); decoding
|
||||
* is normalized min-sum belief propagation (factor 0.8), max 50
|
||||
* iterations, early stop when the syndrome is zero. Channel LLR uses
|
||||
* a fixed nominal crossover p0 = 1e-3 (the decoder does not know the
|
||||
* true BER; this is the honest setting for a storage channel).
|
||||
*
|
||||
* A blob is split into blocks of k data bytes; the last block is
|
||||
* zero-padded to k bytes (padding is discarded on decode). Stored
|
||||
* length per block is exactly n/8 = 1024 bytes.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <math.h>
|
||||
|
||||
#include "ecc_iface.h"
|
||||
|
||||
#define LDPC_N 8192
|
||||
#define LDPC_WC 3
|
||||
#define LDPC_MAX_ITER 50
|
||||
#define LDPC_MS_NORM 0.8f
|
||||
#define LDPC_P0 1e-3
|
||||
|
||||
typedef struct {
|
||||
int m; /* checks */
|
||||
int wr; /* row weight */
|
||||
int k; /* data bits */
|
||||
int kbytes; /* data bytes per block */
|
||||
int nedges;
|
||||
int *chk_var; /* m * wr: vars of each check */
|
||||
int *var_chk; /* n * wc: checks of each var */
|
||||
int *chk_edge; /* m * wr: edge id (var*wc+w) of each check entry */
|
||||
int *pivot_col; /* m: pivot column of each RREF row */
|
||||
uint64_t *enc_rows; /* m * kwords: RREF rows over data positions */
|
||||
int kwords;
|
||||
int *col_of_dp; /* k: column holding data position i */
|
||||
float *msg_vc; /* var->check, nedges */
|
||||
float *msg_cv; /* check->var, nedges */
|
||||
float *llr_ch; /* n */
|
||||
uint8_t *hard; /* n */
|
||||
} ldpc_t;
|
||||
|
||||
static void free_ldpc(ldpc_t *L)
|
||||
{
|
||||
if (!L)
|
||||
return;
|
||||
free(L->chk_var);
|
||||
free(L->var_chk);
|
||||
free(L->chk_edge);
|
||||
free(L->pivot_col);
|
||||
free(L->enc_rows);
|
||||
free(L->col_of_dp);
|
||||
free(L->msg_vc);
|
||||
free(L->msg_cv);
|
||||
free(L->llr_ch);
|
||||
free(L->hard);
|
||||
free(L);
|
||||
}
|
||||
|
||||
static uint64_t lrs = 0x243f6a8885a308d3ULL;
|
||||
static inline uint64_t lxr(void)
|
||||
{
|
||||
lrs ^= lrs << 13;
|
||||
lrs ^= lrs >> 7;
|
||||
lrs ^= lrs << 17;
|
||||
return lrs;
|
||||
}
|
||||
|
||||
/* ---- construction: progressive edge growth (PEG) ----
|
||||
* Edge by edge, each new edge of variable node v connects to the
|
||||
* check node farthest from v in the graph built so far (unreached
|
||||
* checks count as infinitely far), tie-broken by lowest check degree.
|
||||
* PEG never deadlocks (there is always a farthest check) and
|
||||
* maximizes girth by construction -- unlike greedy 4-cycle
|
||||
* rejection, which stalls in the endgame when the remaining stub
|
||||
* rows all close short cycles. Fallback: if every farthest check is
|
||||
* already full (cannot happen with balanced degrees, but be safe),
|
||||
* take the lowest-degree check overall. */
|
||||
static int build_H(ldpc_t *L, uint64_t seed)
|
||||
{
|
||||
int m = L->m, n = LDPC_N, wc = LDPC_WC, wr = L->wr;
|
||||
int *chk_deg = (int *)calloc((size_t)m, sizeof(int));
|
||||
int *var_deg = (int *)calloc((size_t)n, sizeof(int));
|
||||
int *dist = (int *)malloc((size_t)(n + m) * sizeof(int));
|
||||
int *queue = (int *)malloc((size_t)(n + m) * sizeof(int));
|
||||
if (!chk_deg || !var_deg || !dist || !queue) {
|
||||
free(chk_deg);
|
||||
free(var_deg);
|
||||
free(dist);
|
||||
free(queue);
|
||||
return -1;
|
||||
}
|
||||
lrs = seed;
|
||||
(void)lxr; /* seed only matters for tie-breaking below */
|
||||
for (int v = 0; v < n; v++) {
|
||||
for (int e = 0; e < wc; e++) {
|
||||
/* BFS from v over the graph built so far. Node ids:
|
||||
0..n-1 variables, n..n+m-1 checks. */
|
||||
for (int i = 0; i < n + m; i++)
|
||||
dist[i] = -1;
|
||||
int qh = 0, qt = 0;
|
||||
dist[v] = 0;
|
||||
queue[qt++] = v;
|
||||
int found_checks = 0;
|
||||
while (qh < qt && found_checks < m) {
|
||||
int u = queue[qh++];
|
||||
int d = dist[u];
|
||||
if (u < n) {
|
||||
for (int w = 0; w < var_deg[u]; w++) {
|
||||
int nid = n + L->var_chk[u * wc + w];
|
||||
if (dist[nid] < 0) {
|
||||
dist[nid] = d + 1;
|
||||
queue[qt++] = nid;
|
||||
found_checks++;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
int ch = u - n;
|
||||
for (int k = 0; k < chk_deg[ch]; k++) {
|
||||
int vv = L->chk_var[ch * wr + k];
|
||||
if (dist[vv] < 0) {
|
||||
dist[vv] = d + 1;
|
||||
queue[qt++] = vv;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/* farthest distance among reached checks (-1 = unreached) */
|
||||
int bestd = -2, have_unreached = 0;
|
||||
for (int ch = 0; ch < m; ch++) {
|
||||
int d = dist[n + ch];
|
||||
if (d < 0) {
|
||||
have_unreached = 1;
|
||||
} else if (d > bestd) {
|
||||
bestd = d;
|
||||
}
|
||||
}
|
||||
int best = -1, bestdeg = wr + 1;
|
||||
for (int ch = 0; ch < m; ch++) {
|
||||
int d = dist[n + ch];
|
||||
int far = have_unreached ? (d < 0) : (d == bestd);
|
||||
if (!far)
|
||||
continue;
|
||||
if (chk_deg[ch] < wr && chk_deg[ch] < bestdeg) {
|
||||
bestdeg = chk_deg[ch];
|
||||
best = ch;
|
||||
}
|
||||
}
|
||||
if (best < 0) {
|
||||
/* fallback: lowest-degree check anywhere */
|
||||
for (int ch = 0; ch < m; ch++)
|
||||
if (chk_deg[ch] < wr && chk_deg[ch] < bestdeg) {
|
||||
bestdeg = chk_deg[ch];
|
||||
best = ch;
|
||||
}
|
||||
}
|
||||
if (best < 0) {
|
||||
free(chk_deg);
|
||||
free(var_deg);
|
||||
free(dist);
|
||||
free(queue);
|
||||
return -1;
|
||||
}
|
||||
L->var_chk[v * wc + var_deg[v]++] = best;
|
||||
L->chk_var[best * wr + chk_deg[best]++] = v;
|
||||
}
|
||||
}
|
||||
free(chk_deg);
|
||||
free(var_deg);
|
||||
free(dist);
|
||||
free(queue);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* ---- Gauss-Jordan: H -> RREF, record pivot columns + enc rows ---- */
|
||||
static int gauss_jordan(ldpc_t *L)
|
||||
{
|
||||
int m = L->m, n = LDPC_N;
|
||||
int words = (n + 63) / 64;
|
||||
uint64_t *H = (uint64_t *)calloc((size_t)m * words, sizeof(uint64_t));
|
||||
if (!H)
|
||||
return -1;
|
||||
for (int r = 0; r < m; r++)
|
||||
for (int k = 0; k < L->wr; k++) {
|
||||
int c = L->chk_var[r * L->wr + k];
|
||||
H[(size_t)r * words + c / 64] |= 1ULL << (c % 64);
|
||||
}
|
||||
int prow = 0;
|
||||
for (int col = 0; col < n && prow < m; col++) {
|
||||
int sel = -1;
|
||||
for (int r = prow; r < m; r++)
|
||||
if ((H[(size_t)r * words + col / 64] >> (col % 64)) & 1ULL) {
|
||||
sel = r;
|
||||
break;
|
||||
}
|
||||
if (sel < 0)
|
||||
continue;
|
||||
if (sel != prow) {
|
||||
for (int w = 0; w < words; w++) {
|
||||
uint64_t t = H[(size_t)sel * words + w];
|
||||
H[(size_t)sel * words + w] = H[(size_t)prow * words + w];
|
||||
H[(size_t)prow * words + w] = t;
|
||||
}
|
||||
}
|
||||
for (int r = 0; r < m; r++) {
|
||||
if (r != prow &&
|
||||
((H[(size_t)r * words + col / 64] >> (col % 64)) & 1ULL)) {
|
||||
for (int w = 0; w < words; w++)
|
||||
H[(size_t)r * words + w] ^=
|
||||
H[(size_t)prow * words + w];
|
||||
}
|
||||
}
|
||||
L->pivot_col[prow++] = col;
|
||||
}
|
||||
if (prow != m) {
|
||||
free(H);
|
||||
return -1; /* H not full rank */
|
||||
}
|
||||
int *is_pivot = (int *)calloc((size_t)n, sizeof(int));
|
||||
if (!is_pivot) {
|
||||
free(H);
|
||||
return -1;
|
||||
}
|
||||
for (int i = 0; i < m; i++)
|
||||
is_pivot[L->pivot_col[i]] = 1;
|
||||
L->col_of_dp = (int *)malloc((size_t)L->k * sizeof(int));
|
||||
if (!L->col_of_dp) {
|
||||
free(H);
|
||||
free(is_pivot);
|
||||
return -1;
|
||||
}
|
||||
int dp = 0;
|
||||
for (int c = 0; c < n; c++)
|
||||
if (!is_pivot[c])
|
||||
L->col_of_dp[dp++] = c;
|
||||
if (dp != L->k) {
|
||||
free(H);
|
||||
free(is_pivot);
|
||||
return -1;
|
||||
}
|
||||
L->kwords = (L->k + 63) / 64;
|
||||
L->enc_rows = (uint64_t *)calloc((size_t)m * L->kwords,
|
||||
sizeof(uint64_t));
|
||||
if (!L->enc_rows) {
|
||||
free(H);
|
||||
free(is_pivot);
|
||||
return -1;
|
||||
}
|
||||
int *data_pos = (int *)malloc((size_t)n * sizeof(int));
|
||||
if (!data_pos) {
|
||||
free(H);
|
||||
free(is_pivot);
|
||||
return -1;
|
||||
}
|
||||
dp = 0;
|
||||
for (int c = 0; c < n; c++)
|
||||
data_pos[c] = is_pivot[c] ? -1 : dp++;
|
||||
for (int i = 0; i < m; i++) {
|
||||
for (int c = 0; c < n; c++) {
|
||||
if (is_pivot[c])
|
||||
continue;
|
||||
if ((H[(size_t)i * words + c / 64] >> (c % 64)) & 1ULL) {
|
||||
int p = data_pos[c];
|
||||
L->enc_rows[(size_t)i * L->kwords + p / 64] |=
|
||||
1ULL << (p % 64);
|
||||
}
|
||||
}
|
||||
}
|
||||
free(data_pos);
|
||||
free(H);
|
||||
free(is_pivot);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* bit helpers: MSB-first within each byte */
|
||||
static inline int get_bit(const uint8_t *buf, int i)
|
||||
{
|
||||
return (buf[i / 8] >> (7 - (i % 8))) & 1;
|
||||
}
|
||||
static inline void set_bit(uint8_t *buf, int i, int v)
|
||||
{
|
||||
if (v)
|
||||
buf[i / 8] |= (uint8_t)(1u << (7 - (i % 8)));
|
||||
else
|
||||
buf[i / 8] &= (uint8_t) ~(1u << (7 - (i % 8)));
|
||||
}
|
||||
|
||||
static size_t ldpc_encode(ecc_codec_t *c, const uint8_t *data, size_t len,
|
||||
uint8_t **out)
|
||||
{
|
||||
ldpc_t *L = (ldpc_t *)c->priv;
|
||||
size_t nblocks = (len + (size_t)L->kbytes - 1) / (size_t)L->kbytes;
|
||||
size_t slen = nblocks * (LDPC_N / 8);
|
||||
uint8_t *buf = (uint8_t *)calloc(slen ? slen : 1, 1);
|
||||
if (!buf)
|
||||
return 0;
|
||||
uint8_t *dbytes = (uint8_t *)calloc((size_t)L->kbytes, 1);
|
||||
uint64_t *dw = (uint64_t *)malloc((size_t)L->kwords * sizeof(uint64_t));
|
||||
if (!dbytes || !dw) {
|
||||
free(buf);
|
||||
free(dbytes);
|
||||
free(dw);
|
||||
return 0;
|
||||
}
|
||||
for (size_t b = 0; b < nblocks; b++) {
|
||||
size_t dlen = len - b * (size_t)L->kbytes < (size_t)L->kbytes
|
||||
? len - b * (size_t)L->kbytes
|
||||
: (size_t)L->kbytes;
|
||||
memset(dbytes, 0, (size_t)L->kbytes);
|
||||
memcpy(dbytes, data + b * (size_t)L->kbytes, dlen);
|
||||
/* data as words, bit i of the block -> word i/64, bit i%64 */
|
||||
memset(dw, 0, (size_t)L->kwords * sizeof(uint64_t));
|
||||
for (int i = 0; i < L->k; i++)
|
||||
if (get_bit(dbytes, i))
|
||||
dw[i / 64] |= 1ULL << (i % 64);
|
||||
uint8_t *cw = buf + b * (LDPC_N / 8);
|
||||
for (int i = 0; i < L->k; i++)
|
||||
set_bit(cw, L->col_of_dp[i], get_bit(dbytes, i));
|
||||
for (int i = 0; i < L->m; i++) {
|
||||
const uint64_t *row = L->enc_rows + (size_t)i * L->kwords;
|
||||
int acc = 0;
|
||||
for (int w = 0; w < L->kwords; w++)
|
||||
acc ^= __builtin_parityll(row[w] & dw[w]);
|
||||
set_bit(cw, L->pivot_col[i], acc);
|
||||
}
|
||||
}
|
||||
free(dbytes);
|
||||
free(dw);
|
||||
c->overhead = len ? (double)slen / (double)len - 1.0 : 0.0;
|
||||
*out = buf;
|
||||
return slen;
|
||||
}
|
||||
|
||||
static int ldpc_decode_block(ldpc_t *L, const uint8_t *cw_in,
|
||||
uint8_t *data_out, long *corrected_out)
|
||||
{
|
||||
int n = LDPC_N, m = L->m, wc = LDPC_WC, wr = L->wr;
|
||||
float L0 = (float)log((1.0 - LDPC_P0) / LDPC_P0);
|
||||
for (int i = 0; i < n; i++) {
|
||||
L->llr_ch[i] = get_bit(cw_in, i) ? -L0 : L0;
|
||||
for (int w = 0; w < wc; w++)
|
||||
L->msg_vc[i * wc + w] = L->llr_ch[i];
|
||||
}
|
||||
int converged = 0;
|
||||
for (int it = 0; it < LDPC_MAX_ITER && !converged; it++) {
|
||||
/* check update: two-minimum min-sum, via chk_edge ids */
|
||||
for (int j = 0; j < m; j++) {
|
||||
float min1 = 1e30f, min2 = 1e30f;
|
||||
int argmin1 = -1, sign = 1;
|
||||
for (int k = 0; k < wr; k++) {
|
||||
int e = L->chk_edge[j * wr + k];
|
||||
float x = L->msg_vc[e];
|
||||
float a = fabsf(x);
|
||||
if (a < min1) {
|
||||
min2 = min1;
|
||||
min1 = a;
|
||||
argmin1 = k;
|
||||
} else if (a < min2) {
|
||||
min2 = a;
|
||||
}
|
||||
if (x < 0)
|
||||
sign = -sign;
|
||||
}
|
||||
for (int k = 0; k < wr; k++) {
|
||||
int e = L->chk_edge[j * wr + k];
|
||||
float x = L->msg_vc[e];
|
||||
int s = sign;
|
||||
if (x < 0)
|
||||
s = -s;
|
||||
float mag = (k == argmin1 ? min2 : min1) * LDPC_MS_NORM;
|
||||
L->msg_cv[e] = s > 0 ? mag : -mag;
|
||||
}
|
||||
}
|
||||
/* hard decision + syndrome check */
|
||||
converged = 1;
|
||||
for (int i = 0; i < n; i++) {
|
||||
float tot = L->llr_ch[i];
|
||||
for (int w = 0; w < wc; w++)
|
||||
tot += L->msg_cv[i * wc + w];
|
||||
L->hard[i] = tot < 0 ? 1 : 0;
|
||||
}
|
||||
for (int j = 0; j < m; j++) {
|
||||
int p = 0;
|
||||
for (int k = 0; k < wr; k++)
|
||||
p ^= L->hard[L->chk_var[j * wr + k]];
|
||||
if (p) {
|
||||
converged = 0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (converged)
|
||||
break;
|
||||
/* var->check messages for the next iteration */
|
||||
for (int i = 0; i < n; i++)
|
||||
for (int w = 0; w < wc; w++) {
|
||||
float tot = L->llr_ch[i];
|
||||
for (int w2 = 0; w2 < wc; w2++)
|
||||
if (w2 != w)
|
||||
tot += L->msg_cv[i * wc + w2];
|
||||
L->msg_vc[i * wc + w] = tot;
|
||||
}
|
||||
}
|
||||
if (!converged)
|
||||
return -1;
|
||||
long corr = 0;
|
||||
for (int i = 0; i < n; i++)
|
||||
if (L->hard[i] != get_bit(cw_in, i))
|
||||
corr++;
|
||||
if (corrected_out)
|
||||
*corrected_out = corr;
|
||||
int *is_pivot = (int *)calloc((size_t)n, sizeof(int));
|
||||
if (!is_pivot)
|
||||
return -1;
|
||||
for (int i = 0; i < m; i++)
|
||||
is_pivot[L->pivot_col[i]] = 1;
|
||||
int dp = 0;
|
||||
memset(data_out, 0, (size_t)L->kbytes);
|
||||
for (int col = 0; col < n; col++)
|
||||
if (!is_pivot[col])
|
||||
set_bit(data_out, dp++, L->hard[col]);
|
||||
free(is_pivot);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int ldpc_decode(ecc_codec_t *c, const uint8_t *stored, size_t slen,
|
||||
size_t orig_len, uint8_t *out, long *corrected)
|
||||
{
|
||||
ldpc_t *L = (ldpc_t *)c->priv;
|
||||
size_t nblocks = (orig_len + (size_t)L->kbytes - 1) / (size_t)L->kbytes;
|
||||
if (slen != nblocks * (LDPC_N / 8))
|
||||
return -1;
|
||||
long corr = 0;
|
||||
for (size_t b = 0; b < nblocks; b++) {
|
||||
uint8_t *db = (uint8_t *)malloc((size_t)L->kbytes);
|
||||
if (!db)
|
||||
return -1;
|
||||
long bc = 0;
|
||||
int rc = ldpc_decode_block(L, stored + b * (LDPC_N / 8), db, &bc);
|
||||
if (rc != 0) {
|
||||
free(db);
|
||||
if (corrected)
|
||||
*corrected = -1;
|
||||
return -1;
|
||||
}
|
||||
corr += bc;
|
||||
size_t dlen = orig_len - b * (size_t)L->kbytes < (size_t)L->kbytes
|
||||
? orig_len - b * (size_t)L->kbytes
|
||||
: (size_t)L->kbytes;
|
||||
memcpy(out + b * (size_t)L->kbytes, db, dlen);
|
||||
free(db);
|
||||
}
|
||||
if (corrected)
|
||||
*corrected = corr;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void ldpc_destroy(ecc_codec_t *c)
|
||||
{
|
||||
ldpc_t *L = (ldpc_t *)c->priv;
|
||||
free_ldpc(L);
|
||||
free((void *)c->name);
|
||||
free(c);
|
||||
}
|
||||
|
||||
ecc_codec_t *ldpc_new(int rate_pct)
|
||||
{
|
||||
int m, wr;
|
||||
const char *tag;
|
||||
if (rate_pct == 90) {
|
||||
m = 768;
|
||||
wr = 32;
|
||||
tag = "ldpc-r90";
|
||||
} else if (rate_pct == 95) {
|
||||
m = 384;
|
||||
wr = 64;
|
||||
tag = "ldpc-r95";
|
||||
} else {
|
||||
return NULL;
|
||||
}
|
||||
ldpc_t *L = (ldpc_t *)calloc(1, sizeof(*L));
|
||||
if (!L)
|
||||
return NULL;
|
||||
L->m = m;
|
||||
L->wr = wr;
|
||||
L->k = LDPC_N - m;
|
||||
L->kbytes = L->k / 8;
|
||||
L->nedges = LDPC_N * LDPC_WC;
|
||||
L->chk_var = (int *)malloc((size_t)m * wr * sizeof(int));
|
||||
L->var_chk = (int *)malloc((size_t)LDPC_N * LDPC_WC * sizeof(int));
|
||||
L->chk_edge = (int *)malloc((size_t)m * wr * sizeof(int));
|
||||
L->pivot_col = (int *)malloc((size_t)m * sizeof(int));
|
||||
L->msg_vc = (float *)malloc((size_t)L->nedges * sizeof(float));
|
||||
L->msg_cv = (float *)malloc((size_t)L->nedges * sizeof(float));
|
||||
L->llr_ch = (float *)malloc((size_t)LDPC_N * sizeof(float));
|
||||
L->hard = (uint8_t *)malloc((size_t)LDPC_N);
|
||||
if (!L->chk_var || !L->var_chk || !L->chk_edge || !L->pivot_col ||
|
||||
!L->msg_vc || !L->msg_cv || !L->llr_ch || !L->hard) {
|
||||
free_ldpc(L);
|
||||
return NULL;
|
||||
}
|
||||
int ok = -1;
|
||||
int attempt_used = -1;
|
||||
for (int attempt = 0; attempt < 10 && ok != 0; attempt++) {
|
||||
ok = build_H(L, 0x9e3779b97f4a7c15ULL +
|
||||
(uint64_t)attempt * 0x100000001b3ULL);
|
||||
attempt_used = attempt;
|
||||
}
|
||||
if (getenv("LDPC_DEBUG"))
|
||||
fprintf(stderr, "ldpc: build_H ok=%d attempts=%d\n", ok,
|
||||
attempt_used + 1);
|
||||
if (ok != 0) {
|
||||
free_ldpc(L);
|
||||
return NULL;
|
||||
}
|
||||
int gj = gauss_jordan(L);
|
||||
if (getenv("LDPC_DEBUG"))
|
||||
fprintf(stderr, "ldpc: gauss_jordan=%d\n", gj);
|
||||
if (gj != 0) {
|
||||
free_ldpc(L);
|
||||
return NULL;
|
||||
}
|
||||
/* edge ids for the decoder: chk_edge[j*wr+k] = var*wc+w */
|
||||
for (int j = 0; j < m; j++)
|
||||
for (int k = 0; k < wr; k++) {
|
||||
int v = L->chk_var[j * wr + k];
|
||||
int e = -1;
|
||||
for (int w = 0; w < LDPC_WC; w++)
|
||||
if (L->var_chk[v * LDPC_WC + w] == j)
|
||||
e = v * LDPC_WC + w;
|
||||
L->chk_edge[j * wr + k] = e;
|
||||
}
|
||||
|
||||
ecc_codec_t *c = (ecc_codec_t *)calloc(1, sizeof(*c));
|
||||
if (!c) {
|
||||
free_ldpc(L);
|
||||
return NULL;
|
||||
}
|
||||
char *name = (char *)malloc(16);
|
||||
if (!name) {
|
||||
free_ldpc(L);
|
||||
free(c);
|
||||
return NULL;
|
||||
}
|
||||
snprintf(name, 16, "%s", tag);
|
||||
c->name = name;
|
||||
c->desc = "regular LDPC, min-sum belief propagation";
|
||||
c->block_data = (size_t)L->kbytes;
|
||||
c->encode = ldpc_encode;
|
||||
c->decode = ldpc_decode;
|
||||
c->recover_verified = NULL;
|
||||
c->destroy = ldpc_destroy;
|
||||
c->priv = L;
|
||||
return c;
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
/* ldpc_diag.c - diagnostic for the LDPC codec (NOT part of bench).
|
||||
* Encodes one fixed block, flips exactly k bits (k = 0..KMAX), decodes,
|
||||
* and reports the failure count per k. This separates "decoder bug"
|
||||
* (fails even at k=1..3) from "code weakness" (fails only near the
|
||||
* expected threshold). Usage: ldpc_diag <r90|r95> [kmax] [trials]
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdint.h>
|
||||
#include "ecc_iface.h"
|
||||
|
||||
ecc_codec_t *ldpc_new(int rate_pct);
|
||||
|
||||
static uint64_t rs = 0xabcdef1234567ULL;
|
||||
static inline uint64_t xr(void)
|
||||
{
|
||||
rs ^= rs << 13;
|
||||
rs ^= rs >> 7;
|
||||
rs ^= rs << 17;
|
||||
return rs;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
int rate = 90;
|
||||
int kmax = 24, trials = 100;
|
||||
if (argc > 1)
|
||||
rate = atoi(argv[1] + 1); /* "r90" -> 90 */
|
||||
if (argc > 2)
|
||||
kmax = atoi(argv[2]);
|
||||
if (argc > 3)
|
||||
trials = atoi(argv[3]);
|
||||
ecc_codec_t *c = ldpc_new(rate);
|
||||
if (!c) {
|
||||
fprintf(stderr, "ldpc_new failed\n");
|
||||
return 2;
|
||||
}
|
||||
size_t dlen = c->block_data;
|
||||
uint8_t *data = (uint8_t *)malloc(dlen);
|
||||
uint8_t *out = (uint8_t *)malloc(dlen);
|
||||
for (size_t i = 0; i < dlen; i++)
|
||||
data[i] = (uint8_t)(xr() & 0xff);
|
||||
uint8_t *stored = NULL;
|
||||
size_t slen = c->encode(c, data, dlen, &stored);
|
||||
if (!slen) {
|
||||
fprintf(stderr, "encode failed\n");
|
||||
return 2;
|
||||
}
|
||||
printf("rate=%d block_data=%zu stored=%zu overhead=%.2f%%\n", rate,
|
||||
dlen, slen, c->overhead * 100.0);
|
||||
uint8_t *rx = (uint8_t *)malloc(slen);
|
||||
for (int k = 0; k <= kmax; k++) {
|
||||
int fails = 0;
|
||||
for (int t = 0; t < trials; t++) {
|
||||
memcpy(rx, stored, slen);
|
||||
/* flip k distinct random bits */
|
||||
for (int f = 0; f < k; f++) {
|
||||
size_t p = (size_t)(xr() % (slen * 8));
|
||||
rx[p / 8] ^= (uint8_t)(1u << (7 - (p % 8)));
|
||||
}
|
||||
long corr = -1;
|
||||
int rc = c->decode(c, rx, slen, dlen, out, &corr);
|
||||
if (rc != 0 || memcmp(out, data, dlen) != 0)
|
||||
fails++;
|
||||
}
|
||||
printf("k=%2d fails=%d/%d\n", k, fails, trials);
|
||||
fflush(stdout);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
Executable
+27
@@ -0,0 +1,27 @@
|
||||
#!/bin/bash
|
||||
# mkcorpora.sh - build the experiment corpora in exp/corpora/.
|
||||
# text.raw / text.lz : English-ish text (docs + sources)
|
||||
# bin.raw / bin.lz : ELF binaries
|
||||
# rand.raw / rand.lz : seeded pseudo-random bytes (incompressible)
|
||||
# lz files are lzip -9 of the raw files: that is what lzply actually
|
||||
# protects (the compressed blob), plus the raw files for stored entries.
|
||||
set -e
|
||||
cd "$(dirname "$0")/corpora"
|
||||
# text: repo docs/sources + system docs
|
||||
{ find /opt/lzply-exp-ecc -name "*.md" -o -name "*.c" -o -name "*.h" | sort | xargs cat
|
||||
find /usr/share/doc -type f -size -200k 2>/dev/null | head -200 | sort | xargs cat 2>/dev/null
|
||||
find /usr/include -name "*.h" 2>/dev/null | head -300 | sort | xargs cat 2>/dev/null
|
||||
} > text.raw
|
||||
head -c 4194304 text.raw > text4m.raw && mv text4m.raw text.raw
|
||||
# binaries: ELF files from /bin and /usr/bin
|
||||
{ for f in /bin/* /usr/bin/*; do
|
||||
[ -f "$f" ] && head -c1 "$f" | grep -q . && file "$f" 2>/dev/null | grep -q ELF && cat "$f"
|
||||
done
|
||||
} > bin.raw 2>/dev/null
|
||||
head -c 4194304 bin.raw > bin4m.raw && mv bin4m.raw bin.raw
|
||||
# random: seeded python (reproducible on both servers)
|
||||
python3 -c "import random; random.seed(1234); open(\"rand.raw\",\"wb\").write(bytes(random.getrandbits(8) for _ in range(4194304)))"
|
||||
for f in text bin rand; do
|
||||
lzip -9 -f -c "$f.raw" > "$f.lz" 2>/dev/null || lzip -9 -c "$f.raw" > "$f.lz"
|
||||
done
|
||||
ls -la
|
||||
@@ -0,0 +1,89 @@
|
||||
/* pass2_diag.c - targeted test of BCH pass-2 (hash-gated candidates).
|
||||
* Encodes one bch1k block, flips exactly k bits (k around t), and
|
||||
* reports: pass-1 success, and pass-2 rescue (candidate verifies
|
||||
* against the SHA-256 of the original). This separates "pass 2 is
|
||||
* weak" from "the harness wiring is broken".
|
||||
* Usage: pass2_diag <t> [kmax] [trials]
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdint.h>
|
||||
#include "bch.h"
|
||||
#include "bch_polys.h"
|
||||
#include "sha256.h"
|
||||
|
||||
static uint64_t rs = 0xabcdef1234567ULL;
|
||||
static inline uint64_t xr(void)
|
||||
{
|
||||
rs ^= rs << 13;
|
||||
rs ^= rs >> 7;
|
||||
rs ^= rs << 17;
|
||||
return rs;
|
||||
}
|
||||
|
||||
static const bch_poly_t *poly_by_mt(int m, int t)
|
||||
{
|
||||
for (int i = 0; i < BCH_NPOLYS; i++)
|
||||
if (bch_polys[i].m == m && bch_polys[i].t == t)
|
||||
return &bch_polys[i];
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
int t = argc > 1 ? atoi(argv[1]) : 16;
|
||||
int kmax = argc > 2 ? atoi(argv[2]) : t + 8;
|
||||
int trials = argc > 3 ? atoi(argv[3]) : 50;
|
||||
const bch_poly_t *p = poly_by_mt(13, t);
|
||||
if (!p) {
|
||||
fprintf(stderr, "no poly m=13 t=%d\n", t);
|
||||
return 2;
|
||||
}
|
||||
size_t dlen = bch_max_data(p);
|
||||
size_t slen = bch_block_stored_len(dlen, p);
|
||||
uint8_t *data = (uint8_t *)malloc(dlen);
|
||||
uint8_t *stored = (uint8_t *)malloc(slen);
|
||||
uint8_t *rx = (uint8_t *)malloc(slen);
|
||||
uint8_t *out = (uint8_t *)malloc(dlen);
|
||||
uint8_t *cands = (uint8_t *)malloc((size_t)BCH_PASS2_MAX_CANDS * dlen);
|
||||
for (size_t i = 0; i < dlen; i++)
|
||||
data[i] = (uint8_t)(xr() & 0xff);
|
||||
if (bch_encode_block(data, dlen, p, stored) != 0) {
|
||||
fprintf(stderr, "encode failed\n");
|
||||
return 2;
|
||||
}
|
||||
uint8_t want[32];
|
||||
lzply_sha256(data, dlen, want);
|
||||
printf("t=%d block_data=%zu stored=%zu\n", t, dlen, slen);
|
||||
for (int k = t - 2; k <= kmax; k++) {
|
||||
int p1 = 0, rescued = 0;
|
||||
for (int tr = 0; tr < trials; tr++) {
|
||||
memcpy(rx, stored, slen);
|
||||
for (int f = 0; f < k; f++) {
|
||||
size_t pos = (size_t)(xr() % (slen * 8));
|
||||
rx[pos / 8] ^= (uint8_t)(1u << (7 - (pos % 8)));
|
||||
}
|
||||
int corr = -1;
|
||||
if (bch_decode_block(rx, slen, dlen, p, out, &corr) == 0 &&
|
||||
memcmp(out, data, dlen) == 0) {
|
||||
p1++;
|
||||
continue;
|
||||
}
|
||||
int nc = bch_decode_block_candidates(rx, slen, dlen, p, cands,
|
||||
BCH_PASS2_MAX_CANDS);
|
||||
for (int i = 0; i < nc; i++) {
|
||||
uint8_t h[32];
|
||||
lzply_sha256(cands + (size_t)i * dlen, dlen, h);
|
||||
if (memcmp(h, want, 32) == 0) {
|
||||
rescued++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
printf("k=%2d pass1=%d/%d rescued=%d/%d\n", k, p1, trials, rescued,
|
||||
trials);
|
||||
fflush(stdout);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
Executable
+21
@@ -0,0 +1,21 @@
|
||||
#!/bin/bash
|
||||
# run_matrix.sh - full corruption matrix for a list of codecs.
|
||||
# Usage: run_matrix.sh <corpus> <blobsize> <trials> <outfile> <codec...>
|
||||
# Each codec x setting is its own bench invocation; xargs -P spreads
|
||||
# them over all cores. Pass 2 is OFF for the matrix (too slow at scale);
|
||||
# rescue rates are measured separately by run_pass2.sh.
|
||||
set -u
|
||||
CORPUS="$1"; SIZE="$2"; TRIALS="$3"; OUT="$4"; shift 4
|
||||
mkdir -p "$(dirname "$OUT")"
|
||||
{
|
||||
for CODEC in "$@"; do
|
||||
for BER in 1e-5 1e-4 1e-3 3e-3 1e-2; do
|
||||
echo "./bench --codec $CODEC --blob $CORPUS --size $SIZE --trials $TRIALS --ber $BER --nopass2 --out $OUT"
|
||||
done
|
||||
for B in "16,1" "64,1" "256,1" "1024,1" "64,4"; do
|
||||
echo "./bench --codec $CODEC --blob $CORPUS --size $SIZE --trials $TRIALS --burst $B --nopass2 --out $OUT"
|
||||
done
|
||||
echo "./bench --codec $CODEC --blob $CORPUS --size $SIZE --trials $TRIALS --clean --out $OUT"
|
||||
done
|
||||
} | xargs -P "$(nproc)" -I CMD sh -c 'CMD 2>>results/matrix.log'
|
||||
echo "matrix done: $OUT"
|
||||
Executable
+18
@@ -0,0 +1,18 @@
|
||||
#!/bin/bash
|
||||
# run_pass2.sh - BCH pass-2 rescue rates, small trial count (pass 2 is
|
||||
# slow; 25 trials per setting is enough to see rescues).
|
||||
# Usage: run_pass2.sh <corpus> <blobsize> <trials> <outfile> <codec...>
|
||||
set -u
|
||||
CORPUS="$1"; SIZE="$2"; TRIALS="$3"; OUT="$4"; shift 4
|
||||
mkdir -p "$(dirname "$OUT")"
|
||||
{
|
||||
for CODEC in "$@"; do
|
||||
for BER in 1e-4 1e-3 3e-3; do
|
||||
echo "./bench --codec $CODEC --blob $CORPUS --size $SIZE --trials $TRIALS --ber $BER --out $OUT"
|
||||
done
|
||||
for B in "64,1" "256,1"; do
|
||||
echo "./bench --codec $CODEC --blob $CORPUS --size $SIZE --trials $TRIALS --burst $B --out $OUT"
|
||||
done
|
||||
done
|
||||
} | xargs -P "$(nproc)" -I CMD sh -c 'CMD 2>>results/pass2.log'
|
||||
echo "pass2 done: $OUT"
|
||||
@@ -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"
|
||||
|
||||
|
||||
|
||||
@@ -1571,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"
|
||||
@@ -1594,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"
|
||||
@@ -1648,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
|
||||
@@ -1696,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;
|
||||
@@ -1744,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) {
|
||||
@@ -1931,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;
|
||||
|
||||
+6
-312
@@ -18,27 +18,23 @@
|
||||
* and how many bits were corrected. -v adds the per-level trial
|
||||
* counts (BM trials, splitting-filter passes, valid codewords).
|
||||
*
|
||||
* The archive-walking driver lives in repair_cmd.c (shared with
|
||||
* the lzply -r mode); this file is only the option parsing.
|
||||
*
|
||||
* Exit codes: 0 all entries recovered, 1 usage, 2 I/O error,
|
||||
* 3 any entry unrecoverable (matching lzply's EXIT_CORRUPT).
|
||||
*/
|
||||
#define _FILE_OFFSET_BITS 64
|
||||
#define _DEFAULT_SOURCE
|
||||
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <getopt.h>
|
||||
#include <limits.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "bch.h"
|
||||
#include "deep_repair.h"
|
||||
#include "lzply_lib.h"
|
||||
#include "lzrs_lib.h"
|
||||
#include "repair_cmd.h"
|
||||
|
||||
static const char *prog = "lzply_deep_repair";
|
||||
|
||||
@@ -57,56 +53,6 @@ static void usage(void)
|
||||
prog, DEEP_DEFAULT_BUDGET_SEC);
|
||||
}
|
||||
|
||||
/* mkdir -p (mode 0755 for created parents). Returns 0 on success. */
|
||||
static int mkdir_p(const char *path, mode_t mode)
|
||||
{
|
||||
char *tmp = xstrdup(path);
|
||||
size_t n = strlen(tmp);
|
||||
size_t i;
|
||||
if (n == 0) {
|
||||
free(tmp);
|
||||
return 0;
|
||||
}
|
||||
while (n > 1 && tmp[n - 1] == '/')
|
||||
tmp[--n] = '\0';
|
||||
for (i = 1; i <= n; i++) {
|
||||
if (tmp[i] == '/' || tmp[i] == '\0') {
|
||||
char save = tmp[i];
|
||||
struct stat st;
|
||||
tmp[i] = '\0';
|
||||
if (stat(tmp, &st) != 0) {
|
||||
if (mkdir(tmp, mode) != 0 && errno != EEXIST) {
|
||||
free(tmp);
|
||||
return -1;
|
||||
}
|
||||
} else if (!S_ISDIR(st.st_mode)) {
|
||||
free(tmp);
|
||||
return -1;
|
||||
}
|
||||
tmp[i] = save;
|
||||
}
|
||||
}
|
||||
free(tmp);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int write_out_file(const char *path, const uint8_t *data, size_t len,
|
||||
uint32_t mode)
|
||||
{
|
||||
FILE *f = fopen(path, "wb");
|
||||
if (!f)
|
||||
return -1;
|
||||
if (len > 0 && fwrite(data, 1, len, f) != len) {
|
||||
fclose(f);
|
||||
return -1;
|
||||
}
|
||||
if (fclose(f) != 0)
|
||||
return -1;
|
||||
if (mode)
|
||||
chmod(path, (mode_t)(mode & 07777));
|
||||
return 0;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
int max_level = DEEP_MAX_LEVEL;
|
||||
@@ -115,9 +61,6 @@ int main(int argc, char **argv)
|
||||
const char *outdir = "./repaired";
|
||||
const char *only_entry = NULL;
|
||||
const char *archive = NULL;
|
||||
int is_lzrs = 0;
|
||||
FILE *f = NULL;
|
||||
uint8_t magic[4];
|
||||
int opt;
|
||||
static struct option long_opts[] = {
|
||||
{ "time-budget", required_argument, NULL, 1000 },
|
||||
@@ -167,255 +110,6 @@ int main(int argc, char **argv)
|
||||
}
|
||||
archive = argv[optind];
|
||||
|
||||
f = fopen(archive, "rb");
|
||||
if (!f) {
|
||||
fprintf(stderr, "%s: cannot open %s: %s\n", prog, archive,
|
||||
strerror(errno));
|
||||
return EXIT_IO;
|
||||
}
|
||||
if (fread(magic, 1, 4, f) != 4) {
|
||||
fprintf(stderr, "%s: %s is too short to be an archive\n",
|
||||
prog, archive);
|
||||
fclose(f);
|
||||
return EXIT_CORRUPT;
|
||||
}
|
||||
if (memcmp(magic, "LZRS", 4) == 0)
|
||||
is_lzrs = 1;
|
||||
else if (memcmp(magic, "LZPL", 4) != 0) {
|
||||
fprintf(stderr, "%s: %s is not an LZPL or LZRS archive\n",
|
||||
prog, archive);
|
||||
fclose(f);
|
||||
return EXIT_CORRUPT;
|
||||
}
|
||||
/* Validate the archive up front (version, headers, end marker),
|
||||
* so a structurally broken archive fails before any repair is
|
||||
* attempted. The scan also gives the clear v4 message for old
|
||||
* LZPL archives. */
|
||||
{
|
||||
int version = 0;
|
||||
uint32_t count = 0;
|
||||
off_t size = 0, end_off = 0;
|
||||
scan_list_t entries;
|
||||
int s;
|
||||
rewind(f);
|
||||
if (is_lzrs)
|
||||
s = lzrs_scan_archive(archive, &version, &count, &size,
|
||||
&entries, &end_off);
|
||||
else
|
||||
s = scan_archive(archive, &version, &count, &size,
|
||||
&entries, &end_off);
|
||||
if (s != 0) {
|
||||
fclose(f);
|
||||
return EXIT_CORRUPT;
|
||||
}
|
||||
scan_list_free(&entries);
|
||||
rewind(f);
|
||||
}
|
||||
if (mkdir_p(outdir, 0755) != 0) {
|
||||
fprintf(stderr, "%s: cannot create output directory %s: %s\n",
|
||||
prog, outdir, strerror(errno));
|
||||
fclose(f);
|
||||
return EXIT_IO;
|
||||
}
|
||||
|
||||
/* Skip the 16-byte global header; then walk the entries. */
|
||||
if (fseeko(f, 16, SEEK_SET) != 0) {
|
||||
fprintf(stderr, "%s: cannot seek in %s\n", prog, archive);
|
||||
fclose(f);
|
||||
return EXIT_IO;
|
||||
}
|
||||
{
|
||||
int worst = 0;
|
||||
long n_ok = 0, n_fail = 0, n_dir = 0;
|
||||
long landed[4] = { 0, 0, 0, 0 };
|
||||
double t_start = bch_now();
|
||||
for (;;) {
|
||||
char *path = NULL;
|
||||
int level = 0, is_bch = 0, rs_level = 0, is_dir = 0;
|
||||
uint16_t poly_id = 0, want_crc16 = 0;
|
||||
uint64_t stored_size = 0, blob_size = 0, orig_size = 0;
|
||||
uint32_t mode = 0;
|
||||
uint8_t sha[32];
|
||||
uint8_t *stored = NULL;
|
||||
int r;
|
||||
if (is_lzrs) {
|
||||
lzrs_ehdr_t h;
|
||||
r = lzrs_read_entry_header(f, &h);
|
||||
if (r == 1)
|
||||
break;
|
||||
if (r < 0) {
|
||||
fprintf(stderr, "%s: truncated or corrupt entry header\n",
|
||||
prog);
|
||||
worst = EXIT_CORRUPT;
|
||||
break;
|
||||
}
|
||||
path = h.path;
|
||||
level = h.level;
|
||||
is_bch = (h.flags & FLAG_BCH) != 0;
|
||||
rs_level = h.rs_level;
|
||||
is_dir = (h.flags & FLAG_ISDIR) != 0;
|
||||
poly_id = h.bch_poly_id;
|
||||
want_crc16 = h.crc16;
|
||||
stored_size = h.stored_size;
|
||||
blob_size = h.blob_size;
|
||||
orig_size = h.orig_size;
|
||||
mode = h.mode;
|
||||
memcpy(sha, h.sha, 32);
|
||||
} else {
|
||||
ehdr_t h;
|
||||
r = read_entry_header(f, &h);
|
||||
if (r == 1)
|
||||
break;
|
||||
if (r < 0) {
|
||||
fprintf(stderr, "%s: truncated or corrupt entry header\n",
|
||||
prog);
|
||||
worst = EXIT_CORRUPT;
|
||||
break;
|
||||
}
|
||||
path = h.path;
|
||||
level = h.level;
|
||||
is_bch = (h.flags & FLAG_BCH) != 0;
|
||||
rs_level = 0;
|
||||
is_dir = (h.flags & FLAG_ISDIR) != 0;
|
||||
poly_id = (uint16_t)(h.rs_level |
|
||||
((uint16_t)h.reserved << 8));
|
||||
want_crc16 = h.crc16;
|
||||
stored_size = h.stored_size;
|
||||
blob_size = h.blob_size;
|
||||
orig_size = h.orig_size;
|
||||
mode = h.mode;
|
||||
memcpy(sha, h.sha, 32);
|
||||
}
|
||||
stored = xmalloc(stored_size ? (size_t)stored_size : 1);
|
||||
if (stored_size > 0 &&
|
||||
fread(stored, 1, (size_t)stored_size, f) !=
|
||||
(size_t)stored_size) {
|
||||
fprintf(stderr, "%s: truncated data for %s\n", prog, path);
|
||||
free(stored);
|
||||
free(path);
|
||||
worst = EXIT_CORRUPT;
|
||||
break;
|
||||
}
|
||||
if (only_entry && strcmp(path, only_entry) != 0) {
|
||||
free(stored);
|
||||
free(path);
|
||||
continue;
|
||||
}
|
||||
if (is_dir) {
|
||||
char *dp = xmalloc(strlen(outdir) + strlen(path) + 2);
|
||||
sprintf(dp, "%s/%s", outdir, path);
|
||||
if (mkdir_p(dp, mode ? (mode_t)(mode & 07777) : 0755) != 0)
|
||||
fprintf(stderr, "%s: cannot create directory %s: %s\n",
|
||||
prog, dp, strerror(errno));
|
||||
free(dp);
|
||||
free(stored);
|
||||
free(path);
|
||||
n_dir++;
|
||||
continue;
|
||||
}
|
||||
{
|
||||
uint8_t *raw = NULL;
|
||||
size_t raw_len = 0;
|
||||
deep_stats_t st;
|
||||
int drc = deep_repair_entry(stored, (size_t)stored_size,
|
||||
level, is_bch, poly_id,
|
||||
rs_level, sha,
|
||||
(size_t)blob_size, want_crc16,
|
||||
max_level, budget,
|
||||
&raw, &raw_len, &st);
|
||||
free(stored);
|
||||
if (drc != 0) {
|
||||
printf("%s: FAILED (stage %s) after %.3fs, "
|
||||
"cands %ld crc-rejects %ld sha-rejects %ld\n",
|
||||
path, st.fail_stage, st.t_total,
|
||||
st.cands_tried, st.crc_rejects, st.sha_rejects);
|
||||
if (verbose) {
|
||||
int lv;
|
||||
for (lv = 0; lv <= DEEP_MAX_LEVEL; lv++)
|
||||
printf(" L%d: %.3fs trials %ld split %ld "
|
||||
"codewords %ld\n", lv, st.t_level[lv],
|
||||
st.trials[lv], st.split_pass[lv],
|
||||
st.codewords[lv]);
|
||||
printf(" blocks %ld/%ld failed%s\n",
|
||||
st.blocks_failed, st.blocks_total,
|
||||
st.partial ? " (partial: budget hit)" : "");
|
||||
}
|
||||
n_fail++;
|
||||
if (EXIT_CORRUPT > worst)
|
||||
worst = EXIT_CORRUPT;
|
||||
free(path);
|
||||
continue;
|
||||
}
|
||||
if (raw_len != orig_size) {
|
||||
fprintf(stderr, "%s: %s: size mismatch after repair "
|
||||
"(got %zu, expected %llu)\n", prog, path,
|
||||
raw_len, (unsigned long long)orig_size);
|
||||
free(raw);
|
||||
free(path);
|
||||
n_fail++;
|
||||
if (EXIT_CORRUPT > worst)
|
||||
worst = EXIT_CORRUPT;
|
||||
continue;
|
||||
}
|
||||
{
|
||||
char *dp = xmalloc(strlen(outdir) + strlen(path) + 2);
|
||||
char *pd;
|
||||
sprintf(dp, "%s/%s", outdir, path);
|
||||
pd = parent_dir(dp);
|
||||
if (mkdir_p(pd, 0755) != 0)
|
||||
fprintf(stderr, "%s: cannot create %s: %s\n",
|
||||
prog, pd, strerror(errno));
|
||||
free(pd);
|
||||
if (write_out_file(dp, raw, raw_len, mode) != 0) {
|
||||
fprintf(stderr, "%s: cannot write %s: %s\n",
|
||||
prog, dp, strerror(errno));
|
||||
if (EXIT_IO > worst)
|
||||
worst = EXIT_IO;
|
||||
free(dp);
|
||||
free(raw);
|
||||
free(path);
|
||||
continue;
|
||||
}
|
||||
free(dp);
|
||||
}
|
||||
{
|
||||
char rssuf[48];
|
||||
rssuf[0] = '\0';
|
||||
if (st.rs_corrected > 0)
|
||||
snprintf(rssuf, sizeof rssuf,
|
||||
" (RS corrected %d symbols)",
|
||||
st.rs_corrected);
|
||||
printf("%s: RECOVERED at L%d in %.3fs "
|
||||
"(L0 %.3fs, L1 %.3fs, L2 %.3fs, L3 %.3fs) "
|
||||
"cands %ld crc-rejects %ld sha-rejects %ld "
|
||||
"bch-corrected %d%s\n",
|
||||
path, st.level_landed, st.t_total,
|
||||
st.t_level[0], st.t_level[1], st.t_level[2],
|
||||
st.t_level[3], st.cands_tried, st.crc_rejects,
|
||||
st.sha_rejects, st.bch_corrected, rssuf);
|
||||
}
|
||||
if (verbose) {
|
||||
int lv;
|
||||
for (lv = 0; lv <= DEEP_MAX_LEVEL; lv++)
|
||||
printf(" L%d: %.3fs trials %ld split %ld "
|
||||
"codewords %ld\n", lv, st.t_level[lv],
|
||||
st.trials[lv], st.split_pass[lv],
|
||||
st.codewords[lv]);
|
||||
printf(" blocks %ld/%ld failed%s\n",
|
||||
st.blocks_failed, st.blocks_total,
|
||||
st.partial ? " (partial: budget hit)" : "");
|
||||
}
|
||||
landed[st.level_landed]++;
|
||||
n_ok++;
|
||||
free(raw);
|
||||
free(path);
|
||||
}
|
||||
}
|
||||
printf("deep repair: %ld recovered (L0 %ld, L1 %ld, L2 %ld, "
|
||||
"L3 %ld), %ld failed, %ld directories, %.3fs total\n",
|
||||
n_ok, landed[0], landed[1], landed[2], landed[3],
|
||||
n_fail, n_dir, bch_now() - t_start);
|
||||
fclose(f);
|
||||
return worst;
|
||||
}
|
||||
return repair_archive(prog, archive, outdir, max_level, budget,
|
||||
only_entry, verbose);
|
||||
}
|
||||
+354
@@ -0,0 +1,354 @@
|
||||
/* repair_cmd.c - shared archive repair driver for `lzply -r` and
|
||||
* `lzply_deep_repair`.
|
||||
*
|
||||
* repair_archive() validates an LZPL v5 or LZRS v1 archive, then
|
||||
* attempts the escalating deep-repair ladder (L0 standard decode
|
||||
* to t, L1 Chase-1 flips, L2 Chase-2 flips, L3 cross-block list
|
||||
* decoding) per entry, writing recovered files under outdir with
|
||||
* their stored paths preserved. Nothing is ever written unless it
|
||||
* passes both oracles (CRC16, then decompress + SHA-256).
|
||||
*
|
||||
* 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 L1 line carries a (CUDA) marker when the Chase-1 scan ran
|
||||
* on the GPU.
|
||||
*
|
||||
* Returns the worst exit code: 0 all entries recovered, 2 I/O
|
||||
* error, 3 any entry unrecoverable (matching lzply's EXIT_*).
|
||||
*/
|
||||
#define _FILE_OFFSET_BITS 64
|
||||
#define _DEFAULT_SOURCE
|
||||
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <limits.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "bch.h"
|
||||
#include "deep_repair.h"
|
||||
#include "lzply_lib.h"
|
||||
#include "lzrs_lib.h"
|
||||
#include "repair_cmd.h"
|
||||
|
||||
/* mkdir -p (mode 0755 for created parents). Returns 0 on success. */
|
||||
static int mkdir_p(const char *path, mode_t mode)
|
||||
{
|
||||
char *tmp = xstrdup(path);
|
||||
size_t n = strlen(tmp);
|
||||
size_t i;
|
||||
if (n == 0) {
|
||||
free(tmp);
|
||||
return 0;
|
||||
}
|
||||
while (n > 1 && tmp[n - 1] == '/')
|
||||
tmp[--n] = '\0';
|
||||
for (i = 1; i <= n; i++) {
|
||||
if (tmp[i] == '/' || tmp[i] == '\0') {
|
||||
char save = tmp[i];
|
||||
struct stat st;
|
||||
tmp[i] = '\0';
|
||||
if (stat(tmp, &st) != 0) {
|
||||
if (mkdir(tmp, mode) != 0 && errno != EEXIST) {
|
||||
free(tmp);
|
||||
return -1;
|
||||
}
|
||||
} else if (!S_ISDIR(st.st_mode)) {
|
||||
free(tmp);
|
||||
return -1;
|
||||
}
|
||||
tmp[i] = save;
|
||||
}
|
||||
}
|
||||
free(tmp);
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int write_out_file(const char *path, const uint8_t *data, size_t len,
|
||||
uint32_t mode)
|
||||
{
|
||||
FILE *f = fopen(path, "wb");
|
||||
if (!f)
|
||||
return -1;
|
||||
if (len > 0 && fwrite(data, 1, len, f) != len) {
|
||||
fclose(f);
|
||||
return -1;
|
||||
}
|
||||
if (fclose(f) != 0)
|
||||
return -1;
|
||||
if (mode)
|
||||
chmod(path, (mode_t)(mode & 07777));
|
||||
return 0;
|
||||
}
|
||||
|
||||
int repair_archive(const char *prog, const char *archive,
|
||||
const char *outdir, int max_level, double budget,
|
||||
const char *only_entry, int verbose)
|
||||
{
|
||||
int is_lzrs = 0;
|
||||
FILE *f = NULL;
|
||||
uint8_t magic[4];
|
||||
|
||||
lzply_set_progname(prog);
|
||||
f = fopen(archive, "rb");
|
||||
if (!f) {
|
||||
fprintf(stderr, "%s: cannot open %s: %s\n", prog, archive,
|
||||
strerror(errno));
|
||||
return EXIT_IO;
|
||||
}
|
||||
if (fread(magic, 1, 4, f) != 4) {
|
||||
fprintf(stderr, "%s: %s is too short to be an archive\n", prog, archive);
|
||||
fclose(f);
|
||||
return EXIT_CORRUPT;
|
||||
}
|
||||
if (memcmp(magic, "LZRS", 4) == 0)
|
||||
is_lzrs = 1;
|
||||
else if (memcmp(magic, "LZPL", 4) != 0) {
|
||||
fprintf(stderr, "%s: %s is not an LZPL or LZRS archive\n", prog, archive);
|
||||
fclose(f);
|
||||
return EXIT_CORRUPT;
|
||||
}
|
||||
/* Validate the archive up front (version, headers, end marker),
|
||||
* so a structurally broken archive fails before any repair is
|
||||
* attempted. The scan also gives the clear v4 message for old
|
||||
* LZPL archives. */
|
||||
{
|
||||
int version = 0;
|
||||
uint32_t count = 0;
|
||||
off_t size = 0, end_off = 0;
|
||||
scan_list_t entries;
|
||||
int s;
|
||||
rewind(f);
|
||||
if (is_lzrs)
|
||||
s = lzrs_scan_archive(archive, &version, &count, &size,
|
||||
&entries, &end_off);
|
||||
else
|
||||
s = scan_archive(archive, &version, &count, &size,
|
||||
&entries, &end_off);
|
||||
if (s != 0) {
|
||||
fclose(f);
|
||||
return EXIT_CORRUPT;
|
||||
}
|
||||
scan_list_free(&entries);
|
||||
rewind(f);
|
||||
}
|
||||
if (mkdir_p(outdir, 0755) != 0) {
|
||||
fprintf(stderr, "%s: cannot create output directory %s: %s\n",
|
||||
prog, outdir, strerror(errno));
|
||||
fclose(f);
|
||||
return EXIT_IO;
|
||||
}
|
||||
|
||||
/* Skip the 16-byte global header; then walk the entries. */
|
||||
if (fseeko(f, 16, SEEK_SET) != 0) {
|
||||
fprintf(stderr, "%s: cannot seek in %s: %s\n", prog, archive,
|
||||
strerror(errno));
|
||||
fclose(f);
|
||||
return EXIT_IO;
|
||||
}
|
||||
{
|
||||
int worst = 0;
|
||||
long n_ok = 0, n_fail = 0, n_dir = 0;
|
||||
long landed[4] = { 0, 0, 0, 0 };
|
||||
double t_start = bch_now();
|
||||
for (;;) {
|
||||
char *path = NULL;
|
||||
int level = 0, is_bch = 0, rs_level = 0, is_dir = 0;
|
||||
uint16_t poly_id = 0, want_crc16 = 0;
|
||||
uint64_t stored_size = 0, blob_size = 0, orig_size = 0;
|
||||
uint32_t mode = 0;
|
||||
uint8_t sha[32];
|
||||
uint8_t *stored = NULL;
|
||||
int r;
|
||||
if (is_lzrs) {
|
||||
lzrs_ehdr_t h;
|
||||
r = lzrs_read_entry_header(f, &h);
|
||||
if (r == 1)
|
||||
break;
|
||||
if (r < 0) {
|
||||
fprintf(stderr, "%s: truncated or corrupt entry header\n",
|
||||
prog);
|
||||
worst = EXIT_CORRUPT;
|
||||
break;
|
||||
}
|
||||
path = h.path;
|
||||
level = h.level;
|
||||
is_bch = (h.flags & FLAG_BCH) != 0;
|
||||
rs_level = h.rs_level;
|
||||
is_dir = (h.flags & FLAG_ISDIR) != 0;
|
||||
poly_id = h.bch_poly_id;
|
||||
want_crc16 = h.crc16;
|
||||
stored_size = h.stored_size;
|
||||
blob_size = h.blob_size;
|
||||
orig_size = h.orig_size;
|
||||
mode = h.mode;
|
||||
memcpy(sha, h.sha, 32);
|
||||
} else {
|
||||
ehdr_t h;
|
||||
r = read_entry_header(f, &h);
|
||||
if (r == 1)
|
||||
break;
|
||||
if (r < 0) {
|
||||
fprintf(stderr, "%s: truncated or corrupt entry header\n",
|
||||
prog);
|
||||
worst = EXIT_CORRUPT;
|
||||
break;
|
||||
}
|
||||
path = h.path;
|
||||
level = h.level;
|
||||
is_bch = (h.flags & FLAG_BCH) != 0;
|
||||
rs_level = 0;
|
||||
is_dir = (h.flags & FLAG_ISDIR) != 0;
|
||||
poly_id = (uint16_t)(h.rs_level |
|
||||
((uint16_t)h.reserved << 8));
|
||||
want_crc16 = h.crc16;
|
||||
stored_size = h.stored_size;
|
||||
blob_size = h.blob_size;
|
||||
orig_size = h.orig_size;
|
||||
mode = h.mode;
|
||||
memcpy(sha, h.sha, 32);
|
||||
}
|
||||
stored = xmalloc(stored_size ? (size_t)stored_size : 1);
|
||||
if (stored_size > 0 &&
|
||||
fread(stored, 1, (size_t)stored_size, f) !=
|
||||
(size_t)stored_size) {
|
||||
fprintf(stderr, "%s: truncated data for %s\n", prog, path);
|
||||
free(stored);
|
||||
free(path);
|
||||
worst = EXIT_CORRUPT;
|
||||
break;
|
||||
}
|
||||
if (only_entry && strcmp(path, only_entry) != 0) {
|
||||
free(stored);
|
||||
free(path);
|
||||
continue;
|
||||
}
|
||||
if (is_dir) {
|
||||
char *dp = xmalloc(strlen(outdir) + strlen(path) + 2);
|
||||
sprintf(dp, "%s/%s", outdir, path);
|
||||
if (mkdir_p(dp, mode ? (mode_t)(mode & 07777) : 0755) != 0)
|
||||
fprintf(stderr, "%s: cannot create directory %s: %s\n",
|
||||
prog, dp, strerror(errno));
|
||||
free(dp);
|
||||
free(stored);
|
||||
free(path);
|
||||
n_dir++;
|
||||
continue;
|
||||
}
|
||||
{
|
||||
uint8_t *raw = NULL;
|
||||
size_t raw_len = 0;
|
||||
deep_stats_t st;
|
||||
int drc = deep_repair_entry(stored, (size_t)stored_size,
|
||||
level, is_bch, poly_id,
|
||||
rs_level, sha,
|
||||
(size_t)blob_size, want_crc16,
|
||||
max_level, budget,
|
||||
&raw, &raw_len, &st);
|
||||
free(stored);
|
||||
if (drc != 0) {
|
||||
printf("%s: FAILED (stage %s) after %.3fs, "
|
||||
"cands %ld crc-rejects %ld sha-rejects %ld\n",
|
||||
path, st.fail_stage, st.t_total,
|
||||
st.cands_tried, st.crc_rejects, st.sha_rejects);
|
||||
if (verbose) {
|
||||
int lv;
|
||||
for (lv = 0; lv <= DEEP_MAX_LEVEL; lv++)
|
||||
printf(" L%d: %.3fs trials %ld split %ld "
|
||||
"codewords %ld%s\n", lv, st.t_level[lv],
|
||||
st.trials[lv], st.split_pass[lv],
|
||||
st.codewords[lv],
|
||||
(lv == 1 && st.chase_cuda_used) ?
|
||||
" (CUDA)" : "");
|
||||
printf(" blocks %ld/%ld failed%s\n",
|
||||
st.blocks_failed, st.blocks_total,
|
||||
st.partial ? " (partial: budget hit)" : "");
|
||||
}
|
||||
n_fail++;
|
||||
if (EXIT_CORRUPT > worst)
|
||||
worst = EXIT_CORRUPT;
|
||||
free(path);
|
||||
continue;
|
||||
}
|
||||
if (raw_len != orig_size) {
|
||||
fprintf(stderr, "%s: %s: size mismatch after repair "
|
||||
"(got %zu, expected %llu)\n", prog, path,
|
||||
raw_len, (unsigned long long)orig_size);
|
||||
free(raw);
|
||||
free(path);
|
||||
n_fail++;
|
||||
if (EXIT_CORRUPT > worst)
|
||||
worst = EXIT_CORRUPT;
|
||||
continue;
|
||||
}
|
||||
{
|
||||
char *dp = xmalloc(strlen(outdir) + strlen(path) + 2);
|
||||
char *pd;
|
||||
sprintf(dp, "%s/%s", outdir, path);
|
||||
pd = parent_dir(dp);
|
||||
if (mkdir_p(pd, 0755) != 0)
|
||||
fprintf(stderr, "%s: cannot create %s: %s\n",
|
||||
prog, pd, strerror(errno));
|
||||
free(pd);
|
||||
if (write_out_file(dp, raw, raw_len, mode) != 0) {
|
||||
fprintf(stderr, "%s: cannot write %s: %s\n",
|
||||
prog, dp, strerror(errno));
|
||||
if (EXIT_IO > worst)
|
||||
worst = EXIT_IO;
|
||||
free(dp);
|
||||
free(raw);
|
||||
free(path);
|
||||
continue;
|
||||
}
|
||||
free(dp);
|
||||
}
|
||||
{
|
||||
char rssuf[48];
|
||||
rssuf[0] = '\0';
|
||||
if (st.rs_corrected > 0)
|
||||
snprintf(rssuf, sizeof rssuf,
|
||||
" (RS corrected %d symbols)",
|
||||
st.rs_corrected);
|
||||
printf("%s: RECOVERED at L%d in %.3fs "
|
||||
"(L0 %.3fs, L1 %.3fs, L2 %.3fs, L3 %.3fs) "
|
||||
"cands %ld crc-rejects %ld sha-rejects %ld "
|
||||
"bch-corrected %d%s\n",
|
||||
path, st.level_landed, st.t_total,
|
||||
st.t_level[0], st.t_level[1], st.t_level[2],
|
||||
st.t_level[3], st.cands_tried, st.crc_rejects,
|
||||
st.sha_rejects, st.bch_corrected, rssuf);
|
||||
}
|
||||
if (verbose) {
|
||||
int lv;
|
||||
for (lv = 0; lv <= DEEP_MAX_LEVEL; lv++)
|
||||
printf(" L%d: %.3fs trials %ld split %ld "
|
||||
"codewords %ld%s\n", lv, st.t_level[lv],
|
||||
st.trials[lv], st.split_pass[lv],
|
||||
st.codewords[lv],
|
||||
(lv == 1 && st.chase_cuda_used) ?
|
||||
" (CUDA)" : "");
|
||||
printf(" blocks %ld/%ld failed%s\n",
|
||||
st.blocks_failed, st.blocks_total,
|
||||
st.partial ? " (partial: budget hit)" : "");
|
||||
}
|
||||
landed[st.level_landed]++;
|
||||
n_ok++;
|
||||
free(raw);
|
||||
free(path);
|
||||
}
|
||||
}
|
||||
printf("deep repair: %ld recovered (L0 %ld, L1 %ld, L2 %ld, "
|
||||
"L3 %ld), %ld failed, %ld directories, %.3fs total\n",
|
||||
n_ok, landed[0], landed[1], landed[2], landed[3],
|
||||
n_fail, n_dir, bch_now() - t_start);
|
||||
fclose(f);
|
||||
return worst;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
/* repair_cmd.h - shared archive repair driver.
|
||||
*
|
||||
* repair_archive() is the archive-walking repair loop used by both
|
||||
* the lzply -r mode and the lzply_deep_repair binary: it validates
|
||||
* the archive, then attempts the escalating deep-repair ladder
|
||||
* (L0-L3) per entry, writing recovered files under outdir.
|
||||
* Returns the worst exit code: 0 all entries recovered, 2 I/O
|
||||
* error, 3 any entry unrecoverable (matching lzply's EXIT_*).
|
||||
*/
|
||||
#ifndef LZPLY_REPAIR_CMD_H
|
||||
#define LZPLY_REPAIR_CMD_H
|
||||
|
||||
int repair_archive(const char *prog, const char *archive,
|
||||
const char *outdir, int max_level, double budget,
|
||||
const char *only_entry, int verbose);
|
||||
|
||||
#endif /* LZPLY_REPAIR_CMD_H */
|
||||
@@ -0,0 +1,9 @@
|
||||
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
|
||||
flipped 9 bits at: 3498895 1877890 867125 251131 3784195 2342946 1354710 492520 135908
|
||||
control: standard decode fails as expected
|
||||
suspects: 6
|
||||
cpu: nc=13 partial=0
|
||||
trials=4194296 split_pass=117 codewords=117 candidates=13
|
||||
time=166.680 s rate=25164 trials/s
|
||||
cands_hash=0x5c7f589a39df28b8
|
||||
original among candidates: YES
|
||||
@@ -0,0 +1,9 @@
|
||||
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
|
||||
flipped 11 bits at: 7480 711379 3153510 1270250 3083353 1772972 938922 807275 94692 1349411 2303948
|
||||
control: standard decode fails as expected
|
||||
suspects: 0
|
||||
cpu: nc=7 partial=0
|
||||
trials=4194296 split_pass=63 codewords=63 candidates=7
|
||||
time=159.671 s rate=26268 trials/s
|
||||
cands_hash=0x64657c5daf8fe7bd
|
||||
original among candidates: NO
|
||||
@@ -0,0 +1,9 @@
|
||||
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
|
||||
flipped 10 bits at: 1752901 3737741 3059447 2051162 317292 620740 979055 1373300 3126232 2196530
|
||||
control: standard decode fails as expected
|
||||
suspects: 12
|
||||
cpu: nc=11 partial=0
|
||||
trials=4194296 split_pass=99 codewords=99 candidates=11
|
||||
time=164.670 s rate=25471 trials/s
|
||||
cands_hash=0x56c63d470502aee8
|
||||
original among candidates: NO
|
||||
@@ -0,0 +1,9 @@
|
||||
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
|
||||
flipped 9 bits at: 2917275 1921054 4031549 1001171 2122060 1902685 3634746 522053 2462819
|
||||
control: standard decode fails as expected
|
||||
suspects: 0
|
||||
cpu: nc=13 partial=0
|
||||
trials=4194296 split_pass=117 codewords=117 candidates=13
|
||||
time=168.330 s rate=24917 trials/s
|
||||
cands_hash=0x67fdae628952aa68
|
||||
original among candidates: YES
|
||||
@@ -0,0 +1,9 @@
|
||||
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
|
||||
flipped 12 bits at: 890570 2616517 4117318 731678 2468035 436493 204399 1066127 205524 3172107 3730223 2267138
|
||||
control: standard decode fails as expected
|
||||
suspects: 6
|
||||
cpu: nc=13 partial=0
|
||||
trials=4194296 split_pass=117 codewords=117 candidates=13
|
||||
time=166.697 s rate=25161 trials/s
|
||||
cands_hash=0x7e36640193d2f371
|
||||
original among candidates: NO
|
||||
@@ -0,0 +1,9 @@
|
||||
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
|
||||
flipped 10 bits at: 2573515 3309936 1817927 223125 3836982 2344499 4025415 1674867 2505759 2533574
|
||||
control: standard decode fails as expected
|
||||
suspects: 3
|
||||
cuda: nc=10
|
||||
trials=4194296 split_pass=90 codewords=90 candidates=10
|
||||
time=0.305 s rate=13738008 trials/s
|
||||
cands_hash=0xf0ac78a5c0db6077
|
||||
original among candidates: NO
|
||||
@@ -0,0 +1,9 @@
|
||||
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
|
||||
flipped 12 bits at: 3172352 1071835 3926998 3247870 3251552 3325465 155676 3753442 1626860 3680006 2968890 315944
|
||||
control: standard decode fails as expected
|
||||
suspects: 6
|
||||
cuda: nc=13
|
||||
trials=4194296 split_pass=117 codewords=117 candidates=13
|
||||
time=0.316 s rate=13258809 trials/s
|
||||
cands_hash=0xff1b6acdbcda946e
|
||||
original among candidates: NO
|
||||
@@ -0,0 +1,9 @@
|
||||
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
|
||||
flipped 9 bits at: 1139622 1583101 138872 3986032 4059758 2290546 1200718 4107582 2213207
|
||||
control: standard decode fails as expected
|
||||
suspects: 6
|
||||
cuda: nc=9
|
||||
trials=4194296 split_pass=81 codewords=81 candidates=9
|
||||
time=0.292 s rate=14373237 trials/s
|
||||
cands_hash=0xc3dc7b7528027f2c
|
||||
original among candidates: YES
|
||||
@@ -0,0 +1,3 @@
|
||||
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
|
||||
flipped 7 bits at: 3498895 1877890 867125 251131 3784195 2342946 1354710
|
||||
control FAILED: standard decode succeeded on 7-error word
|
||||
@@ -0,0 +1,3 @@
|
||||
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
|
||||
flipped 8 bits at: 3498895 1877890 867125 251131 3784195 2342946 1354710 492520
|
||||
control FAILED: standard decode succeeded on 8-error word
|
||||
@@ -0,0 +1,9 @@
|
||||
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
|
||||
flipped 9 bits at: 3498895 1877890 867125 251131 3784195 2342946 1354710 492520 135908
|
||||
control: standard decode fails as expected
|
||||
suspects: 6
|
||||
cuda: nc=13
|
||||
trials=4194296 split_pass=117 codewords=117 candidates=13
|
||||
time=0.362 s rate=11601794 trials/s
|
||||
cands_hash=0x5c7f589a39df28b8
|
||||
original among candidates: YES
|
||||
@@ -0,0 +1,9 @@
|
||||
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
|
||||
flipped 11 bits at: 3933902 465327 3816380 801717 1488751 2770697 1474470 2075870 803263 2125553 3564454
|
||||
control: standard decode fails as expected
|
||||
suspects: 0
|
||||
cuda: nc=10
|
||||
trials=4194296 split_pass=90 codewords=90 candidates=10
|
||||
time=0.309 s rate=13562801 trials/s
|
||||
cands_hash=0x0828e3f1a1de3768
|
||||
original among candidates: NO
|
||||
@@ -0,0 +1,9 @@
|
||||
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
|
||||
flipped 10 bits at: 1826361 717892 152487 785237 531434 2695038 3847765 1073156 1449180 1378323
|
||||
control: standard decode fails as expected
|
||||
suspects: 0
|
||||
cuda: nc=14
|
||||
trials=4194296 split_pass=126 codewords=126 candidates=14
|
||||
time=0.332 s rate=12630048 trials/s
|
||||
cands_hash=0x2478043cdde3ae3e
|
||||
original among candidates: NO
|
||||
@@ -0,0 +1,9 @@
|
||||
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
|
||||
flipped 10 bits at: 2607436 1927552 988006 2269250 396460 3929804 123706 24069 746876 2808087
|
||||
control: standard decode fails as expected
|
||||
suspects: 3
|
||||
cuda: nc=12
|
||||
trials=4194296 split_pass=108 codewords=108 candidates=12
|
||||
time=0.322 s rate=13016562 trials/s
|
||||
cands_hash=0x06acc3a69443d342
|
||||
original among candidates: NO
|
||||
@@ -0,0 +1,9 @@
|
||||
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
|
||||
flipped 11 bits at: 392468 3185225 2667856 3078904 524650 2513743 2343604 3018313 3280212 3273574 3523990
|
||||
control: standard decode fails as expected
|
||||
suspects: 0
|
||||
cuda: nc=11
|
||||
trials=4194296 split_pass=99 codewords=99 candidates=11
|
||||
time=0.315 s rate=13299619 trials/s
|
||||
cands_hash=0xd0e203ae5074c351
|
||||
original among candidates: NO
|
||||
@@ -0,0 +1,9 @@
|
||||
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
|
||||
flipped 12 bits at: 38571 3843158 2832380 2172314 3143789 732683 2822399 477706 1732523 3284823 1535823 1770581
|
||||
control: standard decode fails as expected
|
||||
suspects: 0
|
||||
cuda: nc=9
|
||||
trials=4194296 split_pass=81 codewords=81 candidates=9
|
||||
time=0.285 s rate=14727206 trials/s
|
||||
cands_hash=0xa817ea75c23a4634
|
||||
original among candidates: NO
|
||||
@@ -0,0 +1,9 @@
|
||||
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
|
||||
flipped 11 bits at: 7480 711379 3153510 1270250 3083353 1772972 938922 807275 94692 1349411 2303948
|
||||
control: standard decode fails as expected
|
||||
suspects: 0
|
||||
cuda: nc=7
|
||||
trials=4194296 split_pass=63 codewords=63 candidates=7
|
||||
time=0.284 s rate=14768929 trials/s
|
||||
cands_hash=0x64657c5daf8fe7bd
|
||||
original among candidates: NO
|
||||
@@ -0,0 +1,9 @@
|
||||
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
|
||||
flipped 9 bits at: 3186922 2673650 95755 3163968 1448843 1728624 3938100 3106615 3246295
|
||||
control: standard decode fails as expected
|
||||
suspects: 3
|
||||
cuda: nc=18
|
||||
trials=4194296 split_pass=162 codewords=162 candidates=18
|
||||
time=0.352 s rate=11929751 trials/s
|
||||
cands_hash=0x9fbf8f81ead3e086
|
||||
original among candidates: YES
|
||||
@@ -0,0 +1,9 @@
|
||||
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
|
||||
flipped 10 bits at: 1752901 3737741 3059447 2051162 317292 620740 979055 1373300 3126232 2196530
|
||||
control: standard decode fails as expected
|
||||
suspects: 12
|
||||
cuda: nc=11
|
||||
trials=4194296 split_pass=99 codewords=99 candidates=11
|
||||
time=0.311 s rate=13481690 trials/s
|
||||
cands_hash=0x56c63d470502aee8
|
||||
original among candidates: NO
|
||||
@@ -0,0 +1,9 @@
|
||||
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
|
||||
flipped 11 bits at: 2942199 3813690 55970 3322604 1721331 1106782 2795398 3273601 2978575 590496 1883743
|
||||
control: standard decode fails as expected
|
||||
suspects: 3
|
||||
cuda: nc=16
|
||||
trials=4194296 split_pass=144 codewords=144 candidates=16
|
||||
time=0.334 s rate=12569297 trials/s
|
||||
cands_hash=0xab869c50c89764d7
|
||||
original among candidates: NO
|
||||
@@ -0,0 +1,9 @@
|
||||
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
|
||||
flipped 11 bits at: 4193586 3139026 1537929 3333519 4177005 3421389 1477710 2478458 3490487 446536 2834840
|
||||
control: standard decode fails as expected
|
||||
suspects: 0
|
||||
cuda: nc=12
|
||||
trials=4194296 split_pass=108 codewords=108 candidates=12
|
||||
time=0.318 s rate=13172288 trials/s
|
||||
cands_hash=0xc2ce80d884c0de3a
|
||||
original among candidates: NO
|
||||
@@ -0,0 +1,9 @@
|
||||
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
|
||||
flipped 9 bits at: 2917275 1921054 4031549 1001171 2122060 1902685 3634746 522053 2462819
|
||||
control: standard decode fails as expected
|
||||
suspects: 0
|
||||
cuda: nc=13
|
||||
trials=4194296 split_pass=117 codewords=117 candidates=13
|
||||
time=0.321 s rate=13079187 trials/s
|
||||
cands_hash=0x67fdae628952aa68
|
||||
original among candidates: YES
|
||||
@@ -0,0 +1,9 @@
|
||||
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
|
||||
flipped 12 bits at: 890570 2616517 4117318 731678 2468035 436493 204399 1066127 205524 3172107 3730223 2267138
|
||||
control: standard decode fails as expected
|
||||
suspects: 6
|
||||
cuda: nc=13
|
||||
trials=4194296 split_pass=117 codewords=117 candidates=13
|
||||
time=0.315 s rate=13309357 trials/s
|
||||
cands_hash=0x7e36640193d2f371
|
||||
original among candidates: NO
|
||||
@@ -0,0 +1,9 @@
|
||||
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
|
||||
flipped 10 bits at: 1565866 3522582 366564 1232519 2738835 229635 1819150 3469645 3127283 2389929
|
||||
control: standard decode fails as expected
|
||||
suspects: 3
|
||||
cuda: nc=13
|
||||
trials=4194296 split_pass=117 codewords=117 candidates=13
|
||||
time=0.326 s rate=12848095 trials/s
|
||||
cands_hash=0x69622442a318139d
|
||||
original among candidates: NO
|
||||
@@ -0,0 +1,9 @@
|
||||
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
|
||||
flipped 12 bits at: 829773 1707577 251473 1166989 1877618 570817 1417188 517337 600769 4129883 74702 301529
|
||||
control: standard decode fails as expected
|
||||
suspects: 3
|
||||
cuda: nc=15
|
||||
trials=4194296 split_pass=135 codewords=135 candidates=15
|
||||
time=0.332 s rate=12614960 trials/s
|
||||
cands_hash=0xf6dc42abffaa291f
|
||||
original among candidates: NO
|
||||
@@ -0,0 +1,9 @@
|
||||
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
|
||||
flipped 10 bits at: 1126595 647008 1758360 1802814 1984026 2375369 1613697 336812 4049402 191539
|
||||
control: standard decode fails as expected
|
||||
suspects: 3
|
||||
cuda: nc=8
|
||||
trials=4194296 split_pass=72 codewords=72 candidates=8
|
||||
time=0.290 s rate=14475440 trials/s
|
||||
cands_hash=0x41d95f8afa6ba1ce
|
||||
original among candidates: NO
|
||||
@@ -0,0 +1,9 @@
|
||||
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
|
||||
flipped 9 bits at: 3397325 2439328 2357346 3286739 3189071 982899 1409094 3266818 3890431
|
||||
control: standard decode fails as expected
|
||||
suspects: 3
|
||||
cuda: nc=11
|
||||
trials=4194296 split_pass=99 codewords=99 candidates=11
|
||||
time=0.303 s rate=13840509 trials/s
|
||||
cands_hash=0x3f83e1d877fff106
|
||||
original among candidates: YES
|
||||
@@ -0,0 +1,9 @@
|
||||
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
|
||||
flipped 12 bits at: 1213157 78591 1181322 103384 1872122 2087522 3012246 3571933 208726 2725019 1244306 726765
|
||||
control: standard decode fails as expected
|
||||
suspects: 0
|
||||
cuda: nc=13
|
||||
trials=4194296 split_pass=117 codewords=117 candidates=13
|
||||
time=0.321 s rate=13085423 trials/s
|
||||
cands_hash=0xaa142dccd701c52f
|
||||
original among candidates: NO
|
||||
@@ -0,0 +1,9 @@
|
||||
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
|
||||
flipped 9 bits at: 3522960 2484215 2732983 881566 254204 1579905 254093 3743235 1848401
|
||||
control: standard decode fails as expected
|
||||
suspects: 0
|
||||
cuda: nc=17
|
||||
trials=4194296 split_pass=153 codewords=153 candidates=17
|
||||
time=0.340 s rate=12347934 trials/s
|
||||
cands_hash=0xdca91931a24c5d24
|
||||
original among candidates: YES
|
||||
@@ -0,0 +1,9 @@
|
||||
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
|
||||
flipped 11 bits at: 3292058 983773 450541 316762 2999583 1512213 3313778 3882320 2021991 1212694 1933913
|
||||
control: standard decode fails as expected
|
||||
suspects: 0
|
||||
cuda: nc=12
|
||||
trials=4194296 split_pass=108 codewords=108 candidates=12
|
||||
time=0.317 s rate=13216590 trials/s
|
||||
cands_hash=0x42fd41c1b975b1f5
|
||||
original among candidates: NO
|
||||
@@ -0,0 +1,9 @@
|
||||
poly: m=22 t=8 r=176 id=0050 D=524265 stored=524287 nbits=4194296
|
||||
flipped 12 bits at: 2923071 2946792 2830609 3426044 2307790 3343130 3761171 3197071 889853 557680 1404485 682587
|
||||
control: standard decode fails as expected
|
||||
suspects: 9
|
||||
cuda: nc=12
|
||||
trials=4194296 split_pass=108 codewords=108 candidates=12
|
||||
time=0.312 s rate=13429427 trials/s
|
||||
cands_hash=0x1aff72716b878008
|
||||
original among candidates: NO
|
||||
@@ -0,0 +1,64 @@
|
||||
control probe nerr=7 rc=1 : control FAILED: standard decode succeeded on 7-error word
|
||||
control probe nerr=8 rc=1 : control FAILED: standard decode succeeded on 8-error word
|
||||
=== cuda seed=11 nerr=9 2026-12-04T01:22:42Z ===
|
||||
done cuda seed=11 nerr=9 susp=6 cands=13 time=0.362s hash=0x5c7f589a39df28b8 orig=YES
|
||||
=== cuda seed=21 nerr=9 2026-12-04T01:22:43Z ===
|
||||
done cuda seed=21 nerr=9 susp=3 cands=18 time=0.352s hash=0x9fbf8f81ead3e086 orig=YES
|
||||
=== cuda seed=101 nerr=9 2026-12-04T01:22:44Z ===
|
||||
done cuda seed=101 nerr=9 susp=6 cands=9 time=0.292s hash=0xc3dc7b7528027f2c orig=YES
|
||||
=== cuda seed=777 nerr=9 2026-12-04T01:22:45Z ===
|
||||
done cuda seed=777 nerr=9 susp=3 cands=11 time=0.303s hash=0x3f83e1d877fff106 orig=YES
|
||||
=== cuda seed=31337 nerr=9 2026-12-04T01:22:46Z ===
|
||||
done cuda seed=31337 nerr=9 susp=0 cands=13 time=0.321s hash=0x67fdae628952aa68 orig=YES
|
||||
=== cuda seed=8675309 nerr=9 2026-12-04T01:22:47Z ===
|
||||
done cuda seed=8675309 nerr=9 susp=0 cands=17 time=0.340s hash=0xdca91931a24c5d24 orig=YES
|
||||
=== cuda seed=12 nerr=10 2026-12-04T01:22:48Z ===
|
||||
FAILED rc=1 seed=12 nerr=10 impl=cuda (see sweep2/cuda-seed12-nerr10.log)
|
||||
=== cuda seed=22 nerr=10 2026-12-04T01:22:48Z ===
|
||||
FAILED rc=1 seed=22 nerr=10 impl=cuda (see sweep2/cuda-seed22-nerr10.log)
|
||||
=== cuda seed=100 nerr=10 2026-12-04T01:22:49Z ===
|
||||
FAILED rc=1 seed=100 nerr=10 impl=cuda (see sweep2/cuda-seed100-nerr10.log)
|
||||
=== cuda seed=1234 nerr=10 2026-12-04T01:22:50Z ===
|
||||
FAILED rc=1 seed=1234 nerr=10 impl=cuda (see sweep2/cuda-seed1234-nerr10.log)
|
||||
=== cuda seed=55555 nerr=10 2026-12-04T01:22:51Z ===
|
||||
FAILED rc=1 seed=55555 nerr=10 impl=cuda (see sweep2/cuda-seed55555-nerr10.log)
|
||||
=== cuda seed=424242 nerr=10 2026-12-04T01:22:53Z ===
|
||||
FAILED rc=1 seed=424242 nerr=10 impl=cuda (see sweep2/cuda-seed424242-nerr10.log)
|
||||
=== cuda seed=13 nerr=11 2026-12-04T01:22:54Z ===
|
||||
FAILED rc=1 seed=13 nerr=11 impl=cuda (see sweep2/cuda-seed13-nerr11.log)
|
||||
=== cuda seed=31 nerr=11 2026-12-04T01:22:54Z ===
|
||||
FAILED rc=1 seed=31 nerr=11 impl=cuda (see sweep2/cuda-seed31-nerr11.log)
|
||||
=== cuda seed=2024 nerr=11 2026-12-04T01:22:55Z ===
|
||||
FAILED rc=1 seed=2024 nerr=11 impl=cuda (see sweep2/cuda-seed2024-nerr11.log)
|
||||
=== cuda seed=11111 nerr=11 2026-12-04T01:22:56Z ===
|
||||
FAILED rc=1 seed=11111 nerr=11 impl=cuda (see sweep2/cuda-seed11111-nerr11.log)
|
||||
=== cuda seed=98765 nerr=11 2026-12-04T01:22:57Z ===
|
||||
FAILED rc=1 seed=98765 nerr=11 impl=cuda (see sweep2/cuda-seed98765-nerr11.log)
|
||||
=== cuda seed=22222 nerr=11 2026-12-04T01:22:58Z ===
|
||||
FAILED rc=1 seed=22222 nerr=11 impl=cuda (see sweep2/cuda-seed22222-nerr11.log)
|
||||
=== cuda seed=14 nerr=12 2026-12-04T01:22:59Z ===
|
||||
FAILED rc=1 seed=14 nerr=12 impl=cuda (see sweep2/cuda-seed14-nerr12.log)
|
||||
=== cuda seed=42 nerr=12 2026-12-04T01:23:00Z ===
|
||||
FAILED rc=1 seed=42 nerr=12 impl=cuda (see sweep2/cuda-seed42-nerr12.log)
|
||||
=== cuda seed=1000 nerr=12 2026-12-04T01:23:01Z ===
|
||||
FAILED rc=1 seed=1000 nerr=12 impl=cuda (see sweep2/cuda-seed1000-nerr12.log)
|
||||
=== cuda seed=54321 nerr=12 2026-12-04T01:23:02Z ===
|
||||
FAILED rc=1 seed=54321 nerr=12 impl=cuda (see sweep2/cuda-seed54321-nerr12.log)
|
||||
=== cuda seed=77777 nerr=12 2026-12-04T01:23:03Z ===
|
||||
FAILED rc=1 seed=77777 nerr=12 impl=cuda (see sweep2/cuda-seed77777-nerr12.log)
|
||||
=== cuda seed=999999 nerr=12 2026-12-04T01:23:04Z ===
|
||||
FAILED rc=1 seed=999999 nerr=12 impl=cuda (see sweep2/cuda-seed999999-nerr12.log)
|
||||
=== cpu seed=11 nerr=9 2026-12-04T01:23:05Z ===
|
||||
done cpu seed=11 nerr=9 susp=6 cands=13 time=166.680s hash=0x5c7f589a39df28b8 orig=YES
|
||||
=== cpu seed=22 nerr=10 2026-12-04T01:25:52Z ===
|
||||
FAILED rc=1 seed=22 nerr=10 impl=cpu (see sweep2/cpu-seed22-nerr10.log)
|
||||
=== cpu seed=2024 nerr=11 2026-12-04T01:28:37Z ===
|
||||
FAILED rc=1 seed=2024 nerr=11 impl=cpu (see sweep2/cpu-seed2024-nerr11.log)
|
||||
=== cpu seed=42 nerr=12 2026-12-04T01:31:17Z ===
|
||||
FAILED rc=1 seed=42 nerr=12 impl=cpu (see sweep2/cpu-seed42-nerr12.log)
|
||||
=== cpu seed=31337 nerr=9 2026-12-04T01:34:04Z ===
|
||||
done cpu seed=31337 nerr=9 susp=0 cands=13 time=168.330s hash=0x67fdae628952aa68 orig=YES
|
||||
match column filled
|
||||
SWEEP DONE 2026-12-04T01:36:53Z
|
||||
.330s hash=0x67fdae628952aa68 orig=YES
|
||||
SWEEP DONE 2026-12-04T01:36:53Z
|
||||
@@ -0,0 +1,46 @@
|
||||
import glob, os, re, csv
|
||||
rows = []
|
||||
for path in sorted(glob.glob("sweep2/*-seed*-nerr*.log")):
|
||||
m = re.match(r"sweep2/(cpu|cuda)-seed(\d+)-nerr(\d+)\.log", path)
|
||||
if not m: continue
|
||||
impl, seed, nerr = m.group(1), int(m.group(2)), int(m.group(3))
|
||||
txt = open(path).read()
|
||||
def g(pat):
|
||||
mm = re.search(pat, txt, re.M)
|
||||
return mm.group(1) if mm else ""
|
||||
ctrl_fail = "control FAILED" in txt
|
||||
rows.append(dict(seed=seed, nerr=nerr, impl=impl,
|
||||
suspects=g(r"^suspects: (\d+)") or ("CTRL-FAIL" if ctrl_fail else ""),
|
||||
trials=g(r"^trials=(\d+)"),
|
||||
split_pass=g(r"split_pass=(\d+)"),
|
||||
codewords=g(r"codewords=(\d+)"),
|
||||
candidates=g(r"candidates=(\d+)"),
|
||||
time_s=g(r"^time=([0-9.]+)"), rate=g(r"rate=(\d+)"),
|
||||
hash=g(r"^cands_hash=(0x[0-9a-f]+)"),
|
||||
original=g(r"^original among candidates: ([A-Z]+)"),
|
||||
partial=g(r"partial=(\d+)"),
|
||||
note="control-fail: std decode succeeds (nerr<=t)" if ctrl_fail else ""))
|
||||
cuda = {(r["seed"], r["nerr"]): r["hash"] for r in rows if r["impl"]=="cuda" and r["hash"]}
|
||||
for r in rows:
|
||||
if r["impl"]=="cpu" and r["hash"]:
|
||||
k=(r["seed"], r["nerr"])
|
||||
r["match"] = "Y" if k in cuda and cuda[k]==r["hash"] else ("N" if k in cuda else "?")
|
||||
else:
|
||||
r["match"] = ""
|
||||
rows.sort(key=lambda r:(r["nerr"], r["seed"], r["impl"]))
|
||||
with open("sweep2/summary.csv","w",newline="") as f:
|
||||
w=csv.DictWriter(f, fieldnames=["seed","nerr","impl","suspects","trials","split_pass","codewords","candidates","time_s","rate_trials_s","hash","original","partial","match","note"])
|
||||
w.writeheader()
|
||||
for r in rows:
|
||||
w.writerow({"seed":r["seed"],"nerr":r["nerr"],"impl":r["impl"],"suspects":r["suspects"],"trials":r["trials"],"split_pass":r["split_pass"],"codewords":r["codewords"],"candidates":r["candidates"],"time_s":r["time_s"],"rate_trials_s":r["rate"],"hash":r["hash"],"original":r["original"],"partial":r["partial"],"match":r["match"],"note":r["note"]})
|
||||
print("rows:", len(rows))
|
||||
# speedup stats for cpu-verified pairs
|
||||
pairs=[]
|
||||
for r in rows:
|
||||
if r["impl"]=="cpu" and r["hash"]:
|
||||
c=[x for x in rows if x["impl"]=="cuda" and x["seed"]==r["seed"] and x["nerr"]==r["nerr"]]
|
||||
if c: pairs.append((r["seed"],r["nerr"],float(r["time_s"]),float(c[0]["time_s"])))
|
||||
for s,n,ct,gt in pairs:
|
||||
print(f"seed {s} nerr {n}: cpu {ct:.3f}s / cuda {gt:.3f}s = {ct/gt:.1f}x")
|
||||
print("max_cands hits (partial=1 or candidates>=64):", [ (r["seed"],r["nerr"],r["impl"],r["candidates"],r["partial"]) for r in rows if r["partial"]=="1" or (r["candidates"].isdigit() and int(r["candidates"])>=64) ])
|
||||
print("mismatches:", [ (r["seed"],r["nerr"]) for r in rows if r["match"]=="N" ])
|
||||
Executable
+78
@@ -0,0 +1,78 @@
|
||||
#!/bin/bash
|
||||
# Chase-1 extended benchmark sweep #2 — hot_house (parrot), RTX 3080 Ti
|
||||
# Branch experiments/cuda-chase @ 368644a. Read-only benchmarking; no commits/pushes.
|
||||
# CUDA on all patterns; CPU on 5 spread across nerr values.
|
||||
# NOTE: nerr 7/8 cannot run the Chase scan: t=8 standard decode corrects
|
||||
# them, so the harness control check fails by design. Valid nerr: 9-12.
|
||||
set -u
|
||||
cd /root/cuda-chase/lzply || exit 1
|
||||
mkdir -p sweep2
|
||||
SUM=sweep2/summary.csv
|
||||
echo "seed,nerr,impl,suspects,trials,split_pass,codewords,candidates,time_s,rate_trials_s,hash,original,match" > "$SUM"
|
||||
|
||||
run_one() { # $1=impl(cpu|cuda) $2=seed $3=nerr
|
||||
local impl="$1" seed="$2" nerr="$3"
|
||||
local bin="./chase_bench_cpu" flag="--cpu"
|
||||
[ "$impl" = "cuda" ] && { bin="./chase_bench_cuda"; flag="--cuda"; }
|
||||
local log="sweep2/${impl}-seed${seed}-nerr${nerr}.log"
|
||||
echo "=== $impl seed=$seed nerr=$nerr $(date -u +%FT%TZ) ===" | tee -a sweep2/driver.log
|
||||
"$bin" $flag --seed "$seed" --nerr "$nerr" > "$log" 2>&1
|
||||
local rc=$?
|
||||
if [ $rc -ne 0 ]; then
|
||||
echo "FAILED rc=$rc seed=$seed nerr=$nerr impl=$impl (see $log)" | tee -a sweep2/driver.log
|
||||
echo "$seed,$nerr,$impl,,,,,,,,,,rc=$rc" >> "$SUM"
|
||||
return 1
|
||||
fi
|
||||
local susp trials sp cw nc t rate hash orig
|
||||
susp=$(grep -oP '^suspects: \K[0-9]+' "$log" || echo "?")
|
||||
trials=$(grep -oP '^trials=\K[0-9]+' "$log" || echo "?")
|
||||
sp=$(grep -oP 'split_pass=\K[0-9]+' "$log" || echo "?")
|
||||
cw=$(grep -oP 'codewords=\K[0-9]+' "$log" || echo "?")
|
||||
nc=$(grep -oP 'candidates=\K[0-9]+' "$log" || echo "?")
|
||||
t=$(grep -oP '^time=\K[0-9.]+' "$log" || echo "?")
|
||||
rate=$(grep -oP 'rate=\K[0-9]+' "$log" || echo "?")
|
||||
hash=$(grep -oP '^cands_hash=\K0x[0-9a-f]+' "$log" || echo "?")
|
||||
orig=$(grep -oP '^original among candidates: \K[A-Z]+' "$log" || echo "?")
|
||||
echo "$seed,$nerr,$impl,$susp,$trials,$sp,$cw,$nc,$t,$rate,$hash,$orig," >> "$SUM"
|
||||
echo "done $impl seed=$seed nerr=$nerr susp=$susp cands=$nc time=${t}s hash=$hash orig=$orig" | tee -a sweep2/driver.log
|
||||
return 0
|
||||
}
|
||||
|
||||
# Control probes: nerr 7/8 expected to fail (standard decode succeeds)
|
||||
for n in 7 8; do
|
||||
./chase_bench_cuda --cuda --seed 11 --nerr "$n" > "sweep2/cuda-seed11-nerr${n}.log" 2>&1
|
||||
echo "control probe nerr=$n rc=$? : $(tail -1 sweep2/cuda-seed11-nerr${n}.log)" | tee -a sweep2/driver.log
|
||||
done
|
||||
|
||||
# CUDA sweep: 24 new patterns, 6 seeds x nerr 9/10/11/12
|
||||
for n in 9 10 11 12; do
|
||||
case $n in
|
||||
9) seeds="11 21 101 777 31337 8675309" ;;
|
||||
10) seeds="12 22 100 1234 55555 424242" ;;
|
||||
11) seeds="13 31 2024 11111 98765 22222" ;;
|
||||
12) seeds="14 42 1000 54321 77777 999999" ;;
|
||||
esac
|
||||
for s in $seeds; do run_one cuda "$s" "$n"; done
|
||||
done
|
||||
|
||||
# CPU verification on 5 patterns spread across nerr/suspects (~170 s each)
|
||||
for spec in "11 9" "22 10" "2024 11" "42 12" "31337 9"; do
|
||||
set -- $spec; run_one cpu "$1" "$2"
|
||||
done
|
||||
|
||||
# Hash-match check: append match=Y/N to CPU rows by comparing with CUDA rows
|
||||
python3 - <<'PYEOF'
|
||||
import csv
|
||||
rows = list(csv.DictReader(open('sweep2/summary.csv')))
|
||||
cuda = {(r['seed'], r['nerr']): r['hash'] for r in rows if r['impl'] == 'cuda' and r['hash']}
|
||||
for r in rows:
|
||||
if r['impl'] == 'cpu' and r['hash']:
|
||||
k = (r['seed'], r['nerr'])
|
||||
r['match'] = 'Y' if k in cuda and cuda[k] == r['hash'] else ('N' if k in cuda else '?')
|
||||
with open('sweep2/summary.csv', 'w', newline='') as f:
|
||||
w = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
|
||||
w.writeheader(); w.writerows(rows)
|
||||
print("match column filled")
|
||||
PYEOF
|
||||
|
||||
echo "SWEEP DONE $(date -u +%FT%TZ)" | tee -a sweep2/driver.log
|
||||
@@ -0,0 +1,32 @@
|
||||
seed,nerr,impl,suspects,trials,split_pass,codewords,candidates,time_s,rate_trials_s,hash,original,partial,match,note
|
||||
11,7,cuda,CTRL-FAIL,,,,,,,,,,,control-fail: std decode succeeds (nerr<=t)
|
||||
11,8,cuda,CTRL-FAIL,,,,,,,,,,,control-fail: std decode succeeds (nerr<=t)
|
||||
11,9,cpu,6,4194296,117,117,13,166.680,25164,0x5c7f589a39df28b8,YES,0,Y,
|
||||
11,9,cuda,6,4194296,117,117,13,0.362,11601794,0x5c7f589a39df28b8,YES,,,
|
||||
21,9,cuda,3,4194296,162,162,18,0.352,11929751,0x9fbf8f81ead3e086,YES,,,
|
||||
101,9,cuda,6,4194296,81,81,9,0.292,14373237,0xc3dc7b7528027f2c,YES,,,
|
||||
777,9,cuda,3,4194296,99,99,11,0.303,13840509,0x3f83e1d877fff106,YES,,,
|
||||
31337,9,cpu,0,4194296,117,117,13,168.330,24917,0x67fdae628952aa68,YES,0,Y,
|
||||
31337,9,cuda,0,4194296,117,117,13,0.321,13079187,0x67fdae628952aa68,YES,,,
|
||||
8675309,9,cuda,0,4194296,153,153,17,0.340,12347934,0xdca91931a24c5d24,YES,,,
|
||||
12,10,cuda,0,4194296,126,126,14,0.332,12630048,0x2478043cdde3ae3e,NO,,,
|
||||
22,10,cpu,12,4194296,99,99,11,164.670,25471,0x56c63d470502aee8,NO,0,Y,
|
||||
22,10,cuda,12,4194296,99,99,11,0.311,13481690,0x56c63d470502aee8,NO,,,
|
||||
100,10,cuda,3,4194296,90,90,10,0.305,13738008,0xf0ac78a5c0db6077,NO,,,
|
||||
1234,10,cuda,3,4194296,108,108,12,0.322,13016562,0x06acc3a69443d342,NO,,,
|
||||
55555,10,cuda,3,4194296,72,72,8,0.290,14475440,0x41d95f8afa6ba1ce,NO,,,
|
||||
424242,10,cuda,3,4194296,117,117,13,0.326,12848095,0x69622442a318139d,NO,,,
|
||||
13,11,cuda,0,4194296,99,99,11,0.315,13299619,0xd0e203ae5074c351,NO,,,
|
||||
31,11,cuda,0,4194296,108,108,12,0.318,13172288,0xc2ce80d884c0de3a,NO,,,
|
||||
2024,11,cpu,0,4194296,63,63,7,159.671,26268,0x64657c5daf8fe7bd,NO,0,Y,
|
||||
2024,11,cuda,0,4194296,63,63,7,0.284,14768929,0x64657c5daf8fe7bd,NO,,,
|
||||
11111,11,cuda,0,4194296,90,90,10,0.309,13562801,0x0828e3f1a1de3768,NO,,,
|
||||
22222,11,cuda,3,4194296,144,144,16,0.334,12569297,0xab869c50c89764d7,NO,,,
|
||||
98765,11,cuda,0,4194296,108,108,12,0.317,13216590,0x42fd41c1b975b1f5,NO,,,
|
||||
14,12,cuda,0,4194296,81,81,9,0.285,14727206,0xa817ea75c23a4634,NO,,,
|
||||
42,12,cpu,6,4194296,117,117,13,166.697,25161,0x7e36640193d2f371,NO,0,Y,
|
||||
42,12,cuda,6,4194296,117,117,13,0.315,13309357,0x7e36640193d2f371,NO,,,
|
||||
1000,12,cuda,6,4194296,117,117,13,0.316,13258809,0xff1b6acdbcda946e,NO,,,
|
||||
54321,12,cuda,3,4194296,135,135,15,0.332,12614960,0xf6dc42abffaa291f,NO,,,
|
||||
77777,12,cuda,0,4194296,117,117,13,0.321,13085423,0xaa142dccd701c52f,NO,,,
|
||||
999999,12,cuda,9,4194296,108,108,12,0.312,13429427,0x1aff72716b878008,NO,,,
|
||||
|
Loaded 100 of 103 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user