Repository navigation
fix segmented_unique_cuda: replace table_ids with segmented_range - #377
Conversation
|
/build |
Greptile SummaryThis PR replaces the per-element
Confidence Score: 5/5Safe 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 The core invariant — unique key count for table t never exceeds input key count for table t — guarantees the tighter No files require special attention. Important Files Changed
Sequence DiagramsequenceDiagram
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
Reviews (7): Last reviewed commit: "style(dynamicemb): apply pre-commit form..." | Re-trigger Greptile |
|
/build |
66bbcdc to
c01854b
Compare
|
/build |
|
❌ Pipeline #50492234 -- failed
Result: 7/14 jobs passed |
…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]>
…pand_table_ids Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…_ids_kernel Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
93808d8 to
ff54179
Compare
Refactor:
segmented_unique_cuda—table_ids→segmented_rangeBackground
segmented_unique_cudapreviously accepted a per-elementtable_idstensor (size = num_keys)identifying which embedding table each key belongs to. At every call site,
table_idswasproduced by
expand_table_ids_cudaexpanding a compactsegmented_rangeboundary tensor —an O(N log T) redundant step that also allocated an extra N-element tensor.
Goal: Change
segmented_unique_cudato acceptsegmented_range(shape[num_tables+1])directly, eliminating
expand_table_ids_cudaat all call sites and shrinking the internalpartitioned buffer from O(T×N) to O(N).
Call Site Analysis (before)
table_idsbatched_dynamicemb_function.pysegmented_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.pytorch.sort(torch.randint(...)).values— synthetic, keys not sorted by tableMemory Optimization
Before
After
segmented_range[t+1] - segmented_range[t]is the exact key count for table t, so thepartitioned buffer can be tightly allocated with table t's partition starting at
segmented_range[t]:Saves
(num_tables - 1) * num_keysallocation;partitioned_freq_countersbenefits equally.Implementation
Design Decisions
Internal
table_idsgeneration:expand_table_ids_kernel(segmented_range, table_ids, num_tables, num_keys)is called insidesegmented_unique_cudato produce a per-elementtable_idstensor. This keepssegmented_unique_kernelandadjust_output_indices_kernelunchanged (they still do O(1) per-element lookups).
segmented_rangeis additionally passedto
segmented_unique_kernelandcompact_keys_and_freq_kernelto compute partition offsets(
d_segmented_range[table_id] + local_idxinstead oftable_id * max_keys_per_table + local_idx).adjust_output_indices_kernelis not modified — it continues to use the internallygenerated
table_ids.Unifying
shard/embedding.py: Both call sites now useget_table_range(offsets, feature_offsets)to obtainsegmented_range, rather than manual indexing(
offsets[d_table_offset * local_batchsize]). The two approaches are mathematicallyequivalent;
get_table_rangeis 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ᵢ]wherefeature_offsets[t]isthe index of the first feature for table t and
feature_offsets[num_tables]is the totalfeature count.
Changes per File
src/unique_op.hsegmented_unique_cudasignature:table_ids→segmented_range(
keys[segmented_range[t]:segmented_range[t+1]]all belong to table t)src/unique_op.cuHost function
segmented_unique_cuda:numel() == num_tables+1,scalar_type() == kLong,is_contiguous(), same device as keysDYNAMICEMB_DEBUG=1(see below): checkssegmented_range[0]==0,segmented_range[num_tables]==num_keys, and monotonically non-decreasingexpand_table_ids_kernel(segmented_range, table_ids, num_tables, num_keys)to generate per-element
table_idspartitioned_unique_keys:{num_tables * num_keys}→{num_keys}partitioned_freq_counters: same reductionsegmented_unique_kernel:const int64_t *d_segmented_range; removedmax_keys_per_tabletable_id * max_keys_per_table + local_idx→
d_segmented_range[table_id] + local_idxcompact_keys_and_freq_kernel:const int64_t *d_segmented_range; removedmax_keys_per_tabletable_id * max_keys_per_table + local_idx→
d_segmented_range[table_id] + local_idxtable_idis derived from the outputtable_offsetsvia binary search;d_segmented_rangelocates the source partition — these two tensors have different semanticsadjust_output_indices_kernel: unchanged; still uses internally generatedtable_ids.bind_unique_op(Python binding):table_ids→segmented_range; C++ call updated accordinglybatched_dynamicemb_function.pysegmented_unique(): removedexpand_table_ids_cudacall; passessegment_rangedirectlyto
segmented_unique_cudaexpand_table_ids_cudaimport retained — still used at L719-725 and L871-877 to expandunique_indices_table_rangefor downstream lookupshard/embedding.py_dedup_indices():expand_table_ids_cuda(offsets, d_table_offset, ...)→get_table_range(offsets, d_table_offset)expand_table_ids_cuda, addedget_table_rangetest/test_unique_op.pymake_segmented_range(table_assignments, num_tables, device)helper:argsorts by table, computes
bincount+cumsumto producesegmented_range, and returnsboth the sort indices (for reordering keys) and
segmented_rangesegmented_unique_cudatests:keysreordered viasort_idxso thatkeys[segmented_range[t]:segmented_range[t+1]]belongs to table t;segmented_rangepassed instead of
table_idstest_expand_table_ids: updated to test new simplified interface (identity mapping only)src/expand_table_ids_torch_binding.cu(inference path)expand_table_ids_cudano longer supportstable_offsets_in_feature. The inference op(
INFERENCE_EMB::expand_table_ids) still needs it (called fromexportable_tables.pywithself.feature_offsets_). Interface unchanged; body adapted:expand_table_ids_inference_kernelin the binding file, supportingfeature_offsets+ arbitrarylocal_batch_sizeexpand_table_ids_cuda; fully self-containednum_tableskept as caller-supplied whentable_offsets_in_featureis present(matching original behavior)
Progress
unique_op.cu+unique_op.h+bind_unique_op)batched_dynamicemb_function.py)shard/embedding.py, unified viaget_table_range)test/test_unique_op.py)get_table_rangesecond-parameter semantics verified consistent across both call sitesDYNAMICEMB_DEBUG=1added: validatessegmented_rangeon CPU before launchexpand_table_ids_cudasimplified: removedtable_offsets_in_feature,local_batch_size,num_tables; inference binding adapted in-place with its own kernelDebug Environment Variables
DYNAMICEMB_DEBUG=1segmented_unique_cuda, copiessegmented_rangeto CPU and verifies:segmented_range[0]==0,segmented_range[num_tables]==num_keys, and the array is monotonically non-decreasing. Raises aTORCH_CHECKfailure with a descriptive message if any condition is violated. Incurs one D→H memcpy per call; intended for development/testing only.Usage:
Key File Paths
Checklist