Skip to content

fix segmented_unique_cuda: replace table_ids with segmented_range - #377

Merged
shijieliu merged 6 commits into
NVIDIA:mainfrom
jiashuy:fix_segmented_unique
May 8, 2026
Merged

shijieliu merged 6 commits into
NVIDIA:mainfrom
jiashuy:fix_segmented_unique

Conversation

@jiashuy

@jiashuy jiashuy commented May 6, 2026 •

Copy link
Copy Markdown
Collaborator

Refactor: segmented_unique_cuda — table_ids → segmented_range

Background

segmented_unique_cuda previously accepted a per-element table_ids tensor (size = num_keys)
identifying which embedding table each key belongs to. At every call site, table_ids was
produced by expand_table_ids_cuda expanding a compact segmented_range boundary tensor —
an O(N log T) redundant step that also allocated an extra N-element tensor.

Goal: Change segmented_unique_cuda to accept segmented_range (shape [num_tables+1])
directly, eliminating expand_table_ids_cuda at all call sites and shrinking the internal
partitioned buffer from O(T×N) to O(N).


Call Site Analysis (before)

File Location Source of table_ids
batched_dynamicemb_function.py segmented_unique() expand_table_ids_cuda(segment_range, None, num_tables, 1, num_keys)
shard/embedding.py _dedup_indices() expand_table_ids_cuda(offsets, d_table_offset, table_num, local_batchsize, num_elements)
test/test_unique_op.py all test functions torch.sort(torch.randint(...)).values — synthetic, keys not sorted by table

Memory Optimization

Before

const int64_t max_keys_per_table = num_keys;  // worst case: all keys in one table
at::Tensor partitioned_unique_keys = at::empty({num_tables * max_keys_per_table}, ...);
// actual allocation: num_tables * num_keys

After

segmented_range[t+1] - segmented_range[t] is the exact key count for table t, so the
partitioned buffer can be tightly allocated with table t's partition starting at
segmented_range[t]:

old layout: [table0: num_keys slots | table1: num_keys slots | ...]  → num_tables * num_keys
new layout: [table0: cnt0 slots | table1: cnt1 slots | ...]          → num_keys

Saves (num_tables - 1) * num_keys allocation; partitioned_freq_counters benefits equally.


Implementation

Design Decisions

Internal table_ids generation: expand_table_ids_kernel(segmented_range, table_ids, num_tables, num_keys) is called inside segmented_unique_cuda to produce a per-element
table_ids tensor. This keeps segmented_unique_kernel and adjust_output_indices_kernel
unchanged (they still do O(1) per-element lookups). segmented_range is additionally passed
to segmented_unique_kernel and compact_keys_and_freq_kernel to compute partition offsets
(d_segmented_range[table_id] + local_idx instead of table_id * max_keys_per_table + local_idx).

adjust_output_indices_kernel is not modified — it continues to use the internally
generated table_ids.

Unifying shard/embedding.py: Both call sites now use get_table_range(offsets, feature_offsets) to obtain segmented_range, rather than manual indexing
(offsets[d_table_offset * local_batchsize]). The two approaches are mathematically
equivalent; get_table_range is preferred for consistency and correct dtype handling.

Second-parameter semantics of get_table_range: confirmed identical at both call sites —
a cumulative feature-offset array [0, f₀, f₀+f₁, ..., Σfᵢ] where feature_offsets[t] is
the index of the first feature for table t and feature_offsets[num_tables] is the total
feature count.

Changes per File

src/unique_op.h

  • segmented_unique_cuda signature: table_ids → segmented_range
  • Updated doc comment: keys must be pre-sorted by table
    (keys[segmented_range[t]:segmented_range[t+1]] all belong to table t)

src/unique_op.cu

Host function segmented_unique_cuda:

  • Added validation: numel() == num_tables+1, scalar_type() == kLong,
    is_contiguous(), same device as keys
  • Debug validation via DYNAMICEMB_DEBUG=1 (see below): checks segmented_range[0]==0,
    segmented_range[num_tables]==num_keys, and monotonically non-decreasing
  • Internally calls expand_table_ids_kernel(segmented_range, table_ids, num_tables, num_keys)
    to generate per-element table_ids
  • partitioned_unique_keys: {num_tables * num_keys} → {num_keys}
  • partitioned_freq_counters: same reduction

segmented_unique_kernel:

  • New parameter const int64_t *d_segmented_range; removed max_keys_per_table
  • Write position: table_id * max_keys_per_table + local_idx
    → d_segmented_range[table_id] + local_idx

compact_keys_and_freq_kernel:

  • New parameter const int64_t *d_segmented_range; removed max_keys_per_table
  • Source position: table_id * max_keys_per_table + local_idx
    → d_segmented_range[table_id] + local_idx
  • Note: table_id is derived from the output table_offsets via binary search;
    d_segmented_range locates the source partition — these two tensors have different semantics

adjust_output_indices_kernel: unchanged; still uses internally generated table_ids.

bind_unique_op (Python binding):

  • Lambda parameter renamed table_ids → segmented_range; C++ call updated accordingly
  • Docstring updated to reflect new interface

batched_dynamicemb_function.py

  • segmented_unique(): removed expand_table_ids_cuda call; passes segment_range directly
    to segmented_unique_cuda
  • expand_table_ids_cuda import retained — still used at L719-725 and L871-877 to expand
    unique_indices_table_range for downstream lookup

shard/embedding.py

  • _dedup_indices(): expand_table_ids_cuda(offsets, d_table_offset, ...) →
    get_table_range(offsets, d_table_offset)
  • Imports: removed expand_table_ids_cuda, added get_table_range

test/test_unique_op.py

  • Added make_segmented_range(table_assignments, num_tables, device) helper:
    argsorts by table, computes bincount + cumsum to produce segmented_range, and returns
    both the sort indices (for reordering keys) and segmented_range
  • All segmented_unique_cuda tests: keys reordered via sort_idx so that
    keys[segmented_range[t]:segmented_range[t+1]] belongs to table t; segmented_range
    passed instead of table_ids
  • test_expand_table_ids: updated to test new simplified interface (identity mapping only)

src/expand_table_ids_torch_binding.cu (inference path)

expand_table_ids_cuda no longer supports table_offsets_in_feature. The inference op
(INFERENCE_EMB::expand_table_ids) still needs it (called from exportable_tables.py with
self.feature_offsets_). Interface unchanged; body adapted:

  • Added expand_table_ids_inference_kernel in the binding file, supporting
    feature_offsets + arbitrary local_batch_size
  • No longer calls expand_table_ids_cuda; fully self-contained
  • num_tables kept as caller-supplied when table_offsets_in_feature is present
    (matching original behavior)

Progress

  • Background analysis and call-site survey
  • CUDA kernel changes (unique_op.cu + unique_op.h + bind_unique_op)
  • Python call-site update (batched_dynamicemb_function.py)
  • Python call-site update (shard/embedding.py, unified via get_table_range)
  • Test file update (test/test_unique_op.py)
  • get_table_range second-parameter semantics verified consistent across both call sites
  • Debug env var DYNAMICEMB_DEBUG=1 added: validates segmented_range on CPU before launch
  • expand_table_ids_cuda simplified: removed table_offsets_in_feature, local_batch_size,
    num_tables; inference binding adapted in-place with its own kernel
  • Build verification
  • Test run

Debug Environment Variables

Variable Effect
DYNAMICEMB_DEBUG=1 In segmented_unique_cuda, copies segmented_range to CPU and verifies: segmented_range[0]==0, segmented_range[num_tables]==num_keys, and the array is monotonically non-decreasing. Raises a TORCH_CHECK failure with a descriptive message if any condition is violated. Incurs one D→H memcpy per call; intended for development/testing only.

Usage:

DYNAMICEMB_DEBUG=1 python test/test_unique_op.py

Key File Paths

corelib/dynamicemb/src/unique_op.cu
corelib/dynamicemb/src/unique_op.h
corelib/dynamicemb/src/table_operation/expand_table_ids_torch_binding.cu
corelib/dynamicemb/dynamicemb/batched_dynamicemb_function.py
corelib/dynamicemb/dynamicemb/shard/embedding.py
corelib/dynamicemb/test/test_unique_op.py

Checklist

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

@jiashuy jiashuy changed the title refactor(dynamicemb): replace table_ids with segmented_range in segme… fix segmented_unique_cuda: replace table_ids with segmented_range May 6, 2026
@jiashuy

jiashuy commented May 6, 2026

Copy link
Copy Markdown
Collaborator Author

/build

@jiashuy

jiashuy commented May 6, 2026

Copy link
Copy Markdown
Collaborator Author

CI

@greptile-apps

greptile-apps Bot commented May 6, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR replaces the per-element table_ids tensor accepted by segmented_unique_cuda with a compact segmented_range boundary tensor (shape [num_tables+1]), eliminating a redundant expand_table_ids_cuda call at every call site and shrinking the internal partitioned buffer from O(T×N) to O(N).

  • CUDA kernels (segmented_unique_kernel, compact_keys_and_freq_kernel): max_keys_per_table stride replaced with d_segmented_range[table_id] offset; table_ids are now generated internally via expand_table_ids_kernel on the same stream. Buffer reduction (partitioned_unique_keys, partitioned_freq_counters) from num_tables × num_keys → num_keys.
  • Python call sites (batched_dynamicemb_function.py, shard/embedding.py): expand_table_ids_cuda pre-processing removed; call sites updated to pass segment_range / get_table_range(...) directly.
  • Inference path (expand_table_ids_torch_binding.cu): INFERENCE_EMB::expand_table_ids self-contained with a new kernel; public interface unchanged. The local_batch_size > 0 guard is correctly placed before the if/else branch.

Confidence Score: 5/5

Safe to merge — the memory-layout refactor is internally consistent, all call sites within the repo are updated, and both the partitioned write path and compact read path agree on d_segmented_range[table_id] as the per-table base offset.

The core invariant — unique key count for table t never exceeds input key count for table t — guarantees the tighter num_keys-sized partitioned buffer cannot be overrun. The segmented_unique_kernel → compact_keys_and_freq_kernel data flow is coherent: both use d_segmented_range[table_id] + local_idx with matching index semantics. All Python call sites have been updated to the new 2- or 3-argument forms and the inference binding retains its original external interface. No data-correctness regressions were identified.

No files require special attention. unique_op.cu carries the most logic but the kernel changes are straightforward index-arithmetic substitutions that have been verified coherent.

Important Files Changed

Filename Overview
corelib/dynamicemb/src/unique_op.cu Core refactor: segmented_unique_cuda signature changed from table_ids to segmented_range; buffers shrunk from O(T×N) to O(N); expand_table_ids_cuda simplified to identity mapping; CUDA kernels updated to use d_segmented_range offsets. Logic appears correct; partitioned buffer indexing is coherent across segmented_unique_kernel and compact_keys_and_freq_kernel.
corelib/dynamicemb/src/table_operation/expand_table_ids_torch_binding.cu Inference path now self-contained with its own expand_table_ids_inference_kernel; local_batch_size > 0 guard is correctly placed before the if/else branch. External interface is unchanged.
corelib/dynamicemb/dynamicemb/batched_dynamicemb_function.py Removed redundant expand_table_ids_cuda call in segmented_unique() and updated remaining two call sites to the new 2-argument form. expand_table_ids_cuda import retained for downstream lookup use.
corelib/dynamicemb/dynamicemb/shard/embedding.py Replaced expand_table_ids_cuda with get_table_range in _dedup_indices(); import updated accordingly. The segmented_range produced by get_table_range is passed directly to segmented_unique_cuda.
corelib/dynamicemb/test/test_unique_op.py All tests updated: make_segmented_range helper added, keys reordered to satisfy the per-table sort contract, segmented_range passed in lieu of table_ids. test_expand_table_ids simplified to the identity-mapping use case.

Sequence Diagram

sequenceDiagram
    participant Caller as Python Caller
    participant SU as segmented_unique_cuda
    participant EK as expand_table_ids_kernel
    participant SUK as segmented_unique_kernel
    participant CK as compact_keys_and_freq_kernel
    participant AK as adjust_output_indices_kernel

    Caller->>SU: keys, segmented_range[T+1], num_tables
    Note over SU: Validate segmented_range shape,\ndtype, device, contiguity
    SU->>EK: segmented_range → table_ids[N]
    EK-->>SU: table_ids (per-element, binary search)
    Note over SU: Alloc partitioned_unique_keys[N]\n(was N×T before)
    SU->>SUK: keys, table_ids, segmented_range
    Note over SUK: For each key: hash lookup,\nwrite unique at segmented_range[t]+local_idx
    SUK-->>SU: partitioned_unique_keys, table_counters
    Note over SU: table_offsets = cumsum(table_counters)
    SU->>CK: partitioned_unique_keys, segmented_range, table_offsets
    Note over CK: For each output idx: binary search\ntable_offsets → table_id,\nread partitioned[segmented_range[t]+local_idx]
    CK-->>SU: unique_keys (compacted)
    SU->>AK: output_indices, table_ids, table_offsets
    AK-->>SU: output_indices (global)
    SU-->>Caller: num_uniques, unique_keys, output_indices,\ntable_offsets, freq_counters
Loading

Reviews (7): Last reviewed commit: "style(dynamicemb): apply pre-commit form..." | Re-trigger Greptile

Comment thread corelib/dynamicemb/src/unique_op.cu Resolved
Comment thread corelib/dynamicemb/src/unique_op.cu Resolved
@jiashuy

jiashuy commented May 6, 2026

Copy link
Copy Markdown
Collaborator Author

/build

@jiashuy

jiashuy commented May 6, 2026

Copy link
Copy Markdown
Collaborator Author

CI

@jiashuy
jiashuy requested a review from shijieliu May 6, 2026 07:23
@jiashuy
jiashuy force-pushed the fix_segmented_unique branch from 66bbcdc to c01854b Compare May 6, 2026 07:44
@jiashuy

jiashuy commented May 7, 2026

Copy link
Copy Markdown
Collaborator Author

/build

@JacoCheung

JacoCheung commented May 7, 2026 •

Copy link
Copy Markdown
Collaborator

❌ Pipeline #50492234 -- failed

Job Status Log
pre_check ❌ failed view
train_build ✅ success view
inference_build ❌ failed view
tritonserver_build ✅ success view
build_whl ✅ success view
dynamicemb_test_fwd_bwd_8gpus ❌ failed view
dynamicemb_test_load_dump_8gpus ❌ failed view
unit_test_1gpu_a100 ✅ success view
unit_test_1gpu_h100 ✅ success view
unit_test_4gpu ✅ success view
unit_test_tp_4gpu ❌ failed view
L20_unit_test_1gpu ✅ success view
inference_unit_test_1gpu ❌ failed view
inference_test_1gpu ❌ failed view

Result: 7/14 jobs passed

View full pipeline

Comment thread corelib/dynamicemb/src/unique_op.cu Resolved
Comment thread corelib/dynamicemb/src/unique_op.h Resolved
jiashuy and others added 6 commits May 8, 2026 09:48
…nted_unique_cuda

Change the interface of segmented_unique_cuda to accept segmented_range
(shape: [num_tables+1]) instead of a per-element table_ids tensor, requiring
keys to be pre-sorted by table. This eliminates the O(N log T) expand_table_ids
pre-processing step at all call sites and reduces the partitioned buffer
allocation from O(num_tables * num_keys) to O(num_keys).

Key changes:
- unique_op.h/cu: new signature takes segmented_range; table_ids generated
  internally via expand_table_ids_kernel; partitioned_unique_keys and
  partitioned_freq_counters sized to num_keys instead of num_tables*num_keys;
  segmented_unique_kernel and compact_keys_and_freq_kernel use segmented_range
  as per-table partition offsets; add contiguous/dtype/device checks
- batched_dynamicemb_function.py: segmented_unique() drops expand_table_ids_cuda
  call, passes segment_range directly to segmented_unique_cuda
- shard/embedding.py: _dedup_indices() replaces expand_table_ids_cuda with
  get_table_range(offsets, d_table_offset), unifying both call sites
- test_unique_op.py: add make_segmented_range helper; all segmented_unique
  tests sort keys by table and pass segmented_range instead of table_ids

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

When DYNAMICEMB_DEBUG is set, segmented_unique_cuda copies segmented_range
to CPU and verifies: starts at 0, ends at num_keys, monotonically
non-decreasing. Also consolidates all env var docs into a new
"Environment Variables" section in DynamicEmb_APIs.md.

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

Remove table_offsets_in_feature, local_batch_size, and num_tables from
expand_table_ids_cuda; num_tables is now derived from offsets.size(0)-1.
The inference binding (expand_table_ids_torch_binding.cu) retains the
full generality via its own kernel, keeping the TorchScript op interface
unchanged. All training call sites updated to the simplified signature.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@shijieliu
shijieliu force-pushed the fix_segmented_unique branch from 93808d8 to ff54179 Compare May 8, 2026 01:48
@shijieliu
shijieliu merged commit 0b11ba5 into NVIDIA:main May 8, 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.

3 participants