Skip to content

nki(histogramming): NKI (Trainium) implementation - #280

Open
bowencui123 wants to merge 6 commits into
mainfrom
bowen/nki/histogramming
Open

bowencui123 wants to merge 6 commits into
mainfrom
bowen/nki/histogramming

Conversation

@bowencui123

@bowencui123 bowencui123 commented Aug 29, 2026

Copy link
Copy Markdown
Collaborator

NKI (AWS Trainium) implementation of histogramming, split out of the consolidated NKI branch cecilia/feature/nki-vector-add (nki-all-operators, #259) so each operator can be reviewed independently. Supersedes #222 (older per-operator branch: legacy neuronxcc.nki imports; this is the migrated import nki version).

Files: A benchmarks/operators/histogramming/impl_nki.py, M benchmarks/operators/histogramming/impl_torch.py

Status: imports and exposes run()/get_last_config() on trn2 (nki 0.6.0); not individually re-benchmarked in this split

  • also carries the operator's impl_torch.py change from the NKI branch

Implementation by @Cecilia123li. Timing/identity infrastructure: #261; Trainium peak/roofline infra: #262.

🤖 Generated with Claude Code

https://claude.ai/code/session_012Q38kGmXvyoeM1qtCbheSL

Autotune (47d2823)

NKI tunables Triton counterpart note
block_size (values chunk per pass) BLOCK_SIZE/BLOCK_ROWS/BLOCK_BINS Triton's bins/rows split has no NKI analog (histogram accumulates per partition)

autotune=False keeps the previous constants (default numbers unchanged). Validation on trn2, case 0 (default run + autotune code path with the candidate timer stubbed — no sweep; --autotune runs a real sweep):

# initial run
[histogramming] default : verify=OK (1s) 
[histogramming] autotune: verify=OK (0s) last_config={'block_size': 8192} trace_records=1 
STUB_EXIT=0
core.nki_artifact.NkiArtifactIdentityError: 2 valid non-NKI (torch) NEFF/HLO pairs found — artifact identity is ambiguous
Params     |    Dtype |  Torch(ms) |      NKI(ms) |  Speedup(N)
n=262144   | int32    |        nan |          nan |        0.00
# re-validation (tolerance parsing fixed in the checker; engine line above stands)
Torch (Neuron) baseline FAILED: torch-on-Neuron verification failed: torch baseline phase failed: NkiArtifactIdentityError: 2 valid non-NKI (torch) NEFF/HLO pairs found — artifact identity is ambiguous
Params     |    Dtype |  Torch(ms) |      NKI(ms) |  Speedup(N)
n=262144   | int32    |        nan |       0.5025 |         nan
BATCH3_DONE

Split out of the consolidated NKI branch cecilia/feature/nki-vector-add
(nki-all-operators, PR #259) so each operator can be reviewed on its own.
Supersedes PR #222 (older per-operator branch).
- also carries the operator's `impl_torch.py` change from the NKI branch

Co-Authored-By: Cecilia123li <68335867+Cecilia123li@users.noreply.github.com>
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012Q38kGmXvyoeM1qtCbheSL
bowencui123 and others added 3 commits August 29, 2026 08:36
Tunables mirror the Triton search space (`BLOCK_SIZE`/`BLOCK_ROWS`/`BLOCK_BINS`); defaults are the previous constants,
so autotune=False is unchanged. Triton's bins/rows split has no NKI analog (histogram accumulates per partition)

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012Q38kGmXvyoeM1qtCbheSL
This branch's impl_torch.py already builds a CPU-safe reference (no
CUDA-only assert), so this was just never actually benchmarked before.
Adds results/csv/histogramming_default.csv: 20/20 cases pass
correctness verification. Performance is notably poor (~0.02x avg vs.
the torch-on-Neuron baseline, i.e. NKI is ~45-100x slower) -- expected
given the kernel counts via broadcast-compare-per-bin rather than
atomics (no atomic histogram primitive on this hardware), which is
O(N * num_bins) work instead of O(N). Correct, just not fast.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AQseF7nyesBh8KZAp8g7Cm
… LNC2)

Merges NKI backend timing into results/csv/histogramming_autotune.csv,
run with --autotune against this branch's impl_nki.py on trn2.3xlarge,
LNC2 execution contract. 19/20 cases pass correctness verification and
are included.

One case (N=67108864, num_bins=4096 int32) is excluded: neuronx-cc's
backend scheduler/register-allocator (walrus_driver) took multiple
hours to compile a single candidate for this shape and was killed
rather than let run indefinitely. This is the operator's largest input
combined with autotune re-compiling per candidate; the same shape
compiles and runs correctly (just slowly, ~45-100x under the
torch-on-Neuron baseline) under the default (non-autotune) config,
where it's covered by results/csv/histogramming_default.csv. Root
cause is very likely the fully-unrolled Python loop over ~524k
partition tiles for this N generating an extremely large static
program for the compiler backend, not a correctness defect -- every
case that did complete verified correctly.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AQseF7nyesBh8KZAp8g7Cm
Comment thread results/csv/histogramming_autotune.csv Outdated
"N=67108864, num_bins=64",int32,0.7712,0.9464,1.8305,0.81,0.42,1.9342,7.8280,111.8305,0.07
"N=67108864, num_bins=256",int32,0.6610,0.9612,1.8510,0.69,0.36,1.9257,7.8234,217.1039,0.04
"N=67108864, num_bins=1024",int32,0.6350,0.9350,1.7902,0.68,0.35,1.9147,7.8260,870.1608,0.01
"N=67108864, num_bins=4096",int32,0.6246,0.8009,1.4265,0.78,0.44,1.7810,,,

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Lost result for N=67108864, num_bins=4096

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I think the main performance issue here is algorithmic rather than an autotuning issue.

The current NKI implementation iterates over ceil(num_bins / 128) bin blocks. For each bin block, it scans the entire N-element input again, broadcasts/materializes each input chunk across up to 128 partitions, compares every value against the bin ID owned by each partition, and then reduces along the free axis. Therefore, the effective number of full input passes scales with ceil(num_bins / 128).

This is quite different from the Triton/cuTile implementation. Triton and cuTile shard the input across up to 256 partial workers, so each input element is read once and performs one atomic add into a per-worker partial histogram. A second kernel then reduces the partial histograms across workers. The main work is therefore approximately:

O(N) + O(num_partials * num_bins)

instead of repeatedly scanning N for every 128-bin block.

The measurements are consistent with this. For N=67,108,864, autotuned NKI goes from:

  • 111.8 ms for 64 bins
  • 217.1 ms for 256 bins
  • 870.2 ms for 1024 bins

This almost exactly follows the number of 128-bin blocks:

1 -> 2 -> 8

while Triton stays around 0.8-1.0 ms.

Could we rework the NKI implementation to follow the Triton/cuTile algorithm more closely? In particular, it may be worth investigating input sharding plus nl.atomic_rmw(..., op=nl.add) into per-worker partial histograms, followed by a reduction kernel.

I don't think tuning block_size alone can fix the current scaling, because the repeated full-input scan is structural.

That's the reason why autotune take more than 3 hours.
In N=67108864, num_bins=1024, nki takes at least 870ms, while triton only takes 0.935ms

bowencui123 and others added 2 commits September 15, 2026 10:42
# Conflicts:
#	results/csv/histogramming_autotune.csv
#	results/csv/histogramming_default.csv
… packed matmuls, exact int32 accumulation, per-core partials); on-device XLA torch baseline (bincount/histc run on the host); rerun benchmarks

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ScXYNjrrKGgDUVNHxv7HJt
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.

1 participant