Skip to content

perf(parlio/wave8): umbrella — single-core algorithmic optimizations to enable ISR-chunked streaming #2548

Closed

Description

@zackees

Goal

Close the ~2 ms/frame gap between PARLIO encode on ESP32-P4 (9.65 ms/frame) and the WS2812B 16-lane transmission budget (7.68 ms/frame) using single-core, single-Wave8 algorithmic changes only, enabling ISR-driven chunked streaming.

Out of scope (tracked separately, deliberately excluded from this umbrella):

Where we are

From #2547 parlioEncodeBenchmark, measured on real P4 v1.3:

perpos_us        ss=150804      → 12.57 µs / byte-position
frame_equiv_us   ss=9651        → 9.65 ms / 16-lane × 256-LED frame
WS2812B TX       16 × 1.25 µs × 256 × 24 = 7.68 ms / frame
gap              +1.97 ms (CPU ~26 % slower than DMA drain)

Stage cost breakdown:

  • Strided gather + 128-B memcpy ≈ 1.1 µs per byte-position
  • 16-lane expansion (byte-LUT) ≈ 7.0 µs
  • 8-symbol spread-transpose ≈ 4.5 µs
  • A big chunk of expansion is the 128-B intermediate-buffer round-trip (16 × 8 B store → 16 × 8 B read).

In-scope work items (checklist)

  • L1 — Fuse expand+transpose via loop interchange + cached byte_lut pointers (~10–15 %, ~1.0–1.4 ms/frame) — primary algorithmic change.
  • L2 — Direct write to outputBuffer (skip engine's 128-B memcpy) (~770 µs/frame) — basically free plumbing once alignment confirmed.
  • L3 — Loop tiling: 2–4 byte-positions per iter (~5–10 %) — strided gather → u32-wide; ILP on in-order core.
  • L5 — Alignment + wider load/store (~3–5 %) — FL_ALIGNAS(16) propagation; route the 128-B store through fl::simd::store_u32_4_aligned × 8 (PIE esp.vst.128.ip via the feat(esp32-p4): PIE (xesppie) SIMD backend Tier-1 ops (#2536) #2538 backend).
  • L6 — Pre-transpose scratch to byte-position-major layout (modest + bigger refactor) — sequential gather, multi-lane u32 loads. Needs upstream channel-manager coordination, so probably batch with another upstream change.
  • L7 — Pre-shifted spread LUT (shifted_a[8][16], 1 KB) (~5–10 %) — removes the 8 runtime shifts per spread half.

Recommended prototype order

  1. L2 (direct write, basically free plumbing).
  2. L1 (fuse expand+transpose).
  3. L3 (loop tiling on top of L1+L2).
  4. L5 alignment / PIE-store polish.
  5. L7 pre-shifted spread LUT.
  6. L6 scratch layout change — combine with other upstream work.

Combined best-case prediction

9.65 ms → ~6.5–7.0 ms/frame on the byte-LUT path. Puts ISR-chunked streaming at the edge, and stacks multiplicatively with #2527 (dual-core) for a comfortable safety margin.

Hot-loop anatomy (per byte_position, for reference)

The engine (parlio_engine.cpp.hpp:981-994) does this 768×/frame for mDataWidth == 16:

u8 lanes[16];
for (size_t lane = 0; lane < 16; lane++) {                            // (A) strided u8 gather
    lanes[lane] = mScratchBuffer[lane * mLaneStride + ... + byteOffset];
}
u8 transposed[16 * sizeof(Wave8Byte)];                                // 128 B stack
fl::wave8Transpose_16(lanes, mWave8ByteLut, transposed);              // (B) + (C) below
fl::memcpy(outputBuffer + outputIdx, transposed, blockSize);          // (D) 128 B copy

And inside wave8Transpose_16 (wave8.cpp.hpp):

Wave8Byte laneWaveformSymbols[16];                                    // 128 B intermediate
for (lane 0..15) wave8_expand_byte(lanes[lane], byteLut, &laneWaveformSymbols[lane]);
detail::wave8_transpose_16(laneWaveformSymbols, output);              // spread-LUT 8 symbols

Per-lever detail

L1 — Fuse expand+transpose via loop interchange + cached byte_lut pointers ★

Eliminate the 128-B intermediate buffer. Pre-cache the 16 byte_lut entry pointers, then iterate symbols × lanes with direct loads:

FASTLED_FORCE_INLINE FL_IRAM
void wave8Transpose_16_fused(const u8 (&lanes)[16],
                             const Wave8ByteExpansionLut &lut,
                             u8 (&output)[128]) {
    const Wave8Byte *e0  = &lut.lut[lanes[0]];   const Wave8Byte *e1  = &lut.lut[lanes[1]];
    const Wave8Byte *e2  = &lut.lut[lanes[2]];   const Wave8Byte *e3  = &lut.lut[lanes[3]];
    /* ... e4..e15 ... */

    for (int s = 0; s < 8; ++s) {
        const u8 l[16] = {
            e0->symbols[s].data,  e1->symbols[s].data,
            /* ... e2..e15 ... */
        };
        spread_transpose16_symbol(l, output + s * 16);
    }
}

Saves: 16 × 8 B intermediate stores + matching reads + the per-lane 2-store sequence inside wave8_expand_byte. L1 cache holds each LUT row trivially (8 B); compiler may hoist into 2 u32 registers per lane.

Predicted: ~10–15 % on the full hot loop.

L2 — Direct write to outputBuffer

Pass outputBuffer + outputIdx straight in as the output arg of wave8Transpose_16. Remove the stack transposed[128] and the fl::memcpy. Requires outputBuffer + outputIdx to be 16-byte aligned, which it already is when outputBuffer is DMA-aligned and outputIdx is a multiple of 128 each iteration.

Saves: ~1 µs / byte-position × 768 ≈ ~770 µs / frame.

L3 — Loop tiling

Byte-positions are independent. Tile by 2 or 4 so the in-order core overlaps memory ops and the compiler emits a wider window of independent ops — same shape that won for the spread-LUT itself (#2533).

for (offset = 0; offset + 4 <= byteCount; offset += 4) {
    u8 lanes0[16], lanes1[16], lanes2[16], lanes3[16];
    for (lane 0..15) {
        const u8 *p = &mScratchBuffer[lane * mLaneStride + startByte + offset];
        lanes0[lane] = p[0]; lanes1[lane] = p[1]; lanes2[lane] = p[2]; lanes3[lane] = p[3];
    }
    wave8Transpose_16_fused(lanes0, byteLut, out + 0);
    wave8Transpose_16_fused(lanes1, byteLut, out + 128);
    wave8Transpose_16_fused(lanes2, byteLut, out + 256);
    wave8Transpose_16_fused(lanes3, byteLut, out + 384);
    out += 512;
}

Saves: ~5–10 %, mostly via ILP on the strided gather (4 consecutive bytes per lane = 1 word load) and amortized branch / index arithmetic.

L5 — Alignment + wider load/store

  • Wave8Byte is FL_ALIGNAS(8) — bump Wave8ByteExpansionLut::lut[256] to FL_ALIGNAS(16) to let the compiler/PIE emit single 16-B loads per row.
  • Mark the engine's transposed[128] FL_ALIGNAS(16) (or remove it via L2).
  • Propagate __restrict__ through wave8Transpose_16 overloads.
  • On P4, route the 128-B store through fl::simd::store_u32_4_aligned × 8 — 8 × esp.vst.128.ip via the feat(esp32-p4): PIE (xesppie) SIMD backend Tier-1 ops (#2536) #2538 backend, instead of ~32 u32 stores.

Saves: ~3–5 %, stacks cleanly with L1/L2.

L6 — Pre-transpose scratch to byte-position-major layout

Today: scratch[lane * 768 + byteOffset] (strided gather). Restructure to scratch[byteOffset * 16 + lane] (sequential gather — 16 contiguous bytes per byte-position) — one wide u32 load yields 4 lanes' bytes.

Saves: strided gather is ~0.4 µs / byte-position (small); larger win is enabling u32-wide gathers and removing the 16-store-to-lanes[16] step.

Cost: layout change at the channel-manager / engine boundary — bigger refactor than the others. Probably worth combining with another upstream change rather than doing alone.

L7 — Pre-shifted spread LUT

Inside spread_transpose16_symbol, each spreadA(l[i]) << i is a runtime shift + OR. Pre-shift the spread LUT for each of the 8 lane bit-positions:

struct Wave8SpreadShiftedLut { u32 a[8][16];  u32 b[8][16]; };  // 1 KB total
// spreadA(v) << lane  →  shifted_a[lane][v >> 4]
// spreadB(v) << lane  →  shifted_b[lane][v & 0xF]

Per symbol, the OR-reduce becomes 8 loads + 7 ORs (no shifts) per half × 2 halves = 30 ops vs current ~46 ops.

Saves: ~5–10 % on the spread-transpose stage (~0.2–0.4 ms/frame).


Deferred / future

L4 — Combined byte+lane LUT (Wave8LaneShiftedLut[16][256][16] = 64 KB)

Pre-compute, for each (lane_position, byte), the byte's complete contribution to the 16-byte output for all 8 symbols — already shifted to its lane bit position:

struct FL_ALIGNAS(16) Wave8LaneShiftedLut { u8 lut[16][256][16]; }; // 64 KB total
u8 acc[16] = {0};
for (lane 0..15) {
    const u8 *contrib = lut.lut[lane][lanes[lane]];
    for (i 0..15) acc[i] |= contrib[i];
}
memcpy(out, acc, 16);

Theoretical impact: algorithmic ceiling, ~2× on the hot loop (~5 ms / frame) — would put encode comfortably under TX.

Why deferred: 64 KB SRAM commitment is a significant slice of internal RAM that affects every PARLIO consumer (and crowds other features). Not worth the memory tradeoff while the other levers above are unmeasured. Revisit only if L1–L7 (combined) fail to close the gap, or if a future variant could share the table across multiple buffers.

Measurement plan

Extend parlioEncodeBenchmark (#2547) to compare current vs each prototype back-to-back. Same volatile-sink, same input, same iteration count. Capture via the existing esp_rom_printf → COM25 path until #2541 fixes the RPC routing. Gate prototypes behind compile flags so they're A/B-able from one firmware.

Related

Activity

  1. changed the title [-]perf(parlio/wave8): single-core algorithmic levers to close the ISR-streaming gap (~2 ms/frame)[/-] [+]perf(parlio/wave8): umbrella — single-core algorithmic optimizations to enable ISR-chunked streaming[/+] on May 29, 2026
  2. zackees commented on May 29, 2026

    @zackees
    MemberAuthor

    Re-evaluation: L1 + L2 + L3 measured on ESP32-P4 — predictions were too optimistic; gap NOT closed

    Implemented L1 (fused expand+transpose), L2 (direct write to output), and L3 (4-byte-position tiling) as bench variants (branch perf/parlio-l1l2l3; extends PR #2547 with measurement-only kernels). Captured on real ESP32-P4 v1.3, 12,000 byte-positions per measurement, SRAM scratch + SRAM output (PSRAM already proven ×1.00 in PR #2547):

    variant total µs frame µs (×768) vs baseline predicted delta
    baseline (current production) 150,790 9,650 1.00× — —
    L2 (direct write) 145,441 9,308 1.03× ~1.08× underperformed
    L1+L2 (fused + direct write) 152,148 9,737 0.99× ⚠ slower ~1.13× regressed
    L1+L2+L3 (fused + direct + 4-tile) 147,556 9,443 1.02× ~1.20× underperformed
    WS2812B TX target — 7,680 — — —

    Conclusion: L1 + L2 + L3 cannot close the ~2 ms/frame ISR-streaming gap. Best measured combo (L2 alone) is 9,308 µs/frame vs target 7,680 µs — still +1,628 µs / 21 % over budget.

    Why each lever underperformed

    L1 — Fused expand+transpose actually regressed (-1 % vs baseline)

    The hypothesis was that eliminating the 128-B laneWaveformSymbols intermediate buffer would save real time. It did not. Caching the 16 Wave8Byte* row pointers across the symbol loop pushes 16 × 4 B = 64 B of pointer state through the register file. On RV32 (32 GPRs) — together with byte_lut.lut base, the output pointer, loop counters, and the per-symbol l[16] working set — that exceeds the register budget and forces the compiler to spill the pointers to stack repeatedly.

    Meanwhile the baseline's laneWaveformSymbols[16] is naturally L1-cached sequential stack memory: writes are cheap (~1 cycle per store, no latency dependency), and the subsequent symbol-by-symbol reads are L1 hits. The intermediate buffer is the compiler's natural register-file extension for this access pattern — eliminating it is a pessimization.

    L2 — Direct write helped, but only +3.5 % (predicted ~+8 %)

    The engine's fl::memcpy(outputBuffer + outputIdx, transposed, 128) is already very cheap: 32 u32 stores from a stack array to a DMA-aligned buffer, fully pipelined on the in-order core. The estimated 1.1 µs / byte-position for "gather + memcpy" turns out to be mostly gather; the memcpy itself is closer to 0.3 µs. So L2 saves ~342 µs / frame — real, but not the lever I'd hoped for.

    L3 — Tiling helped a tiny amount in isolation, undone by L1's regression

    On top of L1's regression, L3's ~+3 % tiling win brought us from 99 → 102 vs baseline. Not nothing, but not a route to 26 % improvement either.

    What this means for the umbrella

    Of the in-scope (no-L4, no-#2527, no-#2523) levers, the predicted gains were too optimistic across the board. The remaining items on the checklist look weaker than I projected:

    • L1 — fuse expand+transpose → ⚠ regressed (-1 %), abandon (register pressure on RV32)
    • L2 — direct write → +3.5 % (kept for any follow-up; small but real)
    • L3 — tiling → ~+2 % on top of baseline, undone by L1; minor
    • L5 — alignment + PIE 128-B store → predicted ~3–5 %, likely now ~1–2 % once anchored to measured cost breakdown (memcpy was much cheaper than estimated)
    • L6 — scratch-layout change → still believable for ILP on gather, but the dominant cost (spread-transpose) isn't touched; probably ~3–5 % at best, requires upstream coordination
    • L7 — pre-shifted spread LUT (1 KB) → still the most promising untried lever; attacks the dominant cost (spread-transpose). Rough re-estimate: ~5–8 % from removing 256 runtime shifts per byte-position, getting us to ~8.7 ms/frame at best.

    Realistic projection

    Stacking L2 + L5 + L7 ≈ 9.65 → ~8.5 ms / frame. Still ~1 ms above the 7.68 ms target. The remaining single-core single-Wave8 algorithmic options that respect the no-L4 constraint cannot close the gap.

    Recommendation

    1. Drop L1 from this umbrella — the RV32 register-budget reality makes loop interchange a net loss for this hot loop.
    2. Keep L2 as a small standalone win (~3.5 %) — straightforward, near-zero churn, can land independently.
    3. Try L7 next (1 KB pre-shifted spread LUT) — it's the only remaining lever that attacks the dominant spread-transpose cost. Worth measuring before declaring the umbrella infeasible.
    4. If L2 + L7 still leaves > 0.5 ms gap to target, accept that closing it requires either:
    5. Update the umbrella to reflect actual measured impact rather than the original predictions.

    Bench branch (RPC + boot bridge) for reproducing: perf/parlio-l1l2l3 layered on PR #2547.

    Refs PR #2547 (the bench) · branch perf/parlio-l1l2l3 (these variants) · #2527 (dual-core, multiplicative) · #2523 (WaveN, orthogonal) · #2541 (RPC routing).

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

    @zackees
    MemberAuthor

    Re-evaluation #2: lazy / PSRAM-allocated L4 — decisively does not work (7.7× slower)

    Per follow-up from @zackees: tried L4 with the original 64 KB SRAM commitment swapped for lazy allocation from PSRAM (fl::span<fl::u8, FL_L4_LUT_BYTES> fixed-extent, heap_caps_malloc(MALLOC_CAP_SPIRAM)). The intent was to keep zero static SRAM footprint and let the L2 cache hide PSRAM latency the same way it does for every other PARLIO access pattern (#2547).

    What got built

    • Layout: lut[8 symbols][16 lanes][256 bytes][16 output bytes] = 524,288 bytes (512 KB). This is the natural L4 size — anything smaller drops the symbol dimension and collapses to L7.
    • Build: correct by construction — call the existing spread_transpose16_symbol on dummy lanes (one lane non-zero at a time) and store the contribution slot. Built once at engine init, lives entirely in PSRAM.
    • Kernel: 8 symbols × 16 lanes × 4-u32 OR-reduce per byte-position. Algorithmic op count ~600 → ~288 — what you'd want, in theory.

    Branch: perf/parlio-l1l2l3 (now layered with L4 on top of L1/L2/L3).

    Measured on ESP32-P4 v1.3

    baseline_us   = 150,858    frame = 9,654 µs        (1.00×)
    L4 PSRAM_us   = 1,081,675  frame = 69,227 µs       (0.13× — 7.7× SLOWER)
    ws2812b_tx_us = 7,680
    

    Why it fails — and why the failure is structural, not implementation

    The P4's L2 cache is 128 KB. The L4 LUT is 512 KB. Per byte-position the kernel touches 128 distinct (lane, byte) entries, each in a different 16-byte slot scattered across the 512 KB working set — they evict each other from L2 every iteration. Every miss then goes to PSRAM at ~100–200 cycle latency, which dominates any algorithmic saving and yields the 7.7× regression.

    This is the exact opposite of what we observed for every other PARLIO access pattern in #2547 (×1.00 SRAM vs PSRAM for scratch and output). The difference is working-set size:

    access pattern working set / frame L2 fits? PSRAM vs SRAM
    scratch (12 KB) ~12 KB ✅ ×1.00
    output (96 KB) ~96 KB ✅ ×1.00
    L4 LUT (512 KB) ~512 KB ❌ ×0.13

    The same will be true of any LUT large enough to cover all 8 symbols in this combined-lane-byte-symbol structure — the natural lower bound is the 512 KB layout above, well over L2. Shrinking the LUT requires dropping either the per-symbol or the per-byte dimension, at which point the structure collapses back to L7 (the 1 KB pre-shifted spread LUT, which fits in cache trivially).

    What this means for the umbrella

    • L4 is now empirically infeasible on P4, even with lazy PSRAM allocation. Mark it permanently deferred — not because of SRAM cost (we solved that with PSRAM) but because of L2 cache pressure. Reopen only if a future P4 stepping ships a larger L2 or if a sparse-format L4 below 128 KB can be designed.
    • Lazy / PSRAM allocation as a technique still works perfectly for smaller LUTs — e.g. L7's 1 KB pre-shifted spread LUT can absolutely be built lazily without any SRAM hit. That pattern is salvageable.
    • None of the in-scope levers (L1, L2, L3, L4-now-disqualified) close the ~2 ms ISR-streaming gap on P4 single-core single-Wave8. The path to ISR streaming on P4 goes through Wave8 opt: dual-core encode on ESP32-P4 #2527 (dual-core) for the gap and PARLIO clockless: encode/DMA is Wave8-bound — add intermediate WaveN (e.g. Wave4) to halve encode time + DMA RAM #2523 (WaveN) for the orthogonal halving — both deliberately out of scope of this umbrella.

    Honest summary on the umbrella checklist

    lever status measured impact
    L1 — fused expand+transpose ❌ abandon -1 % (RV32 register pressure regression)
    L2 — direct write ✅ keep +3.5 % (small but free)
    L3 — loop tiling ⚠ tiny win on top of L2 +2 % vs baseline
    L4 — combined byte+lane LUT ❌ infeasible (even lazy) -670 % (L2 cache thrashing)
    L5 — alignment + PIE store untried predicted ~1–2 % (downward revised)
    L6 — scratch layout change untried (upstream) predicted ~3–5 % (downward revised)
    L7 — pre-shifted spread LUT (1 KB) untried, last remaining predicted ~5–8 %

    If L7 + L2 land best-case (~10 % combined), encode floor is ~8.7 ms/frame — still ~1 ms above the 7.68 ms TX target.

    Recommendation: keep #2548 open only for L2 + L7 + L5 (small wins worth landing), and acknowledge that closing the gap to enable ISR-chunked streaming requires #2527 (dual-core) — multiplicative on top of anything in this umbrella.

    Refs: bench branch perf/parlio-l1l2l3 · L1/L2/L3 result #2548-comment-4580594293 · PSRAM equivalence #2547 · #2527 #2523

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

    @zackees
    MemberAuthor

    Re-evaluation #3: nibble-indexed L4 (32 KB, fits in L2) — also doesn't win (1.69× slower)

    Per follow-up: tried a nibble-indexed L4 that exploits the wave8 expansion's existing nibble structure (hi nibble → symbols 0..3, lo nibble → symbols 4..7) — small enough (32 KB) to fit comfortably in P4's 128 KB L2 cache.

    Layout

    lut_hi[16 lanes][16 nibbles][64 bytes]   // 16 KB — contributes to symbols 0..3 of output
    lut_lo[16 lanes][16 nibbles][64 bytes]   // 16 KB — contributes to symbols 4..7 of output
    Total: 32 KB.
    

    Built via spread_transpose16_symbol on dummy lanes (correct by construction). Kernel does 2 nibble lookups per lane × 16 lanes, OR-reduced into the 128-byte output.

    Measured on ESP32-P4 v1.3

    baseline             frame=9,654 µs   (1.00×)
    L4 byte (512 KB)     frame=69,275 µs  (0.13× — 7.7× SLOWER, L2 thrash)
    L4 nibble (32 KB)    frame=16,323 µs  (0.59× — 1.69× SLOWER, fits L2)
    WS2812B TX           7,680 µs
    

    Why even the cache-resident version loses

    Nibble L4 is dramatically better than byte L4 (no more PSRAM cache misses — every load hits L2) but still loses to the current spread_lut. The op-count math doesn't favor it on RV32:

    path per byte-position nature of ops
    current spread_lut ~864 ops 32 small-LUT loads (64 B L1-resident kSpreadNibble) + 32 cheap shifts + 28 ORs + 16 stores
    L4 nibble ~1,024 ops ~512 L2-hit loads + ~512 ORs + 32 stores

    Each L2 load has 2–3 cycle latency before the OR depending on it can issue — and the in-order RV32 core can't hide that with other independent work in this kernel. Trading the current path's cheap 1-cycle shifts for L2 loads is a net loss.

    Generalizable lesson

    On the in-order RV32 P4 with cheap shifts (1 cycle, no latency), substituting LUT loads for arithmetic doesn't pay unless the saved work substantially exceeds the load-use latency cost. The current spread_lut is already near-optimal for this combination of architecture and problem. L4 at any viable size (whether L2-thrashing 512 KB or cache-resident 32 KB) does not beat it:

    L4 variant size placement L2 fits? speedup
    L4 byte 512 KB PSRAM ❌ thrashes 0.13×
    L4 nibble 32 KB anywhere ✅ fits 0.59×
    (L4 + L4n combined) — — — none possible — same root cause

    Status on the umbrella

    L4 is now empirically infeasible on P4 at every viable LUT size we've tried. Permanently deferred — not for memory cost (lazy PSRAM solves that for any LUT ≤ 128 KB) but for load-use latency on the in-order core. The path forward is the same as the prior re-evaluation:

    Bench branch (with L1/L2/L3/L4/L4-nibble all reproducible): perf/parlio-l1l2l3.

  7. zackees commented on May 30, 2026

    @zackees
    MemberAuthor

    New strategy: a measurement-first deep-dive with two untried lever classes

    After the L1/L2/L3 measurements (+3.5 % / -1 % / +2 %) and the L4-byte (0.13×) / L4-nibble (0.59×) failures, I've drafted a new multi-phase plan that's built around measuring ground truth first and then targeting the two lever classes we have not yet exercised. Capturing it here so the strategy is public before any of the prototype branches land.

    Updated hypothesis

    The L4 failures (byte + nibble) established a sharp generalizable result:

    On the in-order RV32 P4 with cheap 1-cycle shifts, substituting L2 (or even L1) loads for arithmetic loses unless the saved work substantially exceeds the 2–3 cycle load-use stall. The current spread_lut is already near-optimal as a structure.

    That rules out any LUT that grows the working set or merely substitutes loads for arithmetic. What it does NOT rule out:

    1. Pre-shifting the existing small LUT so the same number of loads hit the same L1-resident table, but the runtime shift on the critical path goes away (L7). The OR-tree stays intact; only the shifts move off the dependency chain. This is a qualitatively different trade than L4 because we're not adding loads — we're moving 256 shift ops off the critical path while keeping the load count identical.
    2. Fixing L1's register-pressure regression by caching expanded bytes as u32 pairs (16 GPRs of data) instead of Wave8Byte pointers (16 GPRs of address state that spilled). This trades the 128-B laneWaveformSymbols intermediate for register-resident data of the same size, which the L1-fused-pointer-array version got wrong.
    3. Vectorized 128-B store via PIE — esp.vst.128.ip is wired up in feat(esp32-p4): PIE (xesppie) SIMD backend Tier-1 ops (#2536) #2538's backend and reduces the engine's 32 × u32 store to 8 × 128-bit stores. The L5 lever was never actually built; L2 alone won only +3.5 % because the source side wasn't aligned/vectorized.

    Phased execution plan

    Phase What Expected impact Status
    0 Per-stage cycle-counter instrumentation — measure gather / expand / transpose / store separately via __clock_cycles() (truth-finding) next
    1 ASM inspection of production wave8Transpose_16 — confirm -O3 actually applies, find spills, find lw → arith-on-load-dest stalls (codegen verify) next
    2 L7: pre-shifted spread LUT (512 B, L1-resident) — kSpreadPreShifted[8 lane_pos][16 nibble]. Replaces 256 runtime shifts per byte-position 5–8 % next
    3 Register-cached fused v2 — cache 16 × u32 pairs of expansion bytes (not pointers), read symbol bytes via shift+mask. Stacks with L7. Fixes L1's RV32 register-pressure failure mode 3–5 % next
    4 L5: alignment + vectorized PIE store — FL_ALIGNAS(16) everywhere + 8 × esp.vst.128.ip instead of 32 × u32 stores. Precondition for L2 to actually win 2–4 % next
    5 4 KB combined LUT — conditional, only if Phase 2+3 underdeliver 2–4 % conditional
    6 __builtin_prefetch on strided gather — conditional, only if Phase 0 shows gather > 10 % 0.5–1.5 % conditional
    7 Stop condition — if Phases 2+3+4 leave > 0.7 ms gap, declare single-core unclosable (decision) gate

    Phase 0 decision tree (drives prioritization)

    Once instrumentation lands:

    • transpose > 60 % → Phase 2 (L7) is top priority (pre-shifted spread directly attacks symbol-body shifts).
    • expand > 30 % → Phase 3 (fused v2) is top priority (expand is memory-bound; register-cached version is the real fix).
    • store > 25 % → Phase 4 leapfrogs (vectorized PIE store is the lever).
    • gather > 15 % → Phase 6 (prefetch) before Phase 5.

    Stop condition (when to declare single-core unclosable)

    After Phases 0–4, declare unclosable if all of these hold:

    1. Phase 0 shows transpose + expand > 75 % (memory-bound),
    2. Phase 2 (L7) speedup ≤ 3 % (the symbol body was already near-optimal),
    3. Phase 3 (fused v2) speedup ≤ 2 % (expand stage memory-bound, not issue-bound),
    4. Total frame time after Phases 2+3+4 ≥ 8.4 ms (> 0.7 ms gap remaining).

    Then the verdict is: single-core single-Wave8 ceiling reached; closing the gap to enable ISR-chunked streaming requires #2527 (dual-core, multiplicative) or #2523 (WaveN, halves both encode + TX).

    Branch / PR strategy

    • All Phase 0/1 instrumentation + variant scaffolding stacks on top of perf/parlio-l1l2l3 (the existing bench harness).
    • Each phase that produces a measured win becomes its own clean PR off master:
      • Phase 2: perf/wave8-l7-preshifted-spread
      • Phase 2 + 3: perf/wave8-fused-v2
      • Phase 4: perf/parlio-l5-aligned-pie-store
    • Production wiring (engine call-site swap) only after bit-exact equivalence tests in tests/fl/channels/wave8.cpp over 100k random vectors pass for each variant.

    Why I think this clears the bar L4 didn't

    L4 failed because both variants traded cheap arithmetic for memory traffic — at LUT sizes that either thrashed L2 (512 KB) or paid load-use latency in the symbol loop (32 KB). L7 doesn't grow memory traffic at all — it keeps the same 32 loads per spread_transpose16_symbol call but the loaded values are pre-shifted. Fused v2 also keeps the same load count but moves the intermediate from a 128-B stack buffer into 16 register-resident u32 pairs, avoiding both the L1 pointer-spill regression AND the byte-LUT path's stack ping-pong. Neither lever fights the in-order RV32's strengths.

    If both hypotheses are wrong and L7 + fused v2 also disappoint, the stop condition kicks in cleanly — we'd have evidence that the spread_lut path is at a fundamental issue-port ceiling on this core.

    Plan file is locked in locally; will edit this issue once Phase 0 numbers are in.

  8. added a commit that references this issue on May 30, 2026
  9. zackees commented on May 30, 2026

    @zackees
    MemberAuthor

    Phase 0 result: per-stage cycle-counter breakdown captured ✅

    Wired up cycle-counter (__clock_cycles()) timing of the production hot loop in AutoResearchParlioEncode.h, with asm volatile memory barriers between stages. Captured on real ESP32-P4 v1.3 (8000 iters):

    stage cyc/iter ns/iter % of total
    gather 231 641 3.4 %
    expand (16× byte_lut → Wave8Byte) 2,544 7,066 37.0 %
    transpose (8× spread_transpose16_symbol) 3,919 10,886 57.1 %
    store (128-B memcpy to DMA buffer) 171 475 2.5 %
    total 6,865 19,068 100 %

    The instrumented total (~19 µs/iter) is higher than the production baseline (12.6 µs/iter) because the 4 cycle-counter reads + asm volatile barriers add ~6 µs of measurement overhead. Relative proportions across stages stay accurate (barriers cost roughly the same per stage).

    Decision tree result vs the plan thresholds

    • transpose > 60 % → Phase 2 (L7 pre-shifted spread LUT) — AT THE THRESHOLD (57 %), promote to top priority
    • expand > 30 % → Phase 3 (register-cached fused v2) — HIT (37 %), high priority
    • store > 25 % → Phase 4 (PIE vectorized store) — MISS (2.5 %), defer
    • gather > 15 % → Phase 6 (__builtin_prefetch) — MISS (3.4 %), skip

    Expand + transpose together account for 94 % of the hot loop. That's the clear signal: stack L7 (Phase 2) + register-cached fused v2 (Phase 3) and we hit nearly all the available surface. L5 (Phase 4) would only chip at the 2.5 % store stage — defer unless the gap persists. Prefetch (Phase 6) at 3.4 % gather is in the noise — skip.

    Implications for the umbrella's optimistic estimates

    • Phase 4 was rated 2–4 % in the plan; Phase 0 caps it at ~2 % (store is 2.5 % of total). Demoted to "skip first round".
    • Phases 2 + 3 are the only levers with real surface area. If they don't close the gap, single-core single-Wave8 is done.

    Next action

    Implementing Phase 2: L7 pre-shifted spread LUT (512 B) now. Branch perf/parlio-l1l2l3 continues to accumulate bench variants; a clean PR off master comes once a winning combination is validated.

    Bench snapshot in commit 0f8f1f43bd on branch perf/parlio-l1l2l3 — reproducible via bash autoresearch esp32p4 --simd --no-fbuild with -DFL_BENCH_PARLIO_AT_BOOT=1 (currently set true in AutoResearch.ino).

  10. added 2 commits that reference this issue on May 30, 2026
  11. zackees commented on May 30, 2026

    @zackees
    MemberAuthor

    Final verdict: Phase 2 + Phase 3 both failed → stop condition met → single-core single-Wave8 ceiling reached

    Phase 0 instrumentation pointed at transpose (57 %) and expand (37 %) as the two real targets. Phase 2 (L7 pre-shifted spread LUT) and Phase 3 (register-cached fused v2) attacked them directly. Both regressed.

    Complete measured table on ESP32-P4 v1.3

    variant µs / frame vs baseline LUT size notes
    baseline (current production) 9,652 1.00× — spread_lut (64 B kSpreadNibble) + byte_lut (2 KB)
    L2 (skip 128-B memcpy, direct write) 9,308 1.03× — only confirmed win
    L1 (fused, pointer-cache) 9,737 0.99× — -1 % (RV32 pointer-array spill)
    L1+L2+L3 (4-byte-position tiling) 9,444 1.02× — minor ILP
    L7 (pre-shifted spread LUT) 14,071 0.69× 512 B shifts already pipeline with loads on RV32
    fused_v2 (16 × u32 PAIRS, two-pass) 11,570 0.83× — compiler can't keep 16+ u32 in regs — spills
    L4 byte (combined, PSRAM lazy) 69,278 0.13× 512 KB L2 cache thrash
    L4 nibble (combined, fits L2) 16,306 0.59× 32 KB load-use stalls > saved shifts
    WS2812B 16-lane 256-LED TX 7,680 — — the target

    Why L7 and fused v2 both lost — generalized lesson

    This is now the fourth confirmation of the same architectural truth:

    On in-order RV32 P4 with cheap 1-cycle shifts and L1-resident kSpreadNibble, the production spread_lut + byte-LUT path is at or near the issue-port ceiling for this workload. Any "smaller LUT, less arithmetic" trade (L4 byte → 7.7× slower; L4 nibble → 1.69× slower; L7 → 1.45× slower) loses because the shifts already pipeline with the OR-reduce. Any "register-cache 16+ u32 values" trade (L1, fused_v2 → 1.0–1.2× slower) loses because RV32's 32-GPR budget can't actually keep that much state live across a non-trivial inner loop — the compiler spills, recreating the memory traffic the cache was meant to eliminate.

    Stop condition (from the plan) — all 4 conditions met

    1. ✅ Phase 0 showed transpose + expand = 94 % of total (> 75 %)
    2. ✅ Phase 2 (L7) speedup = -45 % (worse than the ≤ 3 % threshold for "no win")
    3. ✅ Phase 3 (fused v2) speedup = -20 % (worse than the ≤ 2 % threshold)
    4. ✅ Floor after the only winning lever (L2 alone): ~9,310 µs/frame ≥ 8,400 µs (gap of 1.63 ms > the 0.7 ms threshold)

    Final umbrella state

    lever status impact
    L1 — fused (pointer-cache) ❌ abandon -1 %
    L2 — direct write to outputBuffer ✅ only confirmed win +3.5 %
    L3 — 4-byte-position tiling ⚠ tiny, undone by L1 +2 %
    L4 byte (512 KB PSRAM) ❌ infeasible (L2 thrash) -670 %
    L4 nibble (32 KB L1-resident) ❌ infeasible (load-use stalls) -41 %
    L5 — alignment + PIE 128-B store ⚠ store is only 2.5 % of total; capped at ~2 % (deferred)
    L6 — scratch layout change (untried; predicted small; defer) —
    L7 — pre-shifted spread LUT (512 B) ❌ regressed -31 %
    fused_v2 — register-cached pairs ❌ regressed -17 %

    Realistic single-core floor with L2 (and possibly L5 at ~2 %) = 9,200 µs/frame. Still ~1.5 ms over the 7,680 µs WS2812B 16-lane TX target → ISR-chunked streaming requires the CPU to keep ahead of DMA drain, which is unachievable without:

    What's worth landing from this umbrella

    L2 alone as a small, low-risk PR off master:

    • Modify parlio_engine.cpp.hpp:989 to pass outputBuffer + outputIdx directly into wave8Transpose_16 and remove the stack transposed[128] + fl::memcpy.
    • Bit-exactness already validated empirically by the bench (sink XOR matches baseline).
    • Saves ~340 µs/frame (~3.5 %) — small but free.

    Close the umbrella with this verdict and reorient toward #2527.

    Bench branch: perf/parlio-l1l2l3 (commit b17bfb1e60) — all 9 variants reproducible via bash autoresearch esp32p4 --simd --no-fbuild with FL_BENCH_PARLIO_AT_BOOT=1.

  12. added 3 commits that reference this issue on May 30, 2026
  13. 30 remaining items

  14. added 5 commits that reference this issue on May 30, 2026
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