Skip to content

On-device SparseCore/TensorCore recat for CW input dist - #4598

Open
kausv wants to merge 5 commits into
meta-pytorch:mainfrom
kausv:export-D111092421
Open

On-device SparseCore/TensorCore recat for CW input dist#4598
kausv wants to merge 5 commits into
meta-pytorch:mainfrom
kausv:export-D111092421

Conversation

@kausv

@kausv kausv commented Aug 21, 2026

Copy link
Copy Markdown
Contributor

Summary:
The post-all2all KJT reconstruction ("recat", permute_2D_sparse_data) has no TPU kernel, so on TPU it ran on CPU — the received id payload round-tripped device->CPU->device every step (~100MB/rank at 16-chip). This adds two on-device recat backends that keep the payload on-device and wires them into KJTAllToAllTensorsAwaitable._wait_impl behind TPU_RECAT_MODE:

  • SparseCore (recat_sc.py _sc_gather_1d): a Pallas SC gather. A scalar (width-1) gather returns zeros on the SC, so each id is padded to the 16-wide vector lane and column 0 is taken (16x bandwidth waste, inherent to a scalar permute on the SC).
  • TensorCore (_tc_gather_1d): a native width-1 index_select — no lane padding.

Both share one cached plan (the recat gather-index and permuted lengths are compile-time constant for fixed multi-hot), so per step only the value gather runs. dist_init is then called with recat=None (already permuted). Selectable via the benchmark --recat-mode {sc,tc,cpu}; default sc.

Perf finding (16-chip 2x2x4, per_chip_batch=4096, shrunk): recat engine does not matter — it is not the bottleneck.

| Recat engine | ms/step |
| CPU FBGEMM (round-trip) | 39,627 |
| SparseCore (on-device) | 39,598 |
| TensorCore (on-device) | 39,488 |

All within noise; the ~100MB round-trip is negligible against a ~39.6s step dominated by the unfused dense full-table gradient + per-element Adagrad + cross-host all2all. The real lever remains a fused embedding backward with a sparse (touched-rows-only) gradient + optimizer. EXPERIMENT_LOG.md updated with the multi-host table and this A/B.

Differential Revision: D111092421

kausv added 5 commits August 20, 2026 17:47
Summary:

Adds `train_perf_mlperf_tpu.py`, a steady-state training-throughput benchmark for the faithful MLPerf DLRM-v2 model on the torch_tpu stack (torch side only, no JAX). Same model as the GPU `mlperf_dlrm` runner in D110238830: torchrec `DLRM_DCN` (DCNv2, 3 layers / low-rank 512) over a multi-hot `EmbeddingBagCollection` (pool sum 214), `embedding_dim` 128, dense arch `[512,256,128]`, over arch `[1024,1024,512,256,1]`, per-element Adagrad. Cardinalities selectable via `--cardinality` (`shrunk` sum 30M / `canonical` sum 228M).

Embeddings are row-wise sharded on the `UNFUSED_TPU` compute kernel under `DistributedModelParallel` over `tpu_dist`; the dense DCN/MLP path runs on TPU via torch_tpu. Reports steady-state ms/step and K samples/s/chip, the same metric as the jte TPU side, so it is a direct third comparison point for the GPU vs TPU per-chip gap-closure work (B200 GPU vs v7x jte-JAX vs v7x torch_tpu).

Faithful-model caveat: the full MLPerf model uses pooled, multi-hot embeddings, which produce an uneven row-wise all2all. The torch_tpu RW path was first brought up for `EmbeddingCollection` / 1-hot / even-split only, so running this faithful config may require pooled-multi-hot / uneven-all2all support that is still landing.

Reviewed By: Ali-Tehrani, TroyGarden

Differential Revision: D110794150
Summary:

Switches the MLPerf DLRM-v2 torch_tpu train-perf benchmark from ROW_WISE to COLUMN_WISE sharding on the `UNFUSED_TPU` compute kernel, and adds the op registration the CW path needs.

Why column-wise: the `tpu_dist` backend implements only EVEN `all_to_all_single`. Row-wise bucketizes ids across ranks by row, which gives data-dependent, uneven per-partition counts. Column-wise reuses the table-wise input dist (`KJTAllToAll`, no bucketization) and splits each table's `embedding_dim` across all ranks, so every rank owns every feature and each destination receives exactly `per_chip_batch * sum(MULTI_HOT_SIZES)` ids -- an even all2all with no id dropping. It also drops the row padding row-wise needed, since every rank keeps every row.

- `experimental/torch_tpu/pallas/dispatcher.py`: register a TPU fallback for `fbgemm::permute_pooled_embs_auto_grad_split` that round-trips through CPU, matching the sparse-side permute fallbacks already in this file. The CW output dist uses this op to restore feature order after `PooledEmbeddingsAllToAll`; without a TPU impl the forward fails outright. Autograd flows through the `.to()` calls, so backward runs on CPU too.
- `benchmarks/train_dlrm_mlperf_tpu.py`: `row_wise` -> `column_wise(ranks=range(world_size))`; drop the `num_embeddings` round-up to a multiple of `world_size`; set `LOOKUP_MODE=v1_sc` so the forward gather runs on the SparseCore (the unfused backward stays on the TensorCore); move the KJT to device in `make_multihot_kjt` (the splits all2all inside `KJTAllToAll` runs on the KJT's device); assert `EMBEDDING_DIM % world_size == 0` and `(EMBEDDING_DIM // world_size) % 4 == 0`. That second condition matters: `_find_base_dim` rounds each column shard's width up to a multiple of 4, so without it CW places fewer, wider shards on a subset of ranks and the input all2all goes uneven again -- which caps this benchmark at `world_size <= 32` for dim 128.
- `distributed/sharding/BUCK`: point the `cw_sharding` target at `fbsource//third-party/pypi/torch:torch` instead of `//caffe2:_torch`.
- Two new correctness scripts, one for the pooled TPU kernel in isolation and one for the full CW sharded path, declared as `python_binary` in a new `fb/experiments/torchtpu/BUCK`. They are `python_binary` rather than `python_unittest` on purpose: each calls `dist.init_process_group(backend="tpu_dist")` and needs real SparseCore hardware, so `buck2 test` cannot run them and would collect zero cases and report a vacuous pass. They are launched on the pod with `./run_pod.sh run <file>.py`.

The kernel script pins `EMB_DIM = 16` deliberately: the SparseCore `v1_sc` gather silently returns zeros for most rows below the 16-lane vector width (dim 4 is wrong; 8, 16 and 32 are correct). 16 also matches the production shard width of dim 128 over 8 ranks.

Reviewed By: Ali-Tehrani

Differential Revision: D110794151
Summary:

Adds an optional `--profile-dir` flag to `train_perf_mlperf_tpu.py` that captures an xprof xplane trace of the timed steps via `jax.profiler.start_trace`/`stop_trace` (rank 0). `jax.profiler` records the TPU device timeline (SparseCore/TensorCore ops) through libtpu regardless of framework, so it works for the torch_tpu path. The trace is flushed with `_materialize()` before `stop_trace()` so pending TPU work lands in the window. Default is off (empty string), so existing runs are unaffected.

Usage: point it at `/workspace/traces` and pull with `run_pod.sh copy_traces`, then view with TensorBoard (`tensorboard --logdir ./traces`) or convert to a PerfDoctor URL with `share-trace.sh`.

Reviewed By: Ali-Tehrani

Differential Revision: D110786309
…orch#4597)

Summary:

Works around a torch_tpu multi-host runtime limitation that blocks the 16-chip (32-rank) run at model construction. `DistributedModelParallel.init_data_parallel` DDP-wraps the DLRM dense arch (bottom-MLP / DCN / over-arch, trained data-parallel), and `DistributedDataParallel.__init__` runs `_verify_param_shape_across_processes`. That check does a device->CPU transfer whose StableHLO lowering fails at multi-host: `RuntimeError: transfer to 'cpu' device failed with: cHLO => [StableHLO+Shape] => StableHLO failed`. It works at single-host (8 ranks) but not at 32 ranks.

The verify is only a sanity guard, and DMP's dense arch is deterministically replicated (identical shapes on every rank), so `_skip_ddp_shape_verify_on_tpu()` no-ops it — but only when `torch.tpu.is_available()`, and by patching the name in DDP's own module namespace (where `__init__` resolves it). Single-host and non-TPU backends are unaffected (the check already passes there). The durable fix belongs in torch_tpu's device->CPU lowering; this unblocks the multi-host benchmark so we can collect 16-chip perf numbers.

## 16-chip multi-host (2x2x4) result — per_chip_batch=4096

With this fix the 16-chip run completes end-to-end (world=32, 4 pods x 4 chips, 2x2x4 slice). Steady-state at per_chip_batch=4096, shrunk cardinality (sum 28.1M):

| Chips | Pods | Slice | Cardinality | Global batch | Steady ms/step | Global samples/s | Per-chip K/s |
| --- | --- | --- | --- | --- | --- | --- | --- |
| 16 | 4 | 2x2x4 | shrunk (28.1M) | 131,072 | 39,627 | 3,308 | 0.21 |

Per-chip K/s = global samples/s / 16 physical chips; the benchmark's printed per-rank figure is 0.1 K/rank across 32 ranks.

Reason for the slowness: the 16-chip step is ~4.8x slower than the single-host 4-chip step at the same per-chip batch (39,627 vs 8,243 ms). The unfused CW path already fails to amortize with batch (dense full-table gradient + dense per-element Adagrad every step, batch-independent cost); multi-host adds cross-host all-to-all over ICI plus the CW host round-trips (CPU feature-permute -> device -> a2a -> CPU recat -> device lookup, x26 features x32 ranks), and these dominate at 32 ranks. This is the opposite of the jte/SparseCore path (D110238827: ~66 ms, 62 K/chip at 16 chips) — the gap is the unfused torch_tpu kernel + host-side comms, not the hardware.

Stacked on the 16-chip JobSet diff (D110800376).

Reviewed By: Ali-Tehrani

Differential Revision: D110808820
Summary:
The post-all2all KJT reconstruction ("recat", `permute_2D_sparse_data`) has no TPU kernel, so on TPU it ran on CPU — the received id payload round-tripped device->CPU->device every step (~100MB/rank at 16-chip). This adds two on-device recat backends that keep the payload on-device and wires them into `KJTAllToAllTensorsAwaitable._wait_impl` behind `TPU_RECAT_MODE`:

- SparseCore (`recat_sc.py` `_sc_gather_1d`): a Pallas SC gather. A scalar (width-1) gather returns zeros on the SC, so each id is padded to the 16-wide vector lane and column 0 is taken (16x bandwidth waste, inherent to a scalar permute on the SC).
- TensorCore (`_tc_gather_1d`): a native width-1 `index_select` — no lane padding.

Both share one cached plan (the recat gather-index and permuted lengths are compile-time constant for fixed multi-hot), so per step only the value gather runs. `dist_init` is then called with `recat=None` (already permuted). Selectable via the benchmark `--recat-mode {sc,tc,cpu}`; default sc.

Perf finding (16-chip 2x2x4, per_chip_batch=4096, shrunk): recat engine does not matter — it is not the bottleneck.

| Recat engine | ms/step |
| CPU FBGEMM (round-trip) | 39,627 |
| SparseCore (on-device) | 39,598 |
| TensorCore (on-device) | 39,488 |

All within noise; the ~100MB round-trip is negligible against a ~39.6s step dominated by the unfused dense full-table gradient + per-element Adagrad + cross-host all2all. The real lever remains a fused embedding backward with a sparse (touched-rows-only) gradient + optimizer. EXPERIMENT_LOG.md updated with the multi-host table and this A/B.

Differential Revision: D111092421
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Aug 21, 2026
@meta-codesync

meta-codesync Bot commented Aug 21, 2026

Copy link
Copy Markdown
Contributor

@kausv has exported this pull request. If you are a Meta employee, you can view the originating Diff in D111092421.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. meta-exported

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant