Skip to content

Refactor dynamicemb benchmark - #396

Merged
shijieliu merged 35 commits into
NVIDIA:mainfrom
jiashuy:new_bench_fix
May 26, 2026
Merged

shijieliu merged 35 commits into
NVIDIA:mainfrom
jiashuy:new_bench_fix

Conversation

@jiashuy

@jiashuy jiashuy commented May 19, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Checklist

  • I am familiar with the Contributing Guidelines.
  • New or existing tests cover these changes.
  • The documentation is up to date with these changes.

@greptile-apps

greptile-apps Bot commented May 19, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR refactors the DynamicEmb benchmark from an argparse-based script to a pytest parametrize suite, adds dual-backend (DynamicEmb + TorchRec TBE) comparative timing, introduces a correctness-verification mode, adds comprehensive NVTX instrumentation throughout batched_dynamicemb_function.py, and ships three new tooling files (nsys_breakdown.py, nsys_sunburst.py, plot_benchmark_results.py) for trace analysis and result visualization.

  • pytest-based benchmark suite: BenchmarkConfig dataclass replaces CLI args; test classes (TestGpu, TestCaching, TestNoCaching, TestNoHBM) parametrize over optimizer × pooling × batch-size; results are written incrementally to a JSON file consumed by plot_benchmark_results.py.
  • Correctness mode: --correctness flag mirrors TorchRec's first-half embeddings into DynamicEmb and compares per-iteration forward outputs; the random distribution silently ignores the half-cap constraint, producing meaningless comparisons when that combination is used (see inline comment).
  • NVTX wrapping: Every major op in batched_dynamicemb_function.py is wrapped with torch.cuda.nvtx.range using an op:<name> prefix, enabling per-op breakdown via nsys_breakdown.py.

Confidence Score: 5/5

Safe to merge — changes are benchmark tooling only; core library code in batched_dynamicemb_function.py receives only NVTX instrumentation with no logic changes.

The only production-code change in batched_dynamicemb_function.py is mechanical NVTX wrapping that has no effect outside a profiling context. All other changes are benchmark scripts, visualization tools, and test infrastructure. The correctness-mode gap (random distribution ignores half_caps) affects a non-default combination and doesn't corrupt benchmark timing data.

benchmark_batched_dynamicemb_tables.py — the random distribution + correctness mode interaction; nsys_breakdown.py — unclosed file handle at module import.

Important Files Changed

Filename Overview
corelib/dynamicemb/benchmark/benchmark_batched_dynamicemb_tables.py Major refactor: arg-parse CLI replaced with pytest parametrize + BenchmarkConfig dataclass; dual-backend (DynamicEmb + TorchRec) timing added; correctness mode added; NVTX ranges added throughout; one logic gap in the random-distribution branch ignores num_embeddings_override.
corelib/dynamicemb/dynamicemb/batched_dynamicemb_function.py Mechanical NVTX wrapping of all major ops (cache_lookup, storage_find, flagged_compact, initializer, etc.) for nsys profiling; no logic changes, only instrumentation.
corelib/dynamicemb/benchmark/conftest.py New pytest conftest: session fixtures for dist, device, timer, profile_mode, correctness_flag; autouse GPU memory cleanup between tests.
corelib/dynamicemb/benchmark/dataset_generator.py zipf refactored from numpy to torch.multinomial (avoids CPU-GPU round-trips); gen_jagged_key extended to support multi-table KJT; numpy dependency removed.
corelib/dynamicemb/benchmark/nsys_breakdown.py New file: extracts per-op NVTX breakdown from nsys-rep traces into CSVs; loads KERNEL_NAME_PATTERNS via AST at module import time with an unclosed file handle.
corelib/dynamicemb/benchmark/nsys_sunburst.py New visualization tool: renders per-op breakdown CSVs from nsys_breakdown.py as interactive sunburst charts using Plotly.
corelib/dynamicemb/benchmark/plot_benchmark_results.py New plotting script: reads benchmark_results.json and renders per-optimizer stacked bar charts for all storage modes (GPU / Caching / NoCaching / NoHBM).

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A["benchmark_batched_dynamicemb_tables.sh\ntorchrun -m pytest"] --> B["conftest.py\nsession fixtures: dist, device, timer"]
    B --> C{profile_mode?}
    C -- "ncu-gen" --> D["print_ncu_command(cfg)\nreturn early"]
    C -- "torch / nsys / ncu-run" --> E["profiling path\n(run_reporting_loop warmup\n+ profiling loop)"]
    C -- "None (default)" --> F["run_reporting_loop\n(warmup, skipped when correctness=True)"]
    F --> G["benchmark_train_eval\n(CUDA Events: dyn + trc)"]
    E --> G
    G --> H["append_result → benchmark_results.json"]
    H --> I["plot_benchmark_results.py\n→ benchmark_bdet_plot.png"]
    H --> J["nsys_breakdown.py\n→ opcalls__*.csv"]
    J --> K["nsys_sunburst.py\n→ interactive HTML"]
Loading

Reviews (6): Last reviewed commit: "benchmark: refresh H100 results and plot..." | Re-trigger Greptile

@jiashuy

jiashuy commented May 19, 2026 •

Copy link
Copy Markdown
Collaborator Author

why performance mismatch?

image

dynamicemb don't load or load less from PCIe.

The reason is that we use fill_tables to improve the load factor of the storage, but not flush the cache and reset the cache directly after warmup.

so the input keys will all miss on storage

@jiashuy

jiashuy commented May 19, 2026 •

Copy link
Copy Markdown
Collaborator Author

current performance(caching & adam):
DynamicEmb train=12.074 fwd=11.191 bwd=0.884 eval=0.495 ms
TorchRec train=13.000 fwd=3.617 bwd=9.383 eval=2.397 ms

@jiashuy

jiashuy commented May 19, 2026

Copy link
Copy Markdown
Collaborator Author
{
    "caching": true,
    "batch_size": 1048576,
    "num_embeddings_per_feature": [
        268435456
    ],
    "hbm_for_embeddings": [
        41231686041
    ],
    "optimizer_type": "adam",
    "feature_distribution-alpha": "pow-law-1.05",
    "embedding_dim": 128,
    "num_iterations": 100,
    "cache_algorithm": "lru",
    "use_index_dedup": false,
    "eval(torchrec)": 1.9628275120258332,
    "forward(torchrec)": 3.2867475247383116,
    "backward(torchrec)": 9.387946557998657,
    "train(torchrec)": 12.674694147109985,
    "eval(dynamicemb)": 0.4539583998918533,
    "forward(dynamicemb)": 9.69936700820923,
    "backward(dynamicemb)": 0.8845200020074845,
    "train(dynamicemb)": 10.583887071609498
},

@jiashuy
jiashuy requested a review from shijieliu May 19, 2026 08:27
@jiashuy

jiashuy commented May 26, 2026 •

Copy link
Copy Markdown
Collaborator Author

Progress

  1. support single and multi-table(default) benchmark with profile_mode=none
# run every test suites
bash ./benchmark/benchmark_batched_dynamicemb_tables.sh

# Only Adam configs (any suite)
bash ./benchmark/benchmark_batched_dynamicemb_tables.sh -k adam

# Combine
bash ./benchmark/benchmark_batched_dynamicemb_tables.sh -k "TestCaching and adam"

# List configs without running anything
bash ./benchmark/benchmark_batched_dynamicemb_tables.sh --co
# Main figure into ./plots/benchmark_bdet_plot.png
python plot_benchmark_results.py
  1. support performance breakdown with profile_mode=nsys
# pseudocode — see run_nsys_loop.sbatch for the working version
for TEST_ID in $(pytest --collect-only -q ...); do
    LABEL=$(echo "$TEST_ID" | sed -E 's/.*\[(.+)\]$/\1/')
    nsys profile \
        --output=nsys_run/trace_${LABEL} \
        --sample=none --cpuctxsw=none \
        --trace=cuda,nvtx,osrt --cuda-graph-trace=node \
        --capture-range=cudaProfilerApi \
        --capture-range-end=stop \
        torchrun --nnodes 1 --nproc_per_node 1 \
            -m pytest -svv --profile nsys "$TEST_ID"
done

python nsys_breakdown.py nsys_run/*.nsys-rep --out-dir nsys_run/
# -> nsys_run/opcalls__<cfg-label>.csv  (one CSV per .nsys-rep)

python nsys_sunburst.py nsys_run/opcalls__*.csv
# -> nsys_run/opcalls__<cfg-label>.sunburst.png  (next to each CSV)
  1. support to check the correctness with :
bash ./benchmark/benchmark_batched_dynamicemb_tables.sh --correctness

more information please refer to README.md

@jiashuy

jiashuy commented May 26, 2026

Copy link
Copy Markdown
Collaborator Author
image image image

jiashuy and others added 18 commits May 26, 2026 19:44
…ctor-dynamicemb_benchmark

- Replace shell loop runner with torchrun -m pytest (benchmark_batched_dynamicemb_tables.sh)
- Add conftest.py: dist_group/device/timer/profile_mode pytest fixtures
- dataset_generator.py: multi-table PowerLaw support, replace np.random with torch.multinomial
- benchmark_batched_dynamicemb_tables.py: argparse -> BenchmarkConfig dataclass + pytest classes

Port current-branch logic into new structure:
- Add is_hybrid_storage(): only manually insert table data for HybridStorage configs
- Add var.fill_tables() for non-hybrid cases (pure HBM / no-HBM)
- benchmark_train_eval: replace GPUTimer with CUDA Events for per-iter fwd/bwd precision
- Do not reset cache states before benchmark (measure warm-cache hit rate)

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Add _no_hbm_configs() (gpu_ratio=0.0, hbm_for_embeddings=0, caching=False)
and TestNoHbm test class. Update BenchmarkConfig.mode to return "no_hbm"
when gpu_ratio==0 to distinguish from the hybrid no_caching case.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…ming

When profile_mode=None, run a reporting loop before benchmark_train_eval
that prints per-iteration forward/backward/total latency for both
DynamicEmb and TorchRec, with cache hit rate and miss count when caching
is enabled. Reset cache states after the reporting loop so that
benchmark_train_eval measures from a clean state.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…utputs

Add a per-config `correctness` flag and a `--correctness` pytest CLI override.
When enabled, sparse features are sampled from `[0, cap/2)`, DynamicEmb is
populated by mirroring TorchRec's `[0, cap/2)` weight slice in 1M-row chunks,
and benchmark_train_eval (now driving both backends with a shared randn grad
allocated outside the timed loop) asserts torch.allclose on forward outputs
each iter with precision-aware tolerance.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Three small fixes uncovered while running --correctness on TestGpu:
- Default cfg.eps was 1e-3, which made Adam's `sqrt(v_hat) + eps` term
  amplify per-backend formula differences (__powf bias correction, eps
  placement) into ~2e-4 max_diff.  Set to the PyTorch standard 1e-8 so
  Adam diff drops below atol.
- Pass stochastic_rounding=False and bounds_check_mode=NONE to
  BatchedDynamicEmbeddingTablesV2 so its construction matches the
  TorchRec TBE side; remaining differences are kernel-level only.
- precompute_unique_counts was calling the old expand_table_ids_cuda /
  segmented_unique_cuda signatures.  Drop the obsolete expand step and
  pass per-table segment_range directly to match the new API.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Two fixes uncovered while running the full --correctness suite on
eos H200:

- conftest: add an autouse fixture that runs gc.collect() and
  torch.cuda.empty_cache() after every test.  run_single_benchmark's
  own cleanup is skipped on the exception path, so one OOM was
  cascading into every subsequent suite.
- _populate_correctness_tables: drop the mirror chunk size from 1M
  to 256K rows.  With dyn+trc both holding full Adam state in HBM,
  the previous 1M chunk's init_w+opt_zero+cat workspace (~1.5 GiB)
  was tipping TestGpu adam over the 80 GiB H200 budget.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
torch.allclose recomputes (a-b).abs() and rtol*|b| inside its body.
For TestGpu's 1M x 128 fp32 output that stacked ~2.5 GiB of transients
on top of the 72 GiB dyn+trc Adam tables and tipped the iter over the
80 GiB H200 budget.

Factor the check into _forward_allclose which reuses the already-
computed diff in-place (diff <- |a-b| - rtol*|b|; passed = max <= atol)
and frees intermediates as soon as it's done.  Peak per-iter workspace
drops from ~2.5 GiB to ~1 GiB.  Used by both train and eval comparison
sites.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…ndow

Previously `--profile nsys` just printed a note and fell through to the
default reporting + timing path, so nsys had to capture all 200+
unrelated iters and the setup kernels.

Add benchmark_with_nsys that mirrors benchmark_with_ncu's
cudaProfilerStart/Stop pattern but covers both backends in the same
loop -- one iter pushes dyn fwd+bwd and trc fwd+bwd side by side, so
nsys-ui can compare them directly.  The outer NVTX range is named
after cfg.label() so multiple traces stay distinguishable.

The nsys branch in run_single_benchmark now:
  - runs run_reporting_loop as untimed warmup (outside the capture)
  - calls benchmark_with_nsys (inside the capture)
  - returns early, skipping benchmark_train_eval

Also early-return the torch profile branch the same way (was
fall-through, redoing 200 untimed iters in benchmark_train_eval).

Launch with:
  nsys profile --capture-range=cudaProfilerApi --capture-range-end=stop ...

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Profile modes capture/profile a workload, they don't validate it.
With cfg.correctness=True the sampler is restricted to [0, cap/2)
and dyn is populated from trc's first half -- traces taken under
that regime don't reflect the production sampling distribution, and
the nsys path's reporting_loop warmup also breaks the populate-time
weight alignment.

When profile_mode is set, force cfg.correctness=False and warn if
the user explicitly asked for it.  ncu-gen returns before this check
so it's unaffected.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Previously only the correctness path restricted sparse-feature
sampling to [0, cap/2).  Extend the same restriction to:
  - profile_mode=None (default timing run)
  - profile_mode="nsys"

so timing numbers, nsys traces, and the correctness comparison all
share an identical workload distribution.  torch / ncu-run keep the
old full-cap sampling since they measure op- or kernel-level metrics
where the working-set shape isn't the focus.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
jiashuy and others added 17 commits May 26, 2026 19:44
Document the four pytest suites, how to select a subset via -k, the
correctness mode (cap/2 sampling + TorchRec mirror), and the nsys
workflow with cudaProfilerStart/Stop + the launch command users need.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…h size

Drop the is_hybrid_storage branch in create_dynamic_embedding_tables.
Previously full-HBM / caching paths used var.fill_tables(), which only
stamps random keys into the hash map and leaves the embedding / opt-
state slots zero -- every subsequent lookup admitted-and-initialized
instead of hitting the populated row, skewing comparisons across modes.

Now every flavor (gpu / caching / hybrid / no-hbm) is populated via
storage.insert with random fp32 weights for [0, num_embeddings).

Hoist _INSERT_BATCH (= 256 * 1024) to the module-level constants
section so both create_dynamic_embedding_tables and
_populate_correctness_tables share the same chunk size; the previous
1M chunk size for fill-style populate would push H200 over its 80 GiB
budget once Adam optstate is included.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Walk back two recent changes that altered the default workload shape:
  - half-cap sampling is now scoped back to cfg.correctness=True only;
    profile_mode=None/nsys go back to full-cap sampling.
  - create_dynamic_embedding_tables: restore the is_hybrid_storage
    branch.  Hybrid storage still uses chunked storage.insert (with
    the shared _INSERT_BATCH=256K), but full-HBM / caching / no-HBM
    modes go back to var.fill_tables() instead of the unified insert
    path.

Keeps the unrelated improvements that landed alongside (module-level
_INSERT_BATCH, flush() before reset_cache_states, force-disable
correctness under any profile mode, dedicated nsys path).

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Adds plot_benchmark_results.py which consumes benchmark_results.json and
renders two figures:

  - benchmark_bdet_plot.png: per-suite latency comparison (2 rows by
    optimizer x 4 cols by storage mode).  Each panel stacks
    `train = fwd + bwd` next to a separate `eval` bar for DynamicEmb vs
    TorchRec, with independent y-axis auto-scaling.
  - benchmark_bdet_speedup_plot.png (with --speedup): same 2x4 layout
    showing TorchRec / DynamicEmb per metric, with a dashed 1.0x parity
    line.

CLI:
  python plot_benchmark_results.py [--results PATH] [--out PATH]
                                   [--speedup [--speedup-out PATH]]
                                   [--log] [--no-values]

README's plotting and Test Results sections are rewritten to describe
the new script and to make it explicit that the bundled figures were
captured on NVIDIA H100 80GB HBM3.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
The json captures the 8-config H100 sweep (4 storage modes x 2
optimizers) that backs benchmark_bdet_plot.png and
benchmark_bdet_speedup_plot.png so anyone regenerating the figures
can do so without first re-running the suite, and so the plot script's
default --results path points at a file that exists out of the box.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
The previous version split the config label on "=" and AND-joined the
fragments to build the pytest -k expression.  cfg.label() embeds two
literal "=" signs inside its values (pool=none, cap=24M), so the split
produced cross-field chunks like "none_cap" -- they happened to be
substrings of the test id today, but the filter would silently drift
the moment the label format changed or two configs shared a fragment.

pytest -k matches any substring of the test id, and the parametrize id
*is* cfg.label(), so passing the whole label is both simpler and the
unambiguous single-config selector.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
The hybrid-storage populate loop iterated up to
max(cfg.num_embeddings_per_feature) and inserted the same [start, end)
range into every table.  All current configs use a uniform per-table
cap so this is latent, but the function is general enough to be called
with heterogeneous caps, in which case keys past a smaller table's cap
would overflow its hash map.

Build per-table (keys, table_ids) lists inside each chunk and clamp
end_t to that table's own capacity, skipping tables that are already
full.  cat the surviving fragments into a single insert call so the
batched API pattern is preserved.  Uniform-cap configs produce
identical inserts to before; heterogeneous configs are now safe.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
- BenchmarkConfig.cache_footprint_ratio: when set together with
  caching=True, the cache is resized at runtime to
  per_table_unique_footprint * ratio rows.  DynamicEmb HBM bytes
  and FBGEMM cache_load_factor are both derived from this target.
  TestCaching now sweeps [0.5, 0.8].
- Sparse features are generated before table creation so the
  unique-key footprint can be measured up front.
- Result dict picks up gpu_name, cache_footprint_ratio, alpha and
  max_hotness so downstream plotting can label the workload.
- plot_benchmark_results.py: --out / --speedup-out collapsed into
  --out-dir (default ./plots/); one main + one speedup figure are
  emitted per cache_footprint_ratio.  Two-line subtitle shows
  GPU / D / batch on the first line and
  distribution(alpha) / hotness / pool / cache_footprint_ratio on
  the second, all derived from JSON metadata.
- Move benchmark_bdet_plot.png and benchmark_bdet_speedup_plot.png
  into benchmark/plots/; drop the unreferenced
  benchmark_bdet_results.png.  README updated accordingly.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Several related changes batched together because they all bear on the
caching workload's measurement story:

* run_single_benchmark no longer flushes / resets the cache after the
  reporting-loop warmup -- only the hit-rate recorder is turned off.
  benchmark_train_eval therefore measures steady-state cache behavior
  instead of a cold start.  The same change applies to the nsys
  profile path (so it captures steady-state kernels too).  The torch
  profiler path's flush block was dead code (immediately followed by
  del + empty_cache) and is removed.

* plot_benchmark_results.py: one figure instead of per-ratio PNGs.
  The caching column fans out into one panel per cache_footprint_ratio
  found in the JSON, so cfr=0.5 and cfr=0.8 sit side by side; figure
  width auto-scales with column count.  Panel titles drop the
  gpu_ratio hint (was "Caching\n(10% LRU)") in favor of
  "Caching\ncfr=0.5".  Subtitle drops the cfr line (panel titles
  cover it).  New helpers: build_panels / panel_label / collect_panel.

* _gpu_configs cap_per_table: 24M -> 16M.  At 24M with Adam the dual-
  backend (DynamicEmb + TorchRec) HBM footprint peaked >78 GiB on H100
  80GB and OOM'd inside benchmark_train_eval.  16M halves each table
  to ~25 GiB while keeping the pow-law sample pool wide enough.

README updated for all of the above + image refs change from
plot_cfr0.5/0.8.png to plot.png.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Probe the over-provisioned end of the cache-sizing curve.  1.0 covers
the full unique-key footprint (every key fits, ideally near-zero
evictions in steady state).  1.5 over-provisions by 50% so we can see
whether extra cache headroom buys further hit-rate / latency.

Heads up: at ratio=1.5 with Adam the dual-backend HBM usage
(DynamicEmb cache ~38 GiB + FBGEMM cache ~39 GiB) is close to the
80 GiB H100 budget -- the [email protected] case may OOM and need follow-up.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…ata + plots

Picked 0.8 (just-under-footprint, frequent evictions in steady state)
and 1.0 (footprint exactly fits, near-zero evictions) as the canonical
pair.  This brackets the interesting region of the cache-sizing curve
without spending HBM on the saturated end (1.5 was 5x faster than 1.0
but already over-provisioned).

benchmark_results.json refreshed with H100 80GB SXM3 data (10 entries
total: gpu/no_caching/no_hbm x adam/sgd + [email protected]/1.0 x adam/sgd).
The cfr=0.8 entries come from the 2026-05-20 sweep (job 5301898) and
the cfr=1.0 entries from the caching-only follow-up (job 5301998);
both runs share the same code path (16M TestGpu cap + warm-cache
benchmark_train_eval), so the merge is consistent.

plots/ regenerated against the new JSON: one figure with 5 columns
(GPU, Caching cfr=0.8, Caching cfr=1.0, NoCaching, NoHBM) x 2 rows
(adam, sgd).  cfr=1.0 panel makes DynamicEmb's lookup-bound forward
path visibly competitive.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
The per-config cudaProfilerStart/Stop windows that benchmark_with_nsys
and benchmark_with_ncu already emit only get fully captured when the
external launcher uses --capture-range-end=repeat-shutdown.  Update
docs, helpers, and the print_ncu_command output so both single-config
(via -k) and multi-config (no filter) workflows are first-class.

benchmark.py
  * benchmark_with_nsys docstring spells out the two launcher
    conventions and what they capture.
  * benchmark_with_ncu now takes cfg and wraps its window in an outer
    NVTX range = cfg.label(), so an ncu report covering multiple
    configs back-to-back can be sliced by config in ncu-ui.
  * print_ncu_command emits two recipes -- single-config (with -k) and
    multi-config (no -k, --nvtx so the NVTX context is recorded).

README.md (Nsight Systems section)
  * Standardize on --capture-range-end=repeat-shutdown for both single
    and multi-config invocations (no behavior difference when there's
    just one window).
  * Switch the example commands to long-form flags throughout
    (--sample=none, --cpuctxsw=none, --trace=cuda,nvtx,osrt,mpi,ucx,
    --cuda-graph-trace=node, --cuda-flush-interval=100,
    --force-overwrite=true, --output=...).
  * Add a per-flag breakdown table so users can see what each one buys
    and which to drop on single-GPU runs (mpi/ucx).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Two parts that together replace nsys_breakdown's brittle kernel-name
substring matching with explicit NVTX-driven op attribution.

dynamicemb side (batched_dynamicemb_function.py): wrap every leaf
CUDA-launching call in `with torch.cuda.nvtx.range("op:<name>")`.
34 wrappers, 13 distinct op names:

    op:segmented_unique  (the old "segmented_unique" range, renamed
                          for consistency)
    op:cache_lookup, op:cache_insert_evict
    op:storage_find x3   (cache miss, hbm-direct _find_keys, generic)
    op:storage_insert x8 (5 cache-evict-writeback branches +
                          admit + hbm-direct insert + bwd writeback)
    op:load_from_flat x2 (cache evicted, fwd body)
    op:store_to_flat x3  (cache admit, cache new-init, hbm-direct init)
    op:initializer x4    (cache new-admit, hbm-direct admit,
                          generic, fwd body non-admit)
    op:flagged_compact x5 (admission x2, cache miss/admit, generic,
                           fwd body init)
    op:gather_embedding x2 (pooled / sequence)
    op:reduce_grads x2     (pooling / sequence)
    op:optimizer_update_fused / op:optimizer_update_padded
                          (the two backward-update paths)

These nest INSIDE the existing stage:* ranges (DynamicEmbeddingFunction
.forward / .backward, _prefetch_cache_path, _prefetch_hbm_direct_path,
_generic_forward_path, _apply_admission, etc.), giving nsys a clear
"stage > op" hierarchy without changing the stage-level NVTX.

Analysis side (benchmark/nsys_breakdown.py): for each kernel, prefer
the innermost op:* NVTX range as the category; fall back to the
KERNEL_NAME_PATTERNS substring matcher when op is absent (older
traces, or kernels launched outside the instrumented Python paths).
plot_breakdown auto-discovers any op:* names not in the stable
KERNEL_NAME_PATTERNS list and appends them to category_order with
their own colors + legend entries.

New sibling tool benchmark/nsys_sunburst.py: render a 4-ring
nested-donut (config → backend → phase → category) directly from
the breakdown CSV.  Includes a --demo mode with fake data; the
checked-in sunburst_demo.png shows the layout.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…-shutdown

Two related fixes uncovered by the first end-to-end nsys run.

nsys_breakdown.py: the JOIN against StringIds was missing every NVTX
range pushed from Python (torch.cuda.nvtx.range_push("xxx")), because
torch stores the name inline in NVTX_EVENTS.text instead of via
textId.  StringIds-only join silently dropped all op:* / dyn / trc /
forward / backward / cfg.label() ranges; only library NVTX (cub::*)
survived.  Switch to LEFT JOIN + COALESCE(s.value, n.text), which
keeps both flavors.  Without this fix breakdowns show everything as
(no-config) (no-backend) (no-phase) and op:* categories are invisible.

README: the cluster's nsys release rejects bare --capture-range-end=
repeat-shutdown and requires an explicit cycle count
(repeat-shutdown:N).  Bare 'repeat' is accepted but its default
behavior is a sampled capture -- with 10 cudaProfilerStart cycles
back-to-back, only 3 of them ended up on disk (cycles 1, 6, 10).
Update both nsys commands to use repeat-shutdown:10 and add a note
about sizing N >= the number of cycles.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
- plot_benchmark_results.py: merge per-optimizer panels into one
  axes per optimizer with a shared y-axis (panel headers on the top
  secondary x-axis, dotted separators between panel regions); drop
  the speedup figure + --speedup CLI; remove the dead _label_bars
  helper; refresh the top-of-file docstring.
- nsys_breakdown.py: attribute kernels via CPU launch time joined
  through CUPTI_ACTIVITY_KIND_RUNTIME so async backward kernels
  fall under their op:* range; when no op:* wraps a launch, use
  the kernel name directly instead of collapsing under
  "(unwrapped)".
- nsys_sunburst.py: 3-ring layout (phase / stage / op) with letter
  codes A,B,...,AA,AB,...; legend table below the chart listing
  op names + percentage of total iteration time; light pastel ring
  palette + golden-ratio hue jump for globally-unique leaf colors.
- README: document the full .nsys-rep -> per-config CSV -> sunburst
  PNG pipeline (op attribution, per-config loop capture, two-step
  python invocations); update the latency-plot layout description
  for the new merged shared-y figure; drop speedup references.
- plots: regenerate benchmark_bdet_plot.png with the new layout;
  add sample per-op breakdowns (breakdown_sgd_gpu.png,
  breakdown_adam_caching_cfr1.0.png); drop the no-longer-generated
  benchmark_bdet_speedup_plot.png; untrack sunburst_demo.png (now
  lives under local/, which is gitignored).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
- Introduce _GPU_TOTAL_CAP=16M / _CACHE_TOTAL_CAP=256M module constants
  representing the *suite total* capacity across all tables, and hand
  each table cap_total // nt rows at parametrize time.  Keeps DynamicEmb
  + TorchRec TBE + activations within the 80 GB H100 budget at nt=10
  (without this a 10-table TestGpu config would request ~240 GiB).
- Flip default _NUM_TABLES from [1] to [10] -- this makes the suite
  exercise the multi-table launch path by default.
- Compact cfg.label(): when all per-table caps are identical (the
  common case), collapse cap=1M_1M_..._1M to cap=1M.  Heterogeneous
  caps still expand losslessly to the per-table list.  T{nt} already
  carries the table count, so the collapsed form is unambiguous.
- Drop unused _CAP_PER_TABLE constant.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
- benchmark_results.json: 10 configs collected on H100 80 GB at
  nt=10 (per-table batch=104,857; total batch=1,048,570; cap_per_table
  scaled to TOTAL_CAP // nt to keep total HBM fixed); replaces the
  earlier nt=1 snapshot.
- plots/benchmark_bdet_plot.png: regenerated from the new JSON.
  Most notable shift vs the nt=1 plot: TestGpu now shows DynamicEmb
  slightly slower than TorchRec (multi-table CPU launch overhead from
  the per-table loops in the dyn path), while TestCaching cfr=1.0
  still keeps a clear DynamicEmb edge for Adam.
- plots/breakdown_sgd_gpu.png + breakdown_adam_caching_cfr1.0.png:
  re-captured under the same nt=10 setup and rendered via
  nsys_breakdown.py + nsys_sunburst.py.  Totals: sgd+gpu = 1.59 ms/iter
  (segmented_unique / gather_embedding / optimizer_update_fused
  dominate); adam+caching cfr=1.0 = 11.63 ms/iter (storage_insert /
  storage_find / cache_insert_evict / cache_lookup dominate; the Adam
  update itself is only ~5%).
- README: align all narrative with nt=10 -- parametrize axis list
  picks up num_tables and cache_footprint_ratio; Run configuration
  swaps batch_size/(single table) for num_tables=10 and per-table cap
  with the TOTAL_CAP // nt derivation; subtitle, sample label, and
  NVTX tree example use the new totalB1048570 / cap=1M / cap=25M
  values; breakdown bullets refresh to the new per-op percentages.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@shijieliu
shijieliu merged commit ccbdb10 into NVIDIA:main May 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants