Skip to content

Wave8 opt: optimize the Wave8 nibble-LUT expansion (~55%% of encode) #2526

Closed

Description

@zackees

Option from #2524.

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.

Parent: #2524 · Investigation/data: #2522

Activity

  1. zackees commented on May 29, 2026

    @zackees
    MemberAuthor

    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:

    1. hi = (byte>>4)&0xF; memcpy_32(&out.symbols[0], lut.lut[hi], 1) → 1×lw + 1×sw
    2. 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.
    • Scale: 16 lanes × 768 byte-positions (256 LEDs × 3 colors) = 12,288 expansions/frame.

    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, 2 sw):

    srli;andi;slli;add; lw; sw      # hi nibble: index + load4 + store4
    andi;slli;add;       lw; sw      # lo nibble: index + load4 + store4
    

    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 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):

    struct FL_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:

    FASTLED_FORCE_INLINE FL_IRAM
    void wave8_expand_byte(u8 b, const Wave8ByteExpansionLut& lut, Wave8Byte* out) {
        isr::memcpy_32(bit_cast_ptr<u32>(out), bit_cast_ptr<const u32>(&lut.lut[b]), 2);
    }

    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:

    u64 tmp[16];
    for (int i=0;i<16;i++) tmp[i] = bit_cast<u64>(lut.lut[lanes[i]]);   // independent loads
    for (int i=0;i<16;i++) bit_cast_store(&laneWaveformSymbols[i], tmp[i]); // 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.

    Dead ends (documented so they aren't re-explored)


    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

    1. S1 (byte-LUT) + S2 — the main win; small, low-risk, bit-exact, ~1.2–1.3× encode predicted.
    2. S3 (batched loads) if device numbers show load-use stalls.
    3. Hand the intermediate-buffer round-trip to Wave8 opt: combined expand+transpose LUT (skip intermediate Wave8Byte) #2525 (combined expand+transpose) for the structural ceiling; PARLIO clockless: encode/DMA is Wave8-bound — add intermediate WaveN (e.g. Wave4) to halve encode time + DMA RAM #2523 (WaveN, halves symbol count) and Wave8 opt: dual-core encode on ESP32-P4 #2527 (dual-core) remain the largest orthogonal levers.

    Refs: parent #2524 · data #2522 · transpose precedent #2534 · fusion #2525 · PIE-no-gather #2535/#2538

  2. zackees commented on May 29, 2026

    @zackees
    MemberAuthor

    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)

    variant total µs µs / byte-position (16 expansions) frame-equiv µs (768 byte-pos) vs nibble
    nibble (current) 350,170 11.7 8,964 1.00×
    byte-LUT (S1) 210,419 7.0 5,386 1.66×
    batched byte-LUT (S3) 198,682 6.6 5,086 1.76×

    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).
    • 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.
  3. zackees commented on May 29, 2026

    @zackees
    MemberAuthor

    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

    metric nibble (current) byte-LUT (#2526) speedup per-frame Δ
    expand-only (480k expansions) 350,142 µs 210,155 µs 1.66× —
    batched expand (S3) 350,142 µs 206,528 µs 1.69× —
    wave8Transpose_16 (production hot path) 530,115 µs 344,128 µs 1.54× —
    frame-equivalent (×768 byte-positions) 13,570 µs 8,809 µs 1.54× −4,761 µs

    What it means

    • 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.

    Refs PR #2539 · #2541 (RPC routing) · #2540 (FL_PRINT vs esp_rom_printf)

  4. added a commit that references this issue on May 29, 2026
  5. zackees commented on May 29, 2026

    @zackees
    MemberAuthor

    Done — landed via PR #2539 (merge commit 1150f2e307).

    Final measured result (ESP32-P4 v1.3):

    • Byte-LUT expansion: 1.66x vs nibble (isolated)
    • wave8Transpose_16 (production hot path: expansion + 16-lane transpose): 1.54x vs nibble
    • Frame-equivalent at 16x256 LEDs: 13.57 ms -> 8.81 ms (-4.76 ms/frame on the hot loop)

    Follow-ups split out and tracked separately:

    Closing as the byte-LUT optimization #2526 asked for is implemented, integrated into the parlio engine, host-test-equivalent, and measured on real hardware.

  6. zackees commented on May 29, 2026

    @zackees
    MemberAuthor

    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

    placement (scratch / output) total µs µs / byte-position frame-equiv µs (×768) vs SRAM/SRAM
    SRAM / SRAM 150,804 12.57 9,651 1.00×
    SRAM / PSRAM 149,812 12.48 9,587 0.99×
    PSRAM / SRAM 149,931 12.49 9,595 0.99×
    PSRAM / PSRAM 149,815 12.48 9,588 0.99×

    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 = 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).

    3. What to do to make it faster

    Ranked by expected gain:

    lever tracked in expected on full encode rationale
    Dual-core encode (lanes 0–7 / 8–15) #2527 ~1.8× → ~5.4 ms Two P4 cores, ~50% overhead amortized. Brings encode comfortably under 7.68 ms TX → ISR streaming feasible.
    Fused expand+transpose LUT #2525 ~1.1–1.2× → ~8.0–8.7 ms Eliminates the 128 B intermediate-buffer round-trip per byte-position. Helps but not alone enough.
    WaveN (Wave4) #2523 encode & TX both ½ 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.
    Spread-LUT transpose (already shipped) #2534 done 1.54× on the hot loop.
    Byte-LUT expansion (just shipped) #2526 / #2539 done 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

    Refs #2527 #2525 #2523 #2541

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions