NVIDIA RecSys Examples

repository·main·Indexed 43 days ago

https://github.com/nvidia/recsys-examples

A suite of optimized models, libraries, and automated tools for building and deploying high-performance recommendation systems, covering ranking, retrieval, and generative architectures. Includes the dynamicemb library for distributed dynamic embedding storage, featuring benchmarks for EmbeddingCollection and BatchedDynamicEmbeddingTablesV2, and integration with Nsight Systems and Nsight Compute for performance profiling.

Tokens
87.4K
Snippets
175
Records
307
Agent score
56%

What's inside NVIDIA RecSys Examples

  1. Overview of NVIDIA RecSys Examples

    main

    NVIDIA RecSys Examples is a collection of optimized recommender models and components designed for large-scale ranking, retrieval, and generative recommendation tasks. The project is structured into three primary functional areas:

    1. Examples: High-level implementations for specific model architectures:
      • HSTU (Hierarchical Sequential Transformer Unit): For large-scale ranking and retrieval training (using TorchRec, Megatron-Core, and DynamicEmb) and optimized inference (using Triton Inference Server, CUDA graphs, and C++ deployment).
      • Semantic ID (SID-GR) Generative Recommender: For training and retrieval using hierarchical semantic-ID prediction and Megatron-Core decoder support.
      • SID-GR Inference: Specialized serving for long-context, short-decode, and large-beam scenarios using ContextKV/BeamKV/BeamPath abstractions.
    2. Standalone GPU Libraries: Core optimized components:
      • DynamicEmb: Model-parallel dynamic embedding tables with GPU/host storage and TorchRec integration.
      • RecSys KVCache Manager: User-ID-based KV-cache reuse for generative recommender inference.
      • Beam search decode attention: Specialized kernels for SID-GR KV-cache generation.
    3. Agentic Performance Optimization:
      • Talos: An automated toolkit that uses coding agents (like Claude Code) to profile, rewrite, and verify PyTorch model hotspots for performance gains without human intervention.
  2. Overview of DynamicEmb

    main

    DynamicEmb is a Python package designed for model-parallel dynamic embedding tables and embedding lookup functionalities for TorchREC. It targets sparse training in recommendation systems by using a GPU-optimized scored hash table backend. This backend stores key-value (feature-embedding) pairs in both GPU high-bandwidth memory (HBM) and host memory.

    Key features include:

    • Dynamic Embedding Table Support: Uses hash tables to allow optimal utilization of GPU and host memory. Unlike static tables, hash tables can accept any indices type.
    • TorchREC Integration: Inherits the TorchREC API, allowing users to easily modify existing recommendation system models to use dynamic embedding tables.
    • Pooling Mode Support: Supports SUM, MEAN, and NONE (sequence) pooling modes with fused CUDA kernels. It also supports mixed-D (different embedding dimensions).
    • Optimizer Support: Supports EXACT_SGD, ADAM, EXACT_ADAGRAD, and EXACT_ROWWISE_ADAGRAD.
    • Parallel I/O: Supports automatically parallel dump/load of embedding weights.
  3. Overview of HSTU Training Benchmarks

    main

    The HSTU Training Benchmark provides three distinct benchmarking modes through a unified launch pipeline. All scripts in scripts/ accept a --benchmark-type flag to dispatch to the correct Python entry point.

    Available Benchmark Types

    --benchmark-typePython entryDefault experiment listShapeDescription
    e2etraining/pretrain_gr_ranking.pyexperiments.txtMulti-node (default 2×8 GPUs)Measures end-to-end MFU as optimizations are enabled.
    hstu-layerscripts/hstu_layer_benchmark.pylayer_experiments.txtSingle GPUBenchmarks individual HSTU layers.
    hstu-attn-kernelscripts/hstu_attn_kernel_benchmark.pykernel_experiments.txtSingle GPUBenchmarks the CUTLASS-based HSTU attention kernel.
  4. HSTU End-to-End Training Performance Benchmark Overview

    main

    The HSTU end-to-end training benchmark is a series of progressive experiments designed to quantify the performance contribution of various optimizations to training throughput (Model Flops Utilization - MFU). Each experiment builds upon the previous one, allowing for a cumulative measurement of speedups.

    Optimization Progression

    #OptimizationDescription
    0BaselineTriton attention, DynamicEmb without caching, no shuffler, DP-only
    1Workload-Balanced ShufflerRedistributes variable-length sequences across GPUs to balance attention FLOPs and eliminate idle time caused by skewed sequence lengths.
    2CUTLASS AttentionReplaces Triton attention with a hand-tuned CUTLASS kernel optimized for HSTU's causal+context mask.
    3DynamicEmb CachingCaches hot DynamicEmb rows in GPU HBM while keeping the full table in host memory.
    4Hash-RoundRobin ShardingUses row-wise hash_roundrobin placement for DynamicEmb tables to distribute IDs evenly across ranks.
    5Prefetch PipelineEnables a prefetch pipeline on top of caching and Hash-RoundRobin sharding.
  5. Benchmark BatchedDynamicEmbeddingTables

    main

    This benchmark measures the forward, backward, and evaluation overhead of BatchedDynamicEmbeddingTablesV2 compared to the TorchRec/FBGEMM SplitTableBatchedEmbeddingBagsCodegen baseline on a single GPU. It is implemented as a pytest suite (benchmark_batched_dynamicemb_tables.py) wrapped by a shell launcher (benchmark_batched_dynamicemb_tables.sh).

    Available Test Suites

    Suitegpu_ratiocachingNotes
    TestGpu1.0FalseFull table in HBM
    TestCaching0.1True10% HBM as LRU cache
    TestNoCaching0.1False10% HBM in HybridStorage
    TestNoHbm0.0FalsePure UVM

    Default Configuration

    • num_iterations: 100
    • embedding_dim: 128
    • feature_distribution: "pow-law" (alpha=1.05)
    • emb_precision: fp32
    • optimizer: Adam or SGD (learning_rate=0.1, eps=1e-8)
    bash ./benchmark/benchmark_batched_dynamicemb_tables.sh
  6. HSTU Inference Benchmark Paths

    main

    The HSTU (Hierarchical Sequential Transformer Unit) ranking inference benchmarks cover several implementation paths for evaluating performance across different runtimes and backends. These include:

    • Triton Python-backend client: Used for testing the standard Python backend in Triton Server.
    • PyTorch Export (No Cache): Uses export_inference_gr_ranking.py to export the model and compare Python runtime against native C++.
    • PyTorch Export (With KV Cache): Uses export_inference_gr_ranking_kvcache.py to evaluate performance with KV-cache enabled.
    • C++ Torch Replay: Native C++ execution of exported models, both with and without KV cache.
    • Triton AOTI Deployment: Uses PyTorch AOTInductor (AOTI) for optimized deployment via Triton Server.
    • Triton AOTI Request Replay: Uses test_tritonserver_aoti_hstu_model.py to replay requests against an AOTI-enabled Triton server.
  7. HSTU AOTI Inference Workflow Overview

    main

    This workflow describes how to export and run the HSTU ranking inference model using PyTorch AOTInductor (AOTI), native C++ replay, a FlexKV-backed KV cache, and Triton Server.

    The workflow consists of five stages:

    1. Build: Compile required custom operators and runtime libraries.
    2. Export: Use torch.export and AOTInductor to export the HSTU ranking model.
    3. Runtime Service: Start the FlexKV-backed KV-cache runtime service.
    4. Validate: Use native C++ to validate exported artifacts and replay tensors.
    5. Serve: Deploy and test the exported KV-cache AOTI model using Triton Server.

    For detailed deployment steps, refer to the guide_to_hstu_aoti_inference_setup.md.

  8. What is SID-GR Inference and when to use it

    main

    SID-GR (Semantic ID based Generative Recommender) Inference is a specialized runtime optimized for a specific recommendation and search workload: long context + short decode + large beam width.

    Unlike general-purpose LLM serving frameworks (like vLLM or TensorRT-LLM) which are optimized for many user requests and long decoding, SID-GR is designed for scenarios where:

    • The model autoregressively generates short semantic ID sequences (e.g., cluster ID tuples).
    • User history (context) is long.
    • Large beam widths (e.g., 128 or 256) are required to ensure result diversity.
    • Many beams share the same request-level context.

    It provides a compact framework that maintains SID-GR native abstractions while selectively reusing mature serving ideas like continuous batching and paged KV.

  9. SID-GR Inference Core Design Abstractions

    main

    The SID-GR runtime uses specialized KV (Key-Value) abstractions to handle the unique requirements of semantic ID generation:

    • ContextKV: Stores the long, shared user or candidate context once per request. It uses a dense, contiguous layout to support kernel-friendly decode attention and stable pool slices for CUDA graph replay.
    • BeamKV: Stores the short decode history for each individual beam.
    • BeamPath: Records the logical parent-child relationships between beams.
    • gr-decode_atten: A specialized decode attention backend that directly receives ContextKV + BeamKV + BeamPath to efficiently process shared context across multiple beams.
    • Batching Unit: The scheduler groups requests by decode step, beam width, and context shape, using a unit of request x active beams.
  10. Understand the .torch_optimize/ workspace layout

    main

    The .torch_optimize/ directory is a run-local workspace created inside the code root being optimized. It serves as the shared state for the three primary roles in the optimization process: the Main Loop Agent, the Optimizer, and the Judge.

    Each optimization run follows a hierarchical structure of loops and rounds:

    1. Loop Level (loop_<n>)

    A loop represents a single cycle from a specific baseline profile until a PASS verdict is achieved. Each loop contains:

    • loop_baseline.patch: A git checkpoint of the code at the start of the loop (written by Main Loop Agent).
    • loop.patch: The cumulative optimization patch containing all kept optimizations (written by Optimizer).
    • loop_baseline.nsys-rep: The initial Nsys trace (written by Main Loop Agent).
    • <torch-perf-analysis outputs>: Performance profiling data like basics.json (written by Main Loop Agent).
    • loop_baseline_analysis.md: Performance analysis and hotspot identification (written by Main Loop Agent).

    2. Round Level (round_<k>)

    Within each loop, multiple rounds may occur if the Judge issues an ITERATE verdict. Each round contains:

    • <nsys-rep + torch-perf-analysis outputs>: Profiling data for the specific change (written by Optimizer or Judge).
    • verification.json: Real-input parity and end-to-end performance measurements (written by Optimizer).
    • worklog.md: The Optimizer's log of activities.
    • report.md: The Optimizer's report.
    • verdict.md: The final decision from the Judge (e.g., PASS, ITERATE).
  11. Understand torch-function utilisation and CPU-side costs

    main

    The torch_function_util.json artifact (found in step_<N>/cpu_thread_<i>/) measures the fraction of a CPU thread's wall time spent inside talos:: ranges (i.e., inside a torch.* call). This is a C++ / dispatch-utilisation metric.

    Interpreting util values:

    • Low util (Gaps = 1 - util): Indicates Python overhead. The thread is spending time in the Python interpreter (building argument lists, control flow, etc.) between torch ops.
    • High util: Indicates the thread is dispatch-bound. The host is busy with C++ costs (operator resolution, autograd graph building, and kernel launching) to feed the GPU. This is host-side work that merely issues GPU work.

    Note on role: other: Threads with this role run no tracked torch ops (util $\approx$ 0) but are busy launching raw CUDA (communication, copy, or CUDA-graphs).

  12. Format of HSTU Experiment Lists

    main

    Experiment lists (e.g., experiments.txt, layer_experiments.txt, kernel_experiments.txt) follow a simple format: one experiment per line.

    Format: exp_name,<args>

    Note that <args> must match the expected input for the specific --benchmark-type:

    • e2e: Gin options for generate_gin_config.py.
    • hstu-layer: CLI arguments for hstu_layer_benchmark.py run.
    • hstu-attn-kernel: CLI arguments for hstu_attn_kernel_benchmark.py.

    Comments can be added using #.