You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Wave8 opt: optimize the Wave8 nibble-LUT expansion (~55%% of encode) #2526
The Wave8 nibble-LUT expansion runs 16 lanes x 768 byte-positions per frame and is part of the ~55% of encode time NOT in the transpose. Profile it in isolation (extend benchMem) and tighten: wider lookups, fewer stores, confirm inlining/IRAM.
Deep-dive: maximizing the Wave8 nibble-LUT expansion
Investigated the expansion in the current codebase and worked through the optimization space. Summary up front: the highest-leverage in-scope win is a byte-indexed (256×8) LUT — it ~halves the per-byte instruction count for the same memory traffic, which matters because this stage is instruction-issue-bound on the in-order RV32 core, not bandwidth-bound. IRAM/inlining is already correct, so that box is checked. The bigger structural prize (killing the intermediate-buffer round-trip) belongs to the expand+transpose fusion in #2525.
The operation (ground truth in the code)
detail::wave8_convert_byte_to_wave8byte() (src/fl/channels/detail/wave8.hpp:46), per input byte:
hi = (byte>>4)&0xF; memcpy_32(&out.symbols[0], lut.lut[hi], 1) → 1×lw + 1×sw
lo = byte&0xF; memcpy_32(&out.symbols[4], lut.lut[lo], 1) → 1×lw + 1×sw
LUT: Wave8BitExpansionLut { Wave8Bit lut[16][4]; } = 64 bytes, shared by both nibbles (wave8.h:45).
memcpy_32(dst,src,1) is a plain dst[0]=src[0] → a single lw/sw (verified, no overhead).
Call site: wave8Transpose_16() (wave8.cpp.hpp:73, already FL_IRAM FL_OPTIMIZE_FUNCTION) expands all 16 lanes into a 128-byte stack buffer laneWaveformSymbols[16], then wave8_transpose_16() reads that buffer back.
One lookup instead of two; no >>4/mask; index is just byte*8.
slli; add; lw; lw; sw; sw # ≈6 instrs, 2 lw, 2 sw
~45% fewer instructions per expansion, same memory traffic (2 lw + 2 sw). Table grows 64 B → 2 KB. On the P4 (128 KB L2, internal SRAM) that's 32 cache lines — resident after the first frame; cold-cache cost is one-time and negligible.
Build once (endianness-safe — copy bytes, don't pack arithmetically):
structFL_ALIGNAS(8) Wave8ByteExpansionLut { Wave8Byte lut[256]; }; // 2 KB// for b in 0..255: lut[b].symbols[0..3] = nibbleLut[b>>4]; lut[b].symbols[4..7] = nibbleLut[b&0xF];
ISR expansion collapses to one indexed 8-byte copy:
Predicted: if expansion is ~55% of encode and this trims it ~30–45%, full encode drops ~17–25% (~1.2–1.3×) — on top of the shipped spread-LUT transpose win. Validate on device before claiming.
S2 — u64-typed entry / single load+store pair
Make the entry a u64 (or bit_cast) so the compiler emits the tightest paired lw/lw+sw/sw with one index. No RV32 u64 penalty here — there's no 64-bit arithmetic, it's just a load/store pair (the u64 penalty only bit us in SWAR math, see #2533). Folds into S1.
S3 — Batch the 16-lane loop (load-all-then-store-all) for ILP
The 16 per-lane expansions are independent. Split the loop so all 16 table loads issue before the stores:
This hides load-use latency on the in-order core — the same "independent ops, no dependency chain" shape that made the spread-LUT transpose win (#2534). Static instruction count is unchanged; the gain is latency-hiding, so it's measurement-dependent (small if L1-hit latency is 1–2 cycles, larger if the table ever spills toward PSRAM).
S4 — Eliminate the intermediate-buffer round-trip (cross-cuts #2525)
Today: expand → write 128 B to laneWaveformSymbols[16] → transpose reads 128 B back, per byte-position. That round-trip is pure overhead that S1 makes cheaper but doesn't remove. Removing it is the combined expand+transpose LUT in #2525 — the structural ceiling for this whole area. Recommend doing S1 here, then #2525 for the round-trip. (A per-byte LUT can't emit transposed output alone — that needs all lanes — so full fusion stays in #2525.)
S5 — Placement / inlining (the "confirm IRAM" item)
✅ Already good: wave8_convert_byte_to_wave8byte is FORCE_INLINE FL_IRAM; wave8Transpose_16 is FL_IRAM; memcpy_32(…,1) lowers to one lw/sw.
⚠️ For the 2 KB byte-LUT, pin it in internal SRAM, not PSRAM (PSRAM random-access latency would erase S1's gains). Keep it next to mWave8Lut on the engine object.
Compute-instead-of-LUT — the nibble→pulse mapping is an arbitrary timing-derived pattern; a LUT is already optimal. Computing it would be strictly slower.
Measurement plan (extend benchMem, per the issue)
Add an isolated expansion micro-bench to the AutoResearch harness comparing nibble-LUT vs byte-LUT (S1) vs batched byte-LUT (S3) over 16 lanes × 768 positions, with a volatile sink to defeat DCE, measured warm and cold cache; report ns/expansion and full encode_us before/after (4/8/16 lanes). Gate on bit-exactness vs the nibble-LUT reference (host test first).
⚠️ Infra note: on ESP32-P4, build/flash via bash autoresearch esp32p4 --simd --no-fbuild (PlatformIO) — fbuild currently produces non-booting P4 images, and the serial RPC path has a UART0-vs-USB-JTAG routing issue (see #2536/#2538). x86 host timing is for correctness only — it does not rank correctly for the in-order core (#2533).
Recommendation
S1 (byte-LUT) + S2 — the main win; small, low-risk, bit-exact, ~1.2–1.3× encode predicted.
S3 (batched loads) if device numbers show load-use stalls.
Result: implemented + benchmarked on ESP32-P4 — prediction confirmed (1.66×)
Followed the deep-dive comment above and implemented the byte-indexed (256×8) LUT (S1). Measured against the current nibble path with a boot-time micro-bench, run on a real ESP32-P4 (revision v1.3). Output via esp_rom_printf → USB-Serial-JTAG console so it lands on COM25 directly (sidesteps the testSimd RPC's UART0-vs-USB-JTAG block — see #2536/#2538).
Prediction was ~30–45% expansion-time reduction → ~1.2–1.3× full encode. Measured: 40% expansion-time reduction → predicts ~1.28× full encode (at expansion ≈ 55% of encode). Win confirmed; S3 (batched, ILP) gives a further ~6% on top of S1 — the same independent-ops shape that won for the spread-LUT transpose (#2534).
Byte-LUT overloads of wave8Transpose_{2,4,8,16}; PARLIO engine routes all 5 hot expansion call sites through it.
Host test verifies bit-exact equivalence across all 256 input bytes.
Caveats / notes
sink=0 in the bench output is expected: the volatile XOR sink accumulates (it mod 256) ^ (~it mod 256) over 30k iters → cancels. The three loops still ran (proven by the meaningfully different timings).
Full encode_us before/after couldn't be measured directly on this run — the measureParlio RPC path is blocked by the same UART0-vs-USB-JTAG routing as testSimd. The expansion-stage speedup implies the predicted full-encode drop arithmetically; capturing it end-to-end will land once the P4 serial-routing infra fix the user mentioned is in.
The 2 KB LUT lives on the engine object (internal SRAM, not PSRAM) so the lookup stays fast.
Follow-up: measured the real production per-byte-position cost (not just isolated expansion)
Per review feedback on PR #2539, the bench was refactored to also time wave8Transpose_16(lanes, lut, output) — the actual hot path the PARLIO engine calls 768 times per frame — for both LUTs. Same input, same output, same transpose step; only the expansion inside changes. The bench is now RPC-driven (wave8ExpandBenchmark) with no boot-time computation by default; an -DFL_BENCH_WAVE8_AT_BOOT=1 bridge runs it once at boot until the testSimd RPC routing on P4 is fixed (#2541).
Measured on ESP32-P4 v1.3, 30,000 byte-positions per measurement
The production per-byte-position cost (expansion + 16-lane transpose, exactly what parlio_engine calls for mDataWidth==16) drops 1.54× with the byte-LUT.
The hot-loop saves ~4.76 ms per frame at 256 LEDs × 3 colors × 16 lanes (768 byte-positions).
Isolated expansion is faster (1.66×) because the transpose step inside wave8Transpose_16 is the same regardless of LUT and adds fixed cost — so the realized speedup at the production granularity is between the expansion-only number and the full-encode number that we'll get from measureParlio once bug(esp32p4): testSimd RPC write-timeout — Serial routes to UART0 instead of USB-Serial-JTAG #2541 lands.
Batched (S3) gives ~3% on top of S1 — much smaller than seen elsewhere because the in-order RV32 core is already pipelining the single byte-LUT loads well. Probably not worth the code complexity unless data later changes.
Honest caveat
Full encode_us (which adds DMA setup, ring management, ISR overhead beyond the hot loop) still requires measureParlio — blocked by #2541. The 1.54× figure here is directly measured on the production code path for the section #2526 actually optimizes; the wider encode_us speedup is bounded above by 1.54× and depends on what fraction of encode lives in that hot loop.
Closing as the byte-LUT optimization #2526 asked for is implemented, integrated into the parlio engine, host-test-equivalent, and measured on real hardware.
Follow-up benchmark: full PARLIO encode (16×256) post-byte-LUT, with the PSRAM hypothesis settled
Added parlioEncodeBenchmark (RPC + boot-time bridge in AutoResearchParlioEncode.h, PR coming) that replicates the engine's per-byte-position hot path — 16-lane gather + wave8Transpose_16(byteLut) + memcpy 128 B — and times it with the source scratch and the DMA output each in SRAM or PSRAM (4 placements).
Measured on ESP32-P4 v1.3 — 12,000 byte-positions per placement
All four placements land within ~0.7% of each other (ratio_x100 = 99 for every PSRAM variant vs SRAM/SRAM — PSRAM is even fractionally faster, which is noise). The P4's L2 cache fully hides PSRAM latency for the strided-16 gather + sequential 128 B writes the engine does. This matches the prior session's separate ×1.00 measurement (memory note: "PSRAM is NOT slow on the P4 for this pattern"). The PSRAM theory is decisively not the bottleneck; don't chase it further.
2. ISR-chunked streaming feasibility → NOT YET fast enough
Encode: 9,651 µs / frame (SRAM/SRAM, full hot loop)
WS2812B TX: 7,680 µs / frame
Deficit: 1,971 µs (CPU is ~26% slower than DMA drain)
The CPU produces a frame ~26% slower than the DMA can consume it. ISR-chunked streaming would underrun without further optimization. We need encode to drop to ≤ 7,680 µs (just feasible, no safety margin) or, more realistically, ≤ 6,000 µs (~25% headroom).
Halves both — doesn't change the encode/TX ratio (still ~1.26×), so it alone does not enable streaming. But it halves total frame time and DMA RAM, and stacks with the above.
1.66× on isolated expansion / 1.54× on full hot loop.
Recommendation:#2527 (dual-core) is the clear cleanest path to ISR-chunked-streaming feasibility — alone it should push encode from 9.65 → ~5.4 ms, ~30% margin under TX. #2525 (fusion) stacks on top, and after that #2523 (WaveN) for total-frame-time wins.
Notes
The 9.65 ms figure is the engine's hot loop only (gather + transpose + memcpy). The real populateDmaBuffer also handles padding, dispatch, etc. — slightly above this.
Activity
zackees commentedon May 29, 2026
Deep-dive: maximizing the Wave8 nibble-LUT expansion
Investigated the expansion in the current codebase and worked through the optimization space. Summary up front: the highest-leverage in-scope win is a byte-indexed (256×8) LUT — it ~halves the per-byte instruction count for the same memory traffic, which matters because this stage is instruction-issue-bound on the in-order RV32 core, not bandwidth-bound. IRAM/inlining is already correct, so that box is checked. The bigger structural prize (killing the intermediate-buffer round-trip) belongs to the expand+transpose fusion in #2525.
The operation (ground truth in the code)
detail::wave8_convert_byte_to_wave8byte()(src/fl/channels/detail/wave8.hpp:46), per input byte:hi = (byte>>4)&0xF;memcpy_32(&out.symbols[0], lut.lut[hi], 1)→ 1×lw+ 1×swlo = byte&0xF;memcpy_32(&out.symbols[4], lut.lut[lo], 1)→ 1×lw+ 1×swWave8BitExpansionLut { Wave8Bit lut[16][4]; }= 64 bytes, shared by both nibbles (wave8.h:45).memcpy_32(dst,src,1)is a plaindst[0]=src[0]→ a singlelw/sw(verified, no overhead).wave8Transpose_16()(wave8.cpp.hpp:73, alreadyFL_IRAM FL_OPTIMIZE_FUNCTION) expands all 16 lanes into a 128-byte stack bufferlaneWaveformSymbols[16], thenwave8_transpose_16()reads that buffer back.Why it's a cost: static RV32 instruction count (table is SRAM/cache-resident → loads cheap)
Current nibble path, per byte (≈11 instrs, 2
lw, 2sw):Per frame ≈ 12,288 × 11 ≈ 135k instructions just for indexing/moving (plus the 128B buffer write, then re-read by the transpose).
So the stage is dominated by index arithmetic + issue width, not data volume (only 8 B moved per byte). That's exactly where a wider table helps.
Strategies (ranked)
S1 — Byte-indexed 256×8 LUT ⟵ primary, the issue's "wider lookups / fewer stores"
One lookup instead of two; no
>>4/mask; index is justbyte*8.~45% fewer instructions per expansion, same memory traffic (2
lw+ 2sw). Table grows 64 B → 2 KB. On the P4 (128 KB L2, internal SRAM) that's 32 cache lines — resident after the first frame; cold-cache cost is one-time and negligible.Build once (endianness-safe — copy bytes, don't pack arithmetically):
ISR expansion collapses to one indexed 8-byte copy:
Predicted: if expansion is ~55% of encode and this trims it ~30–45%, full encode drops ~17–25% (~1.2–1.3×) — on top of the shipped spread-LUT transpose win. Validate on device before claiming.
S2 — u64-typed entry / single load+store pair
Make the entry a
u64(orbit_cast) so the compiler emits the tightest pairedlw/lw+sw/swwith one index. No RV32 u64 penalty here — there's no 64-bit arithmetic, it's just a load/store pair (the u64 penalty only bit us in SWAR math, see #2533). Folds into S1.S3 — Batch the 16-lane loop (load-all-then-store-all) for ILP
The 16 per-lane expansions are independent. Split the loop so all 16 table loads issue before the stores:
This hides load-use latency on the in-order core — the same "independent ops, no dependency chain" shape that made the spread-LUT transpose win (#2534). Static instruction count is unchanged; the gain is latency-hiding, so it's measurement-dependent (small if L1-hit latency is 1–2 cycles, larger if the table ever spills toward PSRAM).
S4 — Eliminate the intermediate-buffer round-trip (cross-cuts #2525)
Today: expand → write 128 B to
laneWaveformSymbols[16]→ transpose reads 128 B back, per byte-position. That round-trip is pure overhead that S1 makes cheaper but doesn't remove. Removing it is the combined expand+transpose LUT in #2525 — the structural ceiling for this whole area. Recommend doing S1 here, then #2525 for the round-trip. (A per-byte LUT can't emit transposed output alone — that needs all lanes — so full fusion stays in #2525.)S5 — Placement / inlining (the "confirm IRAM" item)
wave8_convert_byte_to_wave8byteisFORCE_INLINE FL_IRAM;wave8Transpose_16isFL_IRAM;memcpy_32(…,1)lowers to onelw/sw.mWave8Luton the engine object.Dead ends (documented so they aren't re-explored)
xesppie) has novgather/scatter with arbitrary indices, so it cannot vectorize a table lookup (consistent with Reverse-engineer ESP32-P4 PIE (xesppie) instruction set by experimentation (for a PIE transpose) #2535). Not viable.Measurement plan (extend
benchMem, per the issue)Add an isolated expansion micro-bench to the AutoResearch harness comparing nibble-LUT vs byte-LUT (S1) vs batched byte-LUT (S3) over 16 lanes × 768 positions, with a
volatilesink to defeat DCE, measured warm and cold cache; report ns/expansion and fullencode_usbefore/after (4/8/16 lanes). Gate on bit-exactness vs the nibble-LUT reference (host test first).Recommendation
Refs: parent #2524 · data #2522 · transpose precedent #2534 · fusion #2525 · PIE-no-gather #2535/#2538
zackees commentedon May 29, 2026
Result: implemented + benchmarked on ESP32-P4 — prediction confirmed (1.66×)
Followed the deep-dive comment above and implemented the byte-indexed (256×8) LUT (S1). Measured against the current nibble path with a boot-time micro-bench, run on a real ESP32-P4 (revision v1.3). Output via
esp_rom_printf→ USB-Serial-JTAG console so it lands on COM25 directly (sidesteps the testSimd RPC's UART0-vs-USB-JTAG block — see #2536/#2538).Numbers (
AutoResearchWave8Expand.h, 30,000 byte-positions × 16 lanes = 480,000 expansions/measurement)Prediction was ~30–45% expansion-time reduction → ~1.2–1.3× full encode. Measured: 40% expansion-time reduction → predicts ~1.28× full encode (at expansion ≈ 55% of encode). Win confirmed; S3 (batched, ILP) gives a further ~6% on top of S1 — the same independent-ops shape that won for the spread-LUT transpose (#2534).
Implementation (PR #2539)
Wave8ByteExpansionLut(256 × 8 = 2 KB) +buildWave8ByteExpansionLUT().detail::wave8_expand_byte()(one indexed 8-byte copy,FORCE_INLINE FL_IRAM).wave8Transpose_{2,4,8,16}; PARLIO engine routes all 5 hot expansion call sites through it.Caveats / notes
sink=0in the bench output is expected: the volatile XOR sink accumulates(it mod 256) ^ (~it mod 256)over 30k iters → cancels. The three loops still ran (proven by the meaningfully different timings).encode_usbefore/after couldn't be measured directly on this run — themeasureParlioRPC path is blocked by the same UART0-vs-USB-JTAG routing astestSimd. The expansion-stage speedup implies the predicted full-encode drop arithmetically; capturing it end-to-end will land once the P4 serial-routing infra fix the user mentioned is in.zackees commentedon May 29, 2026
Follow-up: measured the real production per-byte-position cost (not just isolated expansion)
Per review feedback on PR #2539, the bench was refactored to also time
wave8Transpose_16(lanes, lut, output)— the actual hot path the PARLIO engine calls 768 times per frame — for both LUTs. Same input, same output, same transpose step; only the expansion inside changes. The bench is now RPC-driven (wave8ExpandBenchmark) with no boot-time computation by default; an-DFL_BENCH_WAVE8_AT_BOOT=1bridge runs it once at boot until the testSimd RPC routing on P4 is fixed (#2541).Measured on ESP32-P4 v1.3, 30,000 byte-positions per measurement
wave8Transpose_16(production hot path)What it means
parlio_enginecalls formDataWidth==16) drops 1.54× with the byte-LUT.wave8Transpose_16is the same regardless of LUT and adds fixed cost — so the realized speedup at the production granularity is between the expansion-only number and the full-encode number that we'll get frommeasureParlioonce bug(esp32p4): testSimd RPC write-timeout — Serial routes to UART0 instead of USB-Serial-JTAG #2541 lands.Honest caveat
Full
encode_us(which adds DMA setup, ring management, ISR overhead beyond the hot loop) still requiresmeasureParlio— blocked by #2541. The 1.54× figure here is directly measured on the production code path for the section #2526 actually optimizes; the wider encode_us speedup is bounded above by 1.54× and depends on what fraction of encode lives in that hot loop.Refs PR #2539 · #2541 (RPC routing) · #2540 (FL_PRINT vs esp_rom_printf)
perf(wave8): byte-indexed expansion LUT (#2526) — 1.66x on ESP32-P4 (#…
zackees commentedon May 29, 2026
Done — landed via PR #2539 (merge commit
1150f2e307).Final measured result (ESP32-P4 v1.3):
wave8Transpose_16(production hot path: expansion + 16-lane transpose): 1.54x vs nibbleFollow-ups split out and tracked separately:
esp_rom_printfwithFL_PRINTonce routing is fixedrunSimdTests()out ofsetup()to RPC-only (same pattern this PR established forwave8ExpandBenchmark)Closing as the byte-LUT optimization #2526 asked for is implemented, integrated into the parlio engine, host-test-equivalent, and measured on real hardware.
zackees commentedon May 29, 2026
Follow-up benchmark: full PARLIO encode (16×256) post-byte-LUT, with the PSRAM hypothesis settled
Added
parlioEncodeBenchmark(RPC + boot-time bridge inAutoResearchParlioEncode.h, PR coming) that replicates the engine's per-byte-position hot path — 16-lane gather +wave8Transpose_16(byteLut)+memcpy128 B — and times it with the source scratch and the DMA output each in SRAM or PSRAM (4 placements).Measured on ESP32-P4 v1.3 — 12,000 byte-positions per placement
WS2812B 16-lane 256-LED transmission time: 256 × 24 × 1.25 µs = 7,680 µs / frame.
Answers to the goal's three questions
1. PSRAM-is-slow hypothesis → DENIED
All four placements land within ~0.7% of each other (
ratio_x100 = 99for every PSRAM variant vs SRAM/SRAM — PSRAM is even fractionally faster, which is noise). The P4's L2 cache fully hides PSRAM latency for the strided-16 gather + sequential 128 B writes the engine does. This matches the prior session's separate ×1.00 measurement (memory note: "PSRAM is NOT slow on the P4 for this pattern"). The PSRAM theory is decisively not the bottleneck; don't chase it further.2. ISR-chunked streaming feasibility → NOT YET fast enough
The CPU produces a frame ~26% slower than the DMA can consume it. ISR-chunked streaming would underrun without further optimization. We need encode to drop to ≤ 7,680 µs (just feasible, no safety margin) or, more realistically, ≤ 6,000 µs (~25% headroom).
3. What to do to make it faster
Ranked by expected gain:
Recommendation: #2527 (dual-core) is the clear cleanest path to ISR-chunked-streaming feasibility — alone it should push encode from 9.65 → ~5.4 ms, ~30% margin under TX. #2525 (fusion) stacks on top, and after that #2523 (WaveN) for total-frame-time wins.
Notes
populateDmaBufferalso handles padding, dispatch, etc. — slightly above this.esp_rom_printfbecauseSerial/FL_PRINTis on UART0 in this build; perf(autoresearch): use FL_PRINT instead of esp_rom_printf in on-device benchmarks #2540/bug(esp32p4): testSimd RPC write-timeout — Serial routes to UART0 instead of USB-Serial-JTAG #2541 will let this switch toFL_PRINTand to theparlioEncodeBenchmarkRPC directly.Refs #2527 #2525 #2523 #2541