Skip to content

Unit test of counter table's checkpoint. - #2

Merged
z52527 merged 1 commit into
z52527:fea-admission-strategyfrom
jiashuy:emb_admission
Dec 2, 2025
Merged

z52527 merged 1 commit into
z52527:fea-admission-strategyfrom
jiashuy:emb_admission

Conversation

@jiashuy

@jiashuy jiashuy commented Dec 1, 2025

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.

@jiashuy

jiashuy commented Dec 1, 2025

Copy link
Copy Markdown
Collaborator Author

CI

@z52527
z52527 merged commit b520a7f into z52527:fea-admission-strategy Dec 2, 2025
z52527 pushed a commit that referenced this pull request Apr 8, 2026
* refactor hash tale interface

* hash table support multiple table fusion

* cache, storage, prefetch refactor

* fix prefetch stale, remove insert fail in cache

* fix score

* format

* fix dump load score

* Fea dynamicemb table fusion (#2)

* Avoid outstanding keys overflow: decrement in the end of fwd

* Fix seq-emb'bw test;fix ref_counter in/decrement bug

1.Fix sequence embedding backward test:
issue:
 there are two forward and one backward calls in one iteration,
 which will increment the ref_counter twice and decement it once.
fix:
 switch to eval mode when only evaluate the model.
other method:
 move ref_counter's decrement to the end of fwd, but may unlock the key
early when there is an overlap of prefetch and backwad

2.Fix  ref_counter increment/decrement bug
issue:
  the arg slot_indices are begin from 0 for each table, but we need a
flat index.
  besides, the flat_indices in one iteration are unique as two key can't
share the same slot.
fix:
  make increment/decrement the slot_indices for each table using
table_ids.

* Route to the correct ref_counter table in insert kernel

* Update score in the end of prefetch;and only update it for STEP

* Fix expected score in test as we update score in prefetch

* Remove default value for table_ids in in/decrement_counter and make it not optional

* Return the correct score for get_score/incremental_dump when TIMESTAMP

* Fix incremental dump bug for multi-ranks case

* Remove incremental_dump from Storage

* Feature: table expansion

* fix(dynamicemb): DEFAULT backward persists only admitted rows; Hybrid insert keeps scores

- Track key_persisted in _generic_forward_path so backward storage.insert runs
  only for keys already resident; avoids inserting non-admitted keys.
- Backward insert uses preserve_existing=True (CONST score policy): embedding
  and optimizer buffers refresh without overwriting LFU/timestamp (or other)
  scores. Document this for HybridStorage.insert (HBM tier) and the autograd
  path.
- Refactor expand_if_need / table size collection and LFU find score alignment
  in key_value_table where applicable.
- Tests: assert_batched_dynamicemb_storage_class; --global-hbm-budget-scale
  for Hybrid/StorageMode DEFAULT in admission/lfu scripts; add
  test_hybrid_storage_export (+sh); wire unit_test.sh.

Made-with: Cursor

* dynamicemb: unify planner sizing; reuse TorchREC/FBGEMM types; drop custom OptimizerType

- Plan dynamic tables with get_sharded_table_shape; remove
  num_aligned_embedding_per_rank; derive max_capacity from bucket layout;
  align/clamp init_capacity to max_capacity.
- Merge _ContextOptions into DynamicEmbTableOptions; add get_table_value_bytes,
  get_sharded_table_shape, MAX_BUCKET_CAPACITY; use TorchREC BaseEmbeddingConfig
  and data_type_to_dtype where appropriate.
- Replace dynamicemb_extensions OptimizerType with FBGEMM EmbOptimType
  (TorchREC fused embedding stack); thread it through get_optimizer_state_dim,
  get_table_value_bytes, and planners/kernels.
- Update example, benchmarks, and tests for shared HBM/bucket sizing;
  fix apply_dmp eb_config loop; hybrid export test uses EmbeddingConfig helpers.
- Expand DynamicEmb_APIs.md; trim unused CUDA/utils in this change set.

Made-with: Cursor

* dynamicemb: expose allocated_bytes and extend VMM buffer tests

- Add VMMTensor/HostVMMTensor::allocated_bytes() and pybind; ExtendableBuffer.allocated_bytes() forwards to native backing size while num_bytes() stays logical.
- Expand test_vmm_tensor with deterministic extend/shape/alloc tests and HostExtendableBuffer coverage where supported.
- Stress test_vmm_buffer: correct doubling extend, optional full matrix via env, human-readable logical/allocated prints, per-iteration body timeout caught like OOM (pass), no fill_.

Made-with: Cursor

* dynamicemb: NO_EVICTION expansion, logical-row scores, expansion tests

- key_value_table: NO_EVICTION uses max_load_factor for expand triggers; no max_capacity cap; _expand_tables_impl uses KIM delta for explicit targets; find/store/export/load paths treat NO_EVICTION scores as logical flat rows; HybridStorage wiring; DEBUG_EMB_INITIALIZER_MOD constant.
- batched_dynamicemb_function: prefetch distinguishes NO_EVICTION backing (scores vs LFU); helper _storage_find_scores_are_logical_row_indices.
- batched_dynamicemb_tables: NO_EVICTION + caching guard aligned with Hybrid cache strategy.
- no_eviction_scores.cu: use global assign kernel path (SHM path disabled).
- test_batched_dynamic_embedding_tables_v2: table expansion tests, feature-major multi-table jagged layout, KIM size/capacity logging.
- test_embedding_dump_load: inline notes on sharded shape defaults.

Made-with: Cursor

* support fill_tables API for BatchedDynamicEmbeddingTablesV2 (NVIDIA#5)

* feat(dynamicemb): explicit num_buckets for bucketize; VMM and test fixes

- bucketize_keys: add num_buckets parameter and validate it; stop reading
  table_bucket_offsets[-1] on device (avoids implicit sync). Pybind and
  LinearBucketTable pass num_buckets_ / sum(per-table buckets) in tests.
- HostVMMTensor: robust getTotalPhysicalMemory via /proc/meminfo or sysconf;
  error if size cannot be determined; reject allocations larger than RAM;
  clearer errors when cudaHostRegister fallback fails after expand.
- extendable_tensor: normalize extend_shape to tuple so list vs tuple does
  not break trailing-dim matching.
- Tests: extend 2D with list extend_shape; caching flush uses small
  local_hbm_for_values so cache exists, documents metrics, second prefetch
  for hits; unit_test.sh runs hybrid storage export script and vmm tests.
- Fix mis-indented brace in vmm_tensor.cu.

Made-with: Cursor

* Clean up debug code

Made-with: Cursor

* feat(dynamicemb): default bucket width 128; persist row indices for backward

- Add DEFAULT_BUCKET_CAPACITY (128); use for DynamicEmbTableOptions.bucket_capacity
  and get_table_value_bytes(bucket_capacity=...) default so sizing matches untuned
  table options.
- DEFAULT prefetch forward: build persisted_unique_indices in _generic_forward_path
  (arange or flagged_compact) instead of saving key_persisted_mask; backward slices
  keys/tids/values by index (no second flagged_compact).
- benchmark_embedding_collection: size global_hbm via get_table_value_bytes with
  defaults; drop redundant get_sharded_table_shape / MAX_BUCKET_CAPACITY in planner
  options (implicit bucket_capacity=128).
- example get_planner: KVCounter capacity from num_embeddings // world_size; remove
  unused get_sharded_table_shape-derived row capacity.
- test_embedding_dump_load: simplify KVCounter capacity; keep MAX_BUCKET_CAPACITY
  for get_table_value_bytes and DynamicEmbTableOptions.bucket_capacity aligned.
- Remove unused MAX_BUCKET_CAPACITY import in benchmark.

Made-with: Cursor

---------

Co-authored-by: aleliu <[email protected]>
z52527 added a commit that referenced this pull request May 11, 2026
Addresses the second-pass follow-up findings in
examples/sid_gr/docs/beam_decode_branch_audit_for_cc.md (the section
written against 59ecff5).

Changes
=======

P2 #1 — Validator now checks all three pairs symmetrically
(benchmark_beam_decode.py)
* `_validate_compare_outputs` previously checked top-K overlap only for
  A vs B, while top-1 / log-prob delta were checked across all pairs.
  That meant C(jagged) lower-rank beams could drift past 70% overlap
  without the validator noticing as long as the top-1 SID and lp delta
  stayed close. Now top-K overlap is computed for A vs B, B vs C, and
  A vs C.
* The summary string now includes the three lp deltas and the three
  worst-case overlap percentages even on PASS, so a passing config
  reports the actual numbers instead of just a green tag.

P2 #2 — `--compare_kv_modes` raises by default on validation failure
(benchmark_beam_decode.py)
* Previously `run_compare_kv_modes()` printed validation failures at
  the bottom of the output and exited normally. Since RESULTS.md
  documents this command as the ground-truth reproduction, a
  copy-pasted timing table could absorb broken numbers without the
  reader noticing the validation block.
* Default behavior now: raise RuntimeError after the table if any
  config failed (non-zero exit, CI-friendly).
* New `--allow_validation_fail` flag opts back into the diagnostic
  behavior for sweeps where you want to see timings of a path that's
  known to drift.
* Docstring on `run_compare_kv_modes` documents the contract.

P3 — RESULTS.md prose label synced with the code
(benchmark/RESULTS.md)
* The benchmark CLI now prints `B_ms / C_ms` but RESULTS.md still
  said `C/B median = 0.951x` from the previous label scheme. Updated
  to match: `B_ms / C_ms median = 0.951x` with explicit "B (dense)
  takes 95.1% of C (jagged)'s wallclock" prose so the ratio direction
  is unambiguous.

Tests
=====

New unit test in test_beam_decode_generate.py:
* test_compare_kv_modes_default_raises_on_validation_failure —
  exercises both:
   1. `_validate_compare_outputs` actually flags injected mismatches
      (top-1 disagreement on sample 0).
   2. The post-sweep raise path raises in strict mode and stays
      silent under `--allow_validation_fail`.

Verified: 57/57 tests in test_beam_decode_generate.py pass.

`--compare_kv_modes --sweep_hist 64 --sweep_beam 10 --sweep_dtype bf16`
on H100 PCIe prints the new "top-K overlap >= 70% on all 3 pairs"
language and the validation block.

Out of scope (still deferred from earlier audit rounds, codex agrees
these are the highest-leverage perf items but they live in another
MR):
* Per-step KJT.from_lengths_sync overhead in the decode loop.
* torch.cat for beam KV accumulation -> preallocated tensor.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Signed-off-by: Runchu Zhao <[email protected]>
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