Skip to content

feat(dynamicemb): fp8 table storage with stochastic rounding for row-wise Adagrad - #499

Closed
jyuan-sc wants to merge 3 commits into
NVIDIA:mainfrom
jyuan-sc:fea-dynamicemb-fp8-storage
Closed

jyuan-sc wants to merge 3 commits into
NVIDIA:mainfrom
jyuan-sc:fea-dynamicemb-fp8-storage

Conversation

@jyuan-sc

@jyuan-sc jyuan-sc commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

Draft / feature proposal. Opening this to discuss the approach, following CONTRIBUTING.md's ask to discuss new features first. It works and is tested, but on our model it costs a little accuracy (see Results). I'd like maintainers' input on whether fp8 storage belongs in dynamicemb in this form.

Description

Adds torch.float8_e4m3fn as a DynamicEmb table dtype (DynamicEmbTableOptions.embedding_dtype), so a table's values take 1 byte per element instead of 2 (fp16/bf16) or 4 (fp32). That halves value memory compared with fp16, which matters most for host-resident tables, where every lookup and update crosses PCIe.

Two design points:

  • Scaled e4m3. A table stores e4m3 codes of value * 256, which shifts e4m3's range to about [2^-17, 1.75]: exponent bias 15, the same format FBGEMM's FP8 comm codec uses. Trained embedding values usually sit around 1e-3 to 0.4. In plain float8_e4m3fn, about a third of those would be subnormal, and everything below 2^-9 would round to zero. On trained checkpoints from our model, the largest absolute value in any table was 0.36.
  • Stochastic rounding on every write. A row-wise Adagrad step is often smaller than half an e4m3 spacing, roughly 1/16 of |w|. Round-to-nearest discards such steps, and rows stop moving after a few dozen updates. Values already on the fp8 grid are written back exactly, including loads from an fp16 dump of an fp8 table.

Change

  • Kernel (src/utils.h, src/lookup_kernel.cuh, src/optimizer_kernel.cuh):
    • a 1-byte dyn_fp8_t storage type with float conversions;
    • Vec4T<dyn_fp8_t> keeps codes raw, so same-type copies move bytes unchanged. A value row's optimizer slot holds raw fp32 bytes, which must not round-trip through fp8.
    • Four codes move as one aligned 32-bit word, with byte fallback for unaligned or partial vectors. Without this, host-resident fp8 tables were slower than fp16, because each element read cost its own PCIe transaction.
  • Dispatch: a new DISPATCH_VALUE_DATATYPE_FUNCTION adds fp8 only to the value-type sites (lookup, initializer, flat load/store, row-wise Adagrad). Gradient and accumulator dispatch, and every other optimizer, are unchanged.
  • Optimizer (dynamicemb/optimizer.py): row-wise Adagrad keeps an fp32 accumulator in fp8 tables (four raw bytes in the 16-byte slot, building on fix(dynamicemb): keep rowwise Adagrad accumulator in fp32 for 16-bit tables #495). Any other optimizer, or a table-dtype accumulator, is rejected at table construction. Gradients reach the fused update as fp16.
  • Checkpoints and export (key_value_table.py, batched_dynamicemb_tables.py, batched_dynamicemb_compute_kernel.py):
    • fp8 tables dump and export embeddings as fp16, which holds every fp8 value exactly, so any loader can read them;
    • loads and delta replay convert back;
    • the placeholder parameters stay fp16.
  • Helpers (dynamicemb/utils.py): encode_table_values / decode_table_values / checkpoint_dtype, used at every Python boundary that converts table data.

Tests

New tests:

  • test/unit_tests/optimizer/test_fp8_table_storage.py (9 tests):
    • the accumulator is bit-identical to an fp32 table's, at vec4 and odd dims;
    • weights track an fp32 table, with mean error within 4 standard errors of zero;
    • rounding is unbiased between the two fp8 neighbours;
    • steps below half an fp8 spacing still accumulate, with drift within 5% of fp32's;
    • fp8 requires an fp32 accumulator.
  • test_batched_dynamic_embedding_tables_v2.py:
    • test_fp8_table_trains_like_fp32_table: 30 steps, pooled and sequence, in HBM, cache, and host storage;
    • test_fp8_table_dumps_lossless_fp16_and_round_trips: dump meta is fp16 and the redump is byte-identical.

Regression runs on an L4, sm_89:

suite result
test_batched_dynamic_embedding_tables_v2.py 394 passed, 4 skipped
test_rowwise_adagrad_state_precision.py 42 passed
unit_tests/ 2024 passed, which is the 9 new tests plus the same results as stock main at 6b983fc. The 7 test_lru_lfu.py failures and 319 errors (multi-GPU tests on a single GPU) occur identically on stock main.

The wheel builds for sm_80/89/90/100/120.

Results

Microbenchmark

Forward + backward with row-wise Adagrad: 3 tables (dims 64/32/896), batch 4096 × 8 ids, ms/step.

GPU values in ids fp32 fp16 fp8
L4 host resident 34.4 23.7 17.0
L4 host fresh (insert + evict) 39.8 27.5 20.9
RTX PRO 6000 host resident 9.16 6.05 4.46
RTX PRO 6000 host fresh 9.65 6.57 5.06
RTX PRO 6000 HBM resident / fresh 1.91 / 2.66 1.96 / 2.65 1.87 / 2.48

End-to-end

A multi-head ranking model with 16 DynamicEmb tables, row-wise sharded, values in host memory, on 2 nodes × 8 RTX PRO 6000.

  • Throughput: about +2.2% vs fp16 storage, with an otherwise identical config.
  • Quality, from a 20k-step run with held-out validation: ROC-AUC was −0.0004 to −0.0005 vs fp32/fp16 storage, about −0.05% relative.
    • That's lower on all 5 main heads, and on 19–20 of 21 heads overall.
    • Training loss sits about 0.0007 higher from early on.
    • It's small, near the size of fp32-vs-fp32 run noise, but consistent in sign. A longer comparison with a different lookup layout is running now; I'll post its result here.

Open questions for maintainers

  1. Is fp8 storage something you'd want in dynamicemb, given the small quality cost? It could be marked experimental.
  2. The fixed ×256 scale suits embeddings trained with the usual small initializers. Would you prefer a per-table scale, configurable in DynamicEmbTableOptions?
  3. Stochastic rounding currently draws its noise from a hash of clock64(), the thread index and the value, so fp8 training isn't bitwise deterministic. Would you prefer a seeded generator?

🤖 Generated with Claude Code

jyuan-sc and others added 3 commits October 8, 2026 12:48
…wise Adagrad

Add torch.float8_e4m3fn as a table dtype. An fp8 table stores e4m3 codes of
value * 256, which moves e4m3's range to [2^-17, 1.75] (exponent bias 15, the
format FBGEMM's FP8 comms use): trained embeddings sit around 1e-3..0.4, where
plain e4m3fn would leave a third of the values subnormal and flush everything
below 2^-9.

- kernel: dyn_fp8_t storage type with float conversions; every write rounds
  stochastically, because a row-wise Adagrad step is often below half an e4m3
  step and round-to-nearest would freeze rows after a few dozen updates. Values
  already on the grid are stored exactly. Same-type copies move raw bytes, so
  the fp32 accumulator packed in the state slot is never reinterpreted as fp8.
  A value-type dispatch adds fp8 to the lookup, initializer, load/store and
  row-wise Adagrad paths only; gradients and other optimizers are unchanged.
- optimizer: row-wise Adagrad keeps an fp32 accumulator in fp8 tables (four raw
  bytes in the 16-byte slot); every other optimizer, and a table-dtype
  accumulator, is rejected for fp8. Gradients reach the fused update as fp16.
- checkpoints: fp8 tables dump and export embeddings as fp16, which holds every
  fp8 value exactly, so any loader reads them; loads and delta replay convert
  back. Placeholder parameters stay fp16.

Tests: accumulator bit-identical to an fp32 table at odd widths; weights track
an fp32 table with zero mean error; rounding is unbiased; sub-step updates
accumulate; fp8 trains like fp32 through HBM, cache and host storage, pooled
and sequence; fp16 dump is lossless and round-trips byte for byte.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Jingping Yuan <[email protected]>
Load and store four fp8 codes, and the fp32 row-wise Adagrad accumulator in an
fp8 row, as one aligned 32-bit access instead of four byte accesses, falling
back to bytes for unaligned or partial vectors. Host-resident tables pay a PCIe
transaction per access, so the byte loop made fp8 slower than fp16 there.

L4, three tables (dims 64/32/896), batch 4096 x 8 ids, forward + backward with
row-wise Adagrad, ms/step:

  storage  fp32   fp16   fp8 before  fp8 after
  host     34.4   23.7   61.4        17.0
  HBM       8.7    9.0    8.1         8.1

The fp8 weight-tracking test now bounds the mean error by four standard
errors: the stochastic rounding noise is not seeded, so a fixed bound flaked.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Jingping Yuan <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Jingping Yuan <[email protected]>
@shijieliu

Copy link
Copy Markdown
Collaborator

hi @jyuan-sc

Is fp8 storage something you'd want in dynamicemb, given the small quality cost? It could be marked experimental.

Definitely we need it. And thanks for the contribution!

Is a fixed ×256 scale acceptable initially, with documented saturation at ±1.75, or should configurable per-table scaling be required?

I think fixed scaling is a good start and we can add more fp8 recipe in the future if needed.

Stochastic rounding currently draws its noise from a hash of clock64(), the thread index and the value, so fp8 training isn't bitwise deterministic. Would you prefer a seeded generator?

Dynamicemb itself is not bitwise deterministic so I think we dont need seeded generator for the first version. It can be added if we find it's necessary for debugging.

@shijieliu
shijieliu requested a review from jiashuy October 13, 2026 07:24
@jyuan-sc
jyuan-sc marked this pull request as ready for review October 21, 2026 16:06
@greptile-apps

greptile-apps Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 4/5

[Medium impact] The changes reach DynamicEmb table storage, training, and checkpoint workflows.

Fix the one-row fp8 checkpoint failure before merging.

Findings

  1. P1 One-row checkpoints fail ▶

Summary

Adds scaled fp8 storage with stochastic rounding for row-wise Adagrad.

  • DynamicEmb tables can store embeddings in scaled FP8.
  • Row-wise Adagrad keeps FP8 table updates moving with float32 state.
  • FP8 embeddings pass through exports and checkpoints as float16.

jyuan-sc explicitly identifies the fixed scale, nondeterministic rounding, and measured accuracy cost as intentional design choices or open questions. They are not reported as defects.

Runtime checks were unavailable because PyTorch is not installed in the review environment.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A[Embedding values] --> B[Scale by 256]
  B --> C[fp8 table bytes]
  C --> D[CUDA reads divide by 256]
  D --> E[Model output]
  E --> F[Row-wise Adagrad]
  F --> G[Stochastic rounding]
  G --> C
  C --> H[Decode to fp16 checkpoint]
  H --> B
Loading

Reviews (1) · Last reviewed commit: "style(dynamicemb): black-format the fp8 ..." · Reviewed by Greptile

Comment on lines +756 to +759
words_per_fp32 = 4 // DTYPE_NUM_BYTES[optim_states.dtype]
return _as_words(optim_states[:, :words_per_fp32].contiguous()).view(
torch.float32
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 One-row checkpoints fail

states_for_checkpoint raises for a one-row fp8 table whose embedding dimension is not divisible by four. With dimension 7, the accumulator slice starts at byte offset 7. PyTorch considers a single-row slice contiguous, so .contiguous() can leave that offset unchanged. The final .view(torch.float32) then rejects the unaligned offset, breaking full dumps and incremental exports.

Copy the accumulator bytes into fresh, aligned storage before viewing them as fp32. Add a one-row, odd-dimension test; the current odd-dimension tests use 64 rows, which forces a copy.

with torch.cuda.nvtx.range("op:optimizer_update_fused"):
optimizer.fused_update_for_flat_table(
unique_grads.to(ctx.emb_dtype),
unique_grads.to(gradient_dtype(ctx.emb_dtype)),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When the table's precision is set to FP8 and the gradients are cast to FP16, would it be better to use FP32 for the gradients instead?

@jiashuy

jiashuy commented Nov 11, 2026

Copy link
Copy Markdown
Collaborator

Add some fix in #548

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