Repository navigation
Segmented unique optimization - #417
Conversation
Greptile SummaryThis PR replaces the open-addressing shared hash table in
Confidence Score: 5/5The three-phase kernel sequence is safe: stream ordering ensures correct inter-kernel data visibility, and TORCH_CHECKs guard the int32 index range. The chaining hash algorithm is correctly structured: prepare zeroes all link structures, core performs lock-free tail-append dedup with per-wave warp-aggregated counter privatisation, and finalize reads rep_local only after core has fully completed. TORCH_CHECKs bound both num_keys and num_tables to int32 range. No correctness issues were found that would produce wrong output for valid inputs. corelib/dynamicemb/src/unique_op.cu — the stale output_indices comment and unchecked cudaFuncSetAttribute returns are worth a quick cleanup pass. Important Files Changed
Flowchart%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[segmented_unique_cuda host] --> B[segmented_unique_prepare]
B --> |"init head/next=-1, table_counters=0"| C[segmented_unique_core]
C --> |"lock-free chain dedup, write rep_local"| D[segmented_unique_finalize]
D --> |"prefix-sum, compact keys, write output_indices"| E[return tuple]
C1[per-table bucket spaces] --> C
C2[shared s_segrange cache] --> C
D1[block 0 publishes unique_table_offsets] --> D
Reviews (6): Last reviewed commit: "[bench] Refresh benchmark plots on curre..." | Re-trigger Greptile |
03f0a88 to
9cca8d7
Compare
|
/build |
|
❌ Pipeline #54778391 -- failed
Result: 6/13 jobs passed |
Benchmark / profiling improvements: - Unify warmup: run the reporting loop before timing/profiling for every mode except correctness (torch mode previously had no warmup). Collapses three duplicated warmup blocks (nsys / ncu / default) into one site. - Deterministic backward grads: replace uninitialized torch.empty_like with torch.ones_like everywhere a grad is fabricated, so NaN/denormals are not written into the table (warmup) or added as FP-counter/timing noise (profile paths). - Rename profile mode ncu-run -> ncu (CLI choice, dispatch, result key, generated commands, docs). - benchmark_with_ncu now profiles every sparse_features iteration (was only the first), matching the nsys path; keeps an outer ncu_iter NVTX range. - ncu commands: add --nvtx --nvtx-include 'ncu_iter/' (NVTX-range gate complementing cudaProfilerStart/Stop) and --import-source=yes. - Add --num-iterations CLI option to override BenchmarkConfig.num_iterations on every config (useful to keep --profile ncu tractable). - Build: add -lineinfo to nvcc flags in setup.py and CMakeLists.txt so ncu's Source page / --import-source works (does not disable optimizations). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
- Add --num-iterations: override BenchmarkConfig.num_iterations on every
config (shrinks total iters + warmup), useful to keep ncu tractable.
- Add --ncu-iterations: select which iterations ncu captures (comma list or
begin:end:step slice), default iteration 0 only. Implemented in the
generated ncu command as one --nvtx-include 'ncu_iter/iter_{i}/' per
selected iter under a single cudaProfilerStart/Stop window; unselected iters
still run (keep cache warm) but are filtered out by NVTX. benchmark_with_ncu
tags each iter with an iter_{i} NVTX range.
- Add --ncu-kernel-regex (required for ncu-gen): user supplies the kernel-name
regex verbatim instead of deriving it from KERNEL_NAME_PATTERNS (which stays
for the bandwidth report). Matched as a substring of the real kernel symbol.
- README: new "Nsight Compute (ncu) profiling" section (two-step ncu-gen ->
ncu workflow, flag table, concrete TestGpu example with -k "TestGpu and
adam" and segmented_unique|table_insert regex).
- black-format the benchmark module.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
print_ncu_command emitted `-k '<cfg.label()>'`, but cfg.label() embeds '=' (pool=none, cap=1M). pytest -k is an expression grammar that rejects '=', so the generated command failed at runtime with "Wrong expression passed to '-k': ... unexpected character '='" (only surfaces when the workload actually runs, not in ncu-gen which returns early). Split the label on '=' and AND-join the chunks into a valid, still-unique -k expression. The '=' is fine in the -o report filename, so that is unchanged. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
print_ncu_command no longer requires --ncu-kernel-regex. When given it emits --kernel-name 'regex:<value>' as before; when omitted it emits no --kernel-name filter, so every kernel within the --nvtx-include scope is profiled. This is needed to capture all kernels of an op range (e.g. op:segmented_unique), which launches several differently-named kernels a single name regex can't all match. README: document capturing a whole op range -- the op:<name> NVTX ranges, the nested ncu_iter/iter_0/forward/dynamicemb_prefetch/op:segmented_unique/ path, and the concrete command (omitting --ncu-kernel-regex). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…e_id) Keys are pre-segmented by table, so the shared open-addressing table keyed by (key, table_id) was doing redundant table_id work: hashing table_id into the slot, packing it into hash_vals, and re-checking it on every key match (with a "different table_id -> keep probing" path). Treat the single 2*num_keys buffer as num_tables concatenated sub-tables: table t owns [off_t, off_t+cap_t) with off_t = 2*segmented_range[t] and cap_t = 2*(segmented_range[t+1]-segmented_range[t]). A key hashes/probes only within its table's sub-table, so: - the hash is over the key alone (drop tid hash + hash_combine); - hash_vals stores just local_idx (no pack/unpack, no table_id re-check); - a key match in a sub-table is, by construction, the same (key, table_id). Per sub-table load factor stays <= 0.5 (unique_t <= cnt_t, cap_t = 2*cnt_t), so it never fills -- same guarantee as before. Total buffer size is unchanged. Verified on EOS H100: test_unique_op.py 19/19 passed (incl. overlapping_keys cross-table, empty_tables cap_t=0 edge, random). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Now that hash_vals stores only the per-table local unique index (no packed table_id), it fits in int32 (local_idx < num_keys < 2^31). Halves the hash_vals buffer + its init/probe traffic; empty_val sentinel -> int32 max. Measured on EOS H100 (TestGpu/sgd, iter_0): segmented_init_kernel dropped -19% (10944 -> 8864 ns) as expected for the halved init write. But the dominant segmented_unique_kernel (~82% of the op) is latency/contention-bound (hot-key atomics + spin-wait), not bandwidth-bound, so it did not improve; net op duration was ~+4% vs baseline. Kept here for history; reverted in the following commits because the per-table/int32 line of attack does not move the dominant kernel -- the real lever is hot-key atomic/spin contention. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
This reverts commit beff503.
…key,table_id)" This reverts commit 80d3552.
…ncy) The launch sat at ~12% achieved occupancy / 0.12 waves (grid = SM*4, block=64 -> ~8 of 64 warps/SM), leaving the scheduler nothing to hide the dominant long_scoreboard (scattered global probe) latency behind. Raise BLOCK_SIZE 64->256 and size the grid to min(ceil(num_keys/BLOCK), SM*8) so the kernels fill the SMs (8 blocks/SM = 64 warps = full occupancy on sm_90; regs=32 fit). NOTE: this lifts achieved occupancy 12% -> 96% but segmented_unique_kernel duration is unchanged (~304 -> 310us): the kernel is memory-throughput-bound on scattered probe sectors, not occupancy/latency-bound -- even at 12% the few warps already saturated the random-access memory throughput, so extra warps just queue (per-instr stall scaled 28 -> 240 cyc). Kept as a saner default; the real lever is cutting scattered sector traffic (digest probing / hot-key warp dedup). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The dominant segmented_unique_kernel was bound by the contended atomicAdd(&table_counters[table_id], 1) used to hand out per-table local unique indices: num_tables is small, so each counter is hammered by ~all of that table's unique keys and serializes at the L2 atomic unit. This contention shows up as long_scoreboard stalls (the dependent use waits on the atomic), which earlier looked like scattered-probe memory latency -- only removing it disambiguated the two. Warp-aggregate via cooperative_groups: coalesced_threads() then labeled_partition() by table_id, so same-warp/same-table claimers share ONE atomicAdd(counter, group_size) and each takes base + group rank. Collapses up to 32 atomics into 1 per (warp, table_id); indices stay unique/contiguous. Measured on EOS H100 (TestGpu/sgd, iter_0): segmented_unique_kernel 305088 -> 100608 ns (-67%, ~3x) whole segmented_unique op 379712 -> 142464 ns (-62.5%, with the occupancy launch fix in the previous commit). Correctness: test_unique_op.py 19/19 pass (incl. overlapping/empty/random). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…bounds__)
Three register/codegen cleanups on segmented_unique_kernel:
- table_id: int64 -> int (values < num_tables < 2^31).
- probe index / capacity in uint32 with a 32-bit modulo (capacity =
2*num_keys < 2^32 since num_keys < INT32_MAX is enforced) -- cheaper than
the 64-bit modulo and fewer live registers.
- __launch_bounds__(BLOCK_SIZE, 8) to pin registers at 32 for 8 blocks/SM.
Result on EOS H100 (TestGpu/sgd, iter_0): 35 -> 32 regs with ZERO local
spilling; achieved occupancy 65% -> 90%. But duration is unchanged
(~102us): segmented_unique_kernel is not occupancy/register-bound (warp-agg
already removed the atomic-contention bottleneck), so this is register/
occupancy hygiene, not a speedup. Correctness: test_unique_op.py 19/19.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…variant Two experiments (both kept for history, reverted in the next commit): 1. src/probe_stats.cu (segmented_unique_probe_stats_cuda): diagnostic-only op that mirrors the composite probe and records per-key outcome + probe count. Finding on TestGpu/sgd (1.05M keys, 10 tables, ~35% unique): 94% of keys resolve on the first probe (mean 1.07), 66.5% are duplicates -> the cost is ~1 random L2 access per key, not long probe chains. 2. segmented_unique_cuda_combine: same result as segmented_unique_cuda via a sort-bucketed two-level dedup (radix-sort low 16 hash bits -> per-1024-block shared-hash dedup with warp aggregation -> merge to global). Correct (test parity on 5 scenarios incl. cross-table/empty/freq) but ~2.3x SLOWER end-to-end (351us vs 150us). ncu shows the combine kernel itself is 82.7%, dominated by __syncthreads barrier stalls (57.5%) from per-phase load imbalance -- the two-level scheme trades random-access latency for barrier/ spin overhead, which loses to the barrier-free single-pass warp-agg path. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…combine variant" This reverts commit a98f451.
Co-locate hash key + value into a single 16-byte SUSlot<KeyType>{key,val}
slot (one buffer) instead of two separate arrays, so a probe's key-check
and the duplicate's value-fetch land in the same L2 sector.
Measured on EOS H100 (TestGpu/sgd, segmented_unique_kernel):
- L2 hit rate 70.31% -> 73.42% (+3.1pp)
- L2 sectors 5,666,436 -> 5,460,479 (-3.6%)
- kernel time 102,368ns -> 101,888ns (-0.5%, within noise)
Correct (19/19 unit tests pass) but no real speedup: the kernel is
long_scoreboard-bound (90%) on scattered probe-load *latency*, not L2
bandwidth/capacity, so the modest L2 improvement does not move the
critical path. Reverted in the next commit; kept for history.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…le speedup)" This reverts commit a14a64d.
Add segmented_unique_shared_kernel: each block dedups a tile of 1024 consecutive keys in a shared-memory hash table (size 2x block, load factor <=0.5) before a single thread per occupied slot merges the distinct (key, table_id) into the global table. Collapses tile-local duplicates in fast shared memory to cut scattered global probes. Measured on EOS H100 (TestGpu/sgd, segmented_unique_shared_kernel): - global L2 sectors 5,666,436 -> 4,579,140 (-19%) - long_scoreboard 58.80 -> 17.27 cyc/instr (-71%, bottleneck crushed) - occupancy 89.9% -> 96.2% - kernel time 102,368ns -> 115,104ns (+12.5%, SLOWER) Correct (19/19 unit tests pass). The shared pre-dedup does attack the memory-latency bottleneck (long_scoreboard -71%), but the added cost -- 3 __syncthreads per tile (barrier stall 10.62 cyc/instr, new), per-key shared hashing (2.66M shared wavefronts), shared atomics and the producer/consumer spin on s_tabs -- exceeds the saved global latency, netting +12.5%. Concept is sound; this implementation is too heavy. Kept for history. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Replace the per-tile reset (flush every 1024 keys) with a PERSISTENT shared hash table per block: accumulate distinct (key,table_id) across the block's whole contiguous chunk and flush to the global table only when the table is about to fill (load factor 0.7). Per-input -> slot map moved to a global key_slot[num_keys] (an epoch's key count can exceed the table); scattered to output_indices before each clear. S=4096 (96KB) keeps 2 blocks/SM = full occupancy. Measured on EOS H100 (TestGpu/sgd, op:segmented_unique range, --num-iterations 1): - barrier stall 10.62 -> 7.34 cyc/instr (fewer flushes, as intended) - occupancy 96.8% -> 97.7% - kernel time 121,120ns -> 113,728ns (-6% vs per-tile reset) S=8192 (192KB, 1 block/SM) cuts flushes further (barrier 4.37, long_scoreboard 13.2) but drops occupancy to 50% and is SLOWER (123,968ns) -- the latency-bound kernel needs the occupancy, so the shared table should not exceed what keeps 2 blocks/SM. S=4096 is optimal. Still ~6% slower than the warp-aggregate per-key baseline: within-block duplicate rate is low (input sorted by table, so equal-value keys are scattered across the segment, not clustered in a contiguous chunk), so the shared layer's fixed cost (per-key shared hashing + key_slot global traffic, L2 sectors up to 5.15M) exceeds the saved global latency. Kept for history. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Radix-sort inputs by the low 8 bits of their combined (key,table_id)
hash (cub::DeviceRadixSort, begin_bit=0 end_bit=8) so equal keys cluster
into the same 256-bucket -> same block, giving the shared dedup a high
within-block duplicate rate. The shared table is then indexed with the
bits ABOVE the sort key (combined_hash >> 8) so a bucket's keys spread
across the table instead of piling into S/256 slots (that mistake first
made the kernel 2.4x slower at 271us; the high-bit fix restores it).
Measured on EOS H100 (TestGpu/sgd, op:segmented_unique range). Workload
is 67% duplicates (N_unique 350K / N_total 1.05M), so clustering does
collapse them -- global PROBE count drops ~1M -> ~350K. But it is a net
loss:
- dedup kernel 114,880ns -> 118,208ns (flat), L2 5.15M -> 6.22M,
long_scoreboard 25.4 -> 32.7 (WORSE)
- whole op ~157us -> ~234us (+49%)
Two reasons clustering does not pay off:
1. Permuting the input forces un-permuting the output: output_indices
is scattered back via output_indices[perm[i]] -- ~1M random global
writes that feed L2/long_scoreboard and cancel the probe savings.
2. sort+gather+hash+arange add ~75us of fixed overhead (onesweep 20us,
gather 23us, arange 12us, hash 9us, histogram 7us).
Kept for history.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ss)" This reverts commit ebedb9d.
Restructure su_flush into 3 phases so the per-table unique counter is
summed in SHARED first and committed to the GLOBAL table_counters with
ONE atomic per table per flush, instead of a global atomicAdd per
warp-aggregated claim:
Phase 1 - probe/claim the global table; new claims bump shared
s_tcount[t]. A claim publishes its table_id immediately with
a PENDING (-1) index so concurrent probers disambiguate the
composite (key,table_id) without waiting for the index.
Phase 2 - one atomicAdd(table_counters[t], s_tcount[t]) reserves a
contiguous range per table.
Phase 3 - claimers draw the local idx from shared s_tnext[t] and
publish the final hash_vals; duplicates spin for it.
Claimers publish before any spin -> deadlock-free across blocks.
Adds s_ghash[S] (4B/slot) to carry the global probe index across phases;
24->28 B/slot, still 2 blocks/SM (full occupancy) at S=4096.
Measured on EOS H100 (TestGpu/sgd, op:segmented_unique range):
- long_scoreboard 25.43 -> 11.54 cyc/instr (global-atomic stall gone)
- dedup kernel 114,880ns -> 106,592ns (-7%)
- whole op ~157us -> ~149us
Correct (19/19 unit tests pass). Confirms the table_counters atomic was
still a measurable stall source even after warp-aggregation; block-level
privatization removes it.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Apply the privatized table_counters trick to a lean per-key kernel (no
shared dedup table): block 1024, output_indices doubles as scratch to
carry the global probe slot between two grid-stride passes; phase 1
counts new keys in shared, phase 2 reserves one global range per table,
phase 3 assigns/publishes. Host sizes grid to max active blocks
(cudaOccupancyMaxActiveBlocksPerMultiprocessor) so the deferred
cross-block publish never deadlocks.
Measured on EOS H100 (TestGpu/sgd, op:segmented_unique range):
- dedup kernel 102,208ns, reg 22, occ 96%, barrier 4.11
- beats flush-on-fill+privatize (106,592ns) in the same op-range mode
- long_scoreboard 48.9 / L2 6->9.1M higher (every key probes global,
no dedup collapse) but the leaner kernel still wins on duration.
Correct (19/19). The shared-dedup machinery was net overhead; privatized
counter on the lean per-key kernel is better.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…eline
Replace the 3-phase (two-full-pass) per-key body with a SINGLE-pass
per-wave reduction (the user's design): a block processes keys in waves
of blockDim; within a wave each key is probed once (original claim/find
logic); a new claim takes a block-local rank via shared atomicAdd(s_wc[t])
and publishes its table_id immediately (PENDING idx); then ONE global
atomicAdd(table_counters[t], s_wc[t]) per table fetches the base, and
local_idx = base + rank. No second full pass, no output_indices scratch.
Measured on EOS H100 (TestGpu/sgd, op:segmented_unique range):
- dedup kernel 81,856ns, reg 25, occ 97% (vs 3-phase 102,208ns;
flush-on-fill+privatize 106,592ns; warp-agg baseline ~102us)
- L2 sectors 9.1M -> 6.27M (single pass, no re-traversal)
- barrier 4.1 -> 20.4 (per-wave syncs) but the single pass wins big
- whole op ~145us -> ~125us
Correct (19/19). Single pass kills BOTH the global-atomic contention
(shared per-wave reduction) and the double global traversal.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Process U=2 keys per thread with interleaved probe loads to raise
memory-level parallelism (hide long_scoreboard latency that 97%
occupancy alone cannot). Final variant moves the cold per-lane state
(idx/freq/kind/rank) into shared so the hot probe fits <=32 regs at full
occupancy without local spills.
Measured on EOS H100 (TestGpu/sgd, op:segmented_unique range):
- natural reg 48 -> 98,272ns, occ 50%, long_scoreboard 26 (MLP works,
but reg pressure halves occupancy)
- forced reg<=32 -> 95,840ns, occ 96%, long_scoreboard 58 (local spills hurt)
- cold state in shared-> 82,784ns, occ 96%, long_scoreboard 40 (MLP cashed,
but shared/bookkeeping overhead offsets it)
vs per-wave U=1: 81,856ns. So unroll-2 only TIES (+1.1%, within noise).
Correct (19/19). MLP reduces latency but the bookkeeping cost (regs->
occupancy or shared traffic) eats the gain on this kernel. Reverted; the
simpler per-wave U=1 (fewer regs, no 40KB shared) stays the winner.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…e, not kept" This reverts commit 55f2a46.
… kernel Rename the host tensor table_offsets to unique_table_offsets for clarity, allocate it with at::empty (uninitialized) instead of at::zeros, and seed element [0]=0 inside segmented_init_kernel (the inclusive scan fills [1..num_tables], so only [0] needs seeding). This drops the separate zero-init (at::zeros launches a fill) and folds it into the existing init kernel. Empty-input early-return path renamed too (kept at::zeros there; it does not run the init kernel). Verified on EOS H100: 19/19 unit tests pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… shared Eliminate expand_table_ids_kernel and the num_keys-sized table_ids int64 array entirely from segmented_unique_cuda. The dedup and adjust kernels now cache the tiny segmented_range (num_tables+1) in shared memory and binary-search it to get a key's table_id on the fly. binary_search_upper_bound moved above the kernels so both can use it. (expand_table_ids_cuda public op is unchanged.) Measured on EOS H100 (TestGpu/sgd, op:segmented_unique range): - expand_table_ids kernel (6.7us) + its elementwise (3.1us): gone - adjust 9,600 -> 7,872ns (no big table_ids reads) - dedup unchanged 81,632ns (shared binary search is free) - whole op 125,120 -> 113,248ns (-9.5%) Cumulative vs warp-agg baseline: dedup 105,120 -> 81,632 (-22.3%), whole op 147,552 -> 113,248 (-23.2%). Correct (19/19 unit tests pass). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Lanes that claim a new key for the SAME table in a warp now share one
shared atomicAdd(&s_wc[t], grp.size()) (cg::labeled_partition) instead of
each serializing on s_wc[t]. Input is table-sorted so same-table claims
cluster in a warp -> high contention on the shared counter; this is the
same warp-aggregation already used for the global table_counters.
Measured on EOS H100 (TestGpu/sgd, op:segmented_unique range):
- dedup 81,632 -> 80,416ns (-1.5%), reg 25->28 (still full occupancy),
long_scoreboard ~50 -> 37.
Small win as expected -- the shared atomic is on-chip and largely hidden
behind the global-probe latency that bounds this kernel -- but principled
and correctness-neutral. Correct (19/19 unit tests pass).
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Drop the separate cub::DeviceScan::InclusiveSum (2 kernels: DeviceScanInitKernel + DeviceScanKernel). num_tables is small, so each block of compact_keys_and_freq_kernel now builds the inclusive prefix sum of table_counters in shared (s_off[0..num_tables]); block 0 publishes it to the global unique_table_offsets (for adjust + the return value), and every block uses its shared copy for compaction. The now-redundant unique_table_offsets[0] seeding is removed from segmented_init_kernel. Measured on EOS H100 (TestGpu/sgd, op:segmented_unique range): - 2 cub scan kernels (2,528 + 4,224 = 6,752ns) removed - compact 5,952 -> 6,880ns (absorbs the prefix sum) - whole op ~113k -> 107,616ns (6 kernels -> 4) Cumulative vs warp-agg baseline: whole op 147,552 -> 107,616 (-27.1%). Correct (19/19 unit tests pass). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Fold the output-index global-adjust pass into the compact kernel: it now
caches both the unique-offset prefix sum (s_off) and segmented_range
(s_seg) in shared and runs two independent grid-stride loops -- compaction
over [0,total_unique) and adjust (output_indices[i] += s_off[table_id(i)])
over [0,num_keys). Removes the standalone adjust_output_indices_kernel.
Measured on EOS H100 (TestGpu/sgd, op:segmented_unique range):
- compact 6,880 + adjust 8,000 (two kernels) -> 13,248ns (one kernel)
- op now 3 kernels (init / dedup / compact+adjust), down from 8 at the
start of this work.
Correct: 19/19 unit tests pass, and the benchmark workload runs clean
standalone. Verified the tested .so is freshly built from current source
(.so mtime > unique_op.cu mtime). (A one-off ncu --set full SIGSEGV under
kernel replay did NOT reproduce across repeated runs -- transient tool
issue, not a code bug.)
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…bles)
Replace the thread-0 serial scan of table_counters (O(num_tables)) in
compact_keys_and_freq_kernel with a block-cooperative exclusive prefix
sum (block_offsets_scan): contiguous per-thread chunk sums + a
Hillis-Steele scan of the per-thread totals -> O(num_tables/blockDim +
log blockDim), scaling to hundreds/thousands of tables. Adds a
s_part[blockDim] shared scratch; compact shared is opt-in now since it
can exceed 48KB for large num_tables.
Measured on EOS H100 (TestGpu/sgd, 10 tables, op:segmented_unique range):
- correct: 19/19 unit tests pass (incl 16-table cases)
- compact 13,216 -> 12,960ns, reg 34 -> 32, occupancy 57.7% -> 90.1%
(removing the long single-thread serial section)
At 10 tables runtime is ~unchanged (the serial scan was already cheap);
the benefit is scalability to large num_tables + the occupancy gain.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…(net loss)
Replace partitioned_unique_keys (buffer + gather) with a per-input
local_index[num_keys] int32 (init -1, folded into segmented_init_kernel's
hash-init loop since capacity >= num_keys): the dedup claimer writes
local_index[idx]=local_idx (coalesced) instead of scattering the key into
a partitioned buffer, and compact becomes a single num_keys loop that
adjusts output_indices and scatters keys[idx]/freq for entries >= 0.
Measured on EOS H100 (TestGpu/sgd, op:segmented_unique range):
- dedup 80,576 -> ~81,000ns (UNCHANGED: the removed key store is
fire-and-forget, not on the load-latency critical path -- the hoped
dedup speedup did not materialize)
- init 10,624 -> ~12,100ns (+1.5us = the 4MB local_index writes;
merging the init loops does not help, init is write-bandwidth bound)
- compact 12,960 -> 15,392ns (+2.4us: output_keys[base+li] is a
scattered write vs the old contiguous output_keys[idx])
- whole op 104,160 -> ~108,900ns (+4.5%)
Saves ~4MB (8MB partitioned keys removed, 4MB local_index added) but is a
net runtime regression. Correct (19/19). Reverted next; kept for history.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… buffer (net loss)" This reverts commit 68620c3.
Rename for clarity: segmented_init_kernel -> segmented_unique_prepare segmented_unique_perkey_kernel -> segmented_unique_core compact_keys_and_freq_kernel -> segmented_unique_finalize Remove dead code left from the optimization exploration (none was launched): - segmented_unique_kernel (original per-key warp-agg version) - segmented_unique_shared_kernel (flush-on-fill two-level dedup) - su_flush (flush-on-fill merge helper) - global_insert (orphan device helper) - SHARED_TABLE_SIZE / SHARED_FLUSH_CAP constants (only used by the above) - key_slot tensor in the host (allocated but never used) SHARED_BLOCK_SIZE is kept (moved to the top, used by core). Refresh the stale comments (segmented_unique_core's description now matches the per-wave / privatized-counter / shared binary-search implementation; grid-sizing and launch_bounds comments no longer reference removed symbols). Verified on EOS H100: 19/19 unit tests pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Replace the open-addressing table (hash_keys[2N]+hash_vals[2N] int64,
32MB) with a chaining hash: per-table bucket space head[4*N] (int32),
chain pointers next[N], a claimer marker rep_local[N], per-node freq, and
the keys read straight from the (reused) input array.
- per-table bucket offset (4*seg[t], size 4*table_size) -> the hash is
just hash(key); no table_id stored/hashed/verified;
- lock-free TAIL-APPEND dedup: walk head->next, key match = duplicate;
at the tail ::atomicCAS(-1, idx) appends, the CAS loser re-walks the
new tail (collapsing same-key races) -> exactly one node per distinct
key, even under high duplication;
- privatized per-wave counter retained; a claimer publishes its local
index via output_indices, duplicates spin on the rep's;
- finalize emits keys/freq for representative nodes (rep_local >= 0).
Measured on EOS H100 (TestGpu/sgd, op:segmented_unique range):
- core dedup 81,088 -> 56,032ns (-31%); L2 sectors ~5-6M -> 4.37M;
long_scoreboard ~50 -> 33.6; occ 96%.
- whole op ~104,900 -> ~82,800ns (-21%).
The smaller hot footprint (16MB int32 head + reused keys vs 32MB) lifts
L2 residency, directly cutting the random-probe latency that bounds this
kernel. Correct: 19/19 unit tests pass.
Cumulative vs the warp-agg baseline: op 147,552 -> 82,848ns (-44%).
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
In the chaining core, a duplicate no longer spins on its representative's
published index. Instead it records rep_local[idx] = -(rep+1) (negative,
encoding the rep node) and moves on; the claimer just records its local
index in rep_local. No output_indices writes, no volatile publish, no
spin in the hot kernel -- and thus no cross-block co-residency requirement.
Finalize derives every input's global index from rep_local: a rep (>=0)
maps to base+rep_local[idx]; a duplicate reads rep_local[rep] (the rep's
local index, read-only there so race-free) and maps to base+that.
prepare drops the output_indices/rep_local inits accordingly.
Measured on EOS H100 (TestGpu/sgd, op:segmented_unique range):
- core 56,032 -> 41,120ns (-27%); long_scoreboard 33.6 -> 23.6;
L2 sectors 4.37M -> 3.11M (no output_indices writes in core); occ 97%.
- prepare 11,072 -> 8,000ns (two fewer arrays to init).
- whole op ~82,800 -> ~65,000ns.
Correct: 19/19 unit tests pass.
Cumulative vs the warp-agg baseline: core 105,120 -> 41,120 (-61%),
whole op 147,552 -> 65,024 (-56%).
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
After deferring duplicate resolution to finalize there is no cross-block wait, so the residency cap is no longer a correctness requirement -- it is kept purely for performance: a resident block grid-striding over several waves amortizes its s_segrange load and keeps the SMs busy. Measured one-block-per-wave (full grid, no cap) and it was slower (core 41,120 -> 46,112ns): the per-wave barrier stall is intra-block load imbalance, not wave count, so more blocks do not help and the extra per-block s_segrange reloads cost more. Comment-only; logic unchanged. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Remove the per-wave privatized counter: flat grid-stride loop, claimers take their local index straight from a warp-aggregated global atomicAdd(table_counters[t]). No s_wc/s_base, no per-wave barriers. Measured on EOS H100 (TestGpu/sgd, op:segmented_unique range): - barrier stall 12.3 -> 0.36 (barriers gone, as intended) - BUT core 41,120 -> 79,808ns (+94%), occ 96% -> 85% The ~10-table table_counters[t] is hammered by the whole grid (even warp-aggregated), and that global-atomic contention is far costlier than the per-wave barriers it replaced. Correct (19/19) but a big regression. Reverted: the privatized per-wave counter (with its barriers) is the sweet spot -- barriers here are cheaper than the contention they avoid. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…h slower" This reverts commit 1b5ed4c.
Three session-wide CLI overrides on the batched dynamicemb benchmark,
registered in conftest.pytest_addoption and applied in _apply_overrides:
--num-tables N Rebuild every config for N tables, holding the per-suite
total capacity and total batch fixed (cap/table =
total//N, batch_size = total_batch//N). Stresses the
many-tables path (e.g. 1000 tables) without changing the
overall HBM footprint or total key count.
--sparse-key-range N Each table samples indices from [.., N) instead of
[.., per-table cap), so the duplicate rate is controlled
independently of capacity (smaller N -> more dups).
--no-torchrec Skip the TorchRec/FBGEMM TBE baseline entirely (neither
built nor run); only DynamicEmb is exercised, trc_*
metrics are null. Auto-disabled under --correctness
(which needs the baseline).
Supporting changes: BenchmarkConfig gains sparse_key_range/run_torchrec
fields; generate_sparse_features_gpu honors sparse_key_range; the torchrec
baseline is made optional across benchmark_train_eval / run_reporting_loop /
benchmark_with_nsys / the torch-profiler path; label() renders sub-MB caps in
K (so 1000-table 16K caps no longer show as "0M").
Validated on EOS H100: 1000-table + --no-torchrec run passes (dyn-only,
total cap 1000x16777); 10-table run with torchrec + --sparse-key-range 8192
passes (N_unique tracks the range); default path unchanged.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
segmented_unique_core's shared (s_wc + s_base + s_segrange) is 16*num_tables + 8 bytes, exceeding the 48KB default dynamic-shared limit once num_tables > ~3071. Without a cudaFuncSetAttribute opt-in the driver rejects the launch (cudaErrorInvalidValue) -- and the blocks_per_sm<1 guard does not catch it, since cudaOccupancyMaxActiveBlocksPerMultiprocessor also returns 0 for an oversized request, so the kernel still launches and errors at the following DEMB_CUDA_KERNEL_LAUNCH_CHECK(). Add the same opt-in segmented_unique_finalize already uses, before the occupancy query so it accounts for the raised limit. Reachable via the new --num-tables. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ntics - conftest --profile help: 'ncu' runs all iterations inside one cudaProfilerStart/Stop window (use --num-iterations to bound replay overhead), replacing the stale "single-iteration" wording. - parse_ncu_iterations docstring: None means "not specified by the caller"; print_ncu_command treats it as iteration 0 only. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Regenerate the committed figures from fresh runs of the rebased benchmark-ncu-improvements (optimized segmented_unique), all on one H100: - benchmark_bdet_plot.png: from a full profile=none sweep (10 cases: TestGpu/Caching/NoCaching/NoHbm x adam/sgd, +cfr for caching) via plot_benchmark_results.py. - breakdown_sgd_gpu.png / breakdown_adam_caching_cfr1.0.png: per-op GPU time sunbursts via the nsys pipeline (nsys profile --profile nsys -> nsys_breakdown.py -> nsys_sunburst.py). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
a585384 to
b5e580d
Compare



Description
Checklist