Repository navigation
Description
Summary
Claude drafted the change, the benchmark scripts, and the blockquoted passages. Codex helped edit this revision.
The Neuron executor fills the
vocab_shard_indexgraph input with a newtorch.tensor(shard_index, device=...)at each call. This 8-byte host-to-device write stops the runtime from submitting the next graph while the previous graph runs. This RFC proposes that the executor reuses one tensor for each (device index, current stream, shard index), with a small LRU cache, and only for real execution on a Neuron device.
Affected areas
torch.compile (
neuron_dynamo_backend:executor.py,fx/io_mutation.py); the cache key uses the current stream id.
Motivation
I noticed this issue while optimizing latency for my real-time model. I'm sharing the PR because the Trainium2 benchmark confirmed that reusing the shard-index tensor reduced the average time per queued graph call.
ShardIndexInjection(torch_neuronx/neuron_dynamo_backend/fx/passes/vocab_sharding_spmd.py) adds avocab_shard_indexinput to a graph with a vocab-parallel embedding when it can infer the shard index from the graph's vocabulary-sharding constants.Executor.__call__fills it throughapply_input_mutations(executor.py#L421) andTRANSFORM_REGISTRY["shard_index"](fx/io_mutation.py#L101), which makes a new tensor at each call. The pass injects the input only when it infers the shard index (vocab_sharding_spmd.py#L421).Each compiled graph into which
ShardIndexInjectioninjectsvocab_shard_indexpays for this when the caller queues graphs without a synchronize at each call. The pass injects it only when it can infer the shard index from the graph's vocabulary-sharding constants. A benchmark built fromtests/distributed/neuron_dynamo_backend/tensor_parallel/test_embedding_grad_compile.py(trn2.48xlarge, torch-neuronx 2.14.3.0 from Neuron 2.33.0, bf16, one token for each call) gives these times in ms for each call, TP rank 0. Each cell gives two runs. Each run is the rank-0 median of 5 repeats of 400 queued calls. "Proposed" is revision 8aa18dc of the change:
Model TP Current Proposed (8aa18dc) Pass disabled (reference) hidden 2048, ffn 8192, 4 layers 4 0.5026 / 0.5020 0.3988 / 0.3970 0.3544 / 0.3524 hidden 4096, ffn 14336, 8 layers 16 0.9140 / 0.9147 0.6317 / 0.6265 0.6193 / 0.6186 hidden 4096, ffn 14336, 8 layers 4 2.1563 / 2.1319 1.9482 / 1.9478 1.9460 / 1.9461
Root cause
Measured: the per-call times above, and that on the two larger models the proposed change is within 2.1% of the time with the pass disabled (
TORCH_NEURONX_VOCAB_SHARDING_SPMD_DISABLE=1, used only as a reference): 0.1% at TP 4 and 1.3-2.0% at TP 16 in the two runs.torch.equalmatched the saved rank-0 outputs of all arms.Inferred from the code: a one-element CPU-to-Neuron copy is an asynchronous write on the current stream (
csrc/core/utils/CopyUtils.cpp#L64, thenumel() == 1path). It runs on a different execution unit than a graph (GetXUIndex,csrc/core/KernelExecution.h#L95). The runtime submits an operation on a different unit only after the previous operation on the stream retires (StreamImpl::IsScheduleGatedByPriorOp,csrc/core/streams/StreamImpl.cpp#L396, case (c) at line 422). Thus the write is submitted after the previous graph retires, and the next graph after the write. Without the write, the runtime can submit the next graph while the previous graph is still running.The shard index is fixed for a given injected input, so a tensor can be reused for the same device, stream and shard index.
Proposed change
Executor.__call__passes a cached transform for the shard index it injects (apply_input_mutations(..., transforms=...), a new optional argument;executor.py#L423,fx/io_mutation.py#L152). The executor only uses the tensor as a graph input.- The cache is
functools.lru_cache(maxsize=16)keyed by (device index, current stream id, shard index). The stream is in the key because the first upload is ordered only on its own stream. The device index is in the key because stream ids repeat across devices.TRANSFORM_REGISTRY["shard_index"]is unchanged: it makes a new tensor at each call. The CPU fallback and every other caller behave as today. A caller that changes the tensor it gets does not change a later call.- The executor reuses its tensor only while the registry holds the original factory, and only for real execution on a Neuron device. A call gets a new tensor when its own thread has a dispatch mode on its stack (
torch._C._len_torch_dispatch_stack()), thePreDispatchorFunctionalizekey in its include set, a torch function mode active, a functorch transform active, or under Dynamo (torch.compiler.is_compiling()). The Dynamo check comes first, because Dynamo cannot trace the dispatch state checks.apply_input_mutationstakes an override fromtransformswhen the key is present.
Precedent
The Neuron dispatcher already makes the same split for scalars. It reuses internal scalar inputs by value through
ScalarDeviceMemoryCache(csrc/core/dispatch/PreprocessArgs.cpp#L67). Foraten::scalar_tensorit makes a fresh scalar, because that result goes to the caller, who can write it in place (csrc/core/dispatch/NeuronDispatcher.cpp#L284). This change does the same: the executor reuses its internal input, andTRANSFORM_REGISTRY["shard_index"]still gives each caller a fresh tensor.
torch_neuronx/python_ops/torch_mlir/kernel.pyalready checkstorch._C._len_torch_dispatch_stack()to detect a dispatch mode.functools.lru_cacheis used for process-wide caches inint64_policy.py,nki_kernel.pyandneuron_dynamo_backend/metrics.py. I did not find a cache of an injected graph input in this repository; this is the first one.
Alternatives considered
- Do nothing: graphs with an injected
vocab_shard_indexkeep the per-call gate (see the table).- Disable the pass with
TORCH_NEURONX_VOCAB_SHARDING_SPMD_DISABLE=1: each rank keeps its own vocabulary offsets as constants, so the output stays correct. The ranks' graphs then differ, so the ranks can need separate compiled artifacts. Used here only as a reference.- An unbounded cache:
NeuronStream::createStreamgives each new stream a new id, so it would keep one tensor for each stream a process ever used.- Cache in
TRANSFORM_REGISTRY["shard_index"]itself (an earlier version): callers that change the returned tensor, or replace the registry entry, would see different results than today.- A check that the thread's dispatch-key include set is empty: plain eager code already has keys there (
BackendSelect,ADInplaceOrView), andinference_mode()changes it.
Scope and limitations
- Only the shard index that the executor injects. Other injected inputs are unchanged.
- The 16 entries are shared by all devices, streams and shard indices. With more than 16 keys in use, a key that is used often can still hit. Calls that cycle through more than 16 keys can miss at each call, and then behave as today.
- Under any torch function mode, including the context manager
with torch.device(...)and the mode that the settertorch.set_default_device(...)installs, the executor makes a new tensor, as today.- Each hit avoids the 8-byte write. The time saved comes from the next graph's submission, which this small write delays, not from the size of the transfer. With a synchronize after each call, synchronized p50 and p99 varied across the two runs, in both directions. For example, the small TP 4 model's rank-0 p99 was 0.8391 / 0.8434 ms today and 0.8242 / 0.9348 ms with the change.
Evidence (hardware)
Environment: trn2.48xlarge, torch 2.14.0, torch-neuronx 2.14.3.0 (Neuron 2.33.0), neuronx-cc 2.28.4568.0, Neuron runtime 2.34.10.
Method: the same image, torch-neuronx 2.14.3.0 as installed (itsexecutor.pyandfx/io_mutation.pyare byte-identical tocontribute-2.33's), with a fresh container for each run (one arm, one model, one run number). The scriptsbench_shard_index.pyandsame_outputs.pyare in the description of #1047. In each container, run the block below from the directory that holds the two scripts, without/on a host directory that every container mounts.ARMonly names the output file; the twoifsteps select the arm.mkdir -p out ARM=current # current, proposed or disabled MODEL=tp4small # tp4small, tp16large or tp4large N=1 # the run number SITE=$(python3 -c 'import os, torch_neuronx; print(os.path.dirname(torch_neuronx.__file__))') # proposed: the two files of 8aa18dc over the installed ones if [ "$ARM" = proposed ]; then git clone -q https://github.com/zouchaoqun/torch-neuronx-fork.git fork git -C fork checkout -q 8aa18dc92a0b9b0495655ad4bf1baf12ee6a7ed4 cp fork/torch_neuronx/neuron_dynamo_backend/executor.py "$SITE/neuron_dynamo_backend/executor.py" cp fork/torch_neuronx/neuron_dynamo_backend/fx/io_mutation.py "$SITE/neuron_dynamo_backend/fx/io_mutation.py" fi # disabled: the reference arm if [ "$ARM" = disabled ]; then export TORCH_NEURONX_VOCAB_SHARDING_SPMD_DISABLE=1; fi case "$MODEL" in tp4small) NP=4; SIZE="" ;; tp16large) NP=16; SIZE="--hidden 4096 --ffn 14336 --layers 8" ;; tp4large) NP=4; SIZE="--hidden 4096 --ffn 14336 --layers 8" ;; esac torchrun --nproc-per-node "$NP" bench_shard_index.py $SIZE --save "out/$ARM.$MODEL.r$N.pt"After all runs:
python3 same_outputs.py out/*.pt. The recorded runner mounted the two 8aa18dc files read-only (docker run -v ...:ro) instead of copying them; the result is the same files in the same place.Results: see the table under Motivation.
same_outputs.py(in the PR) compares shape, dtype and bytes, and exits 1 on a difference; the runs above were checked withtorch.equal. Host time for each call, measured on revision 2f72621 (20,000 calls onneuron:0, p50 / p99):apply_input_mutationswith one shard index 25.4 / 46.4 µs today, 7.8 / 13.9 µs through the executor's cached transform, of which the mode checks take 1.7 / 1.8 µs. Memory: the cache retains at most 16 tensors (one-element int64). The cache teststream_churnchecks the Python references to CPU tensors across 1,000 simulated stream ids. It does not measure peak device memory.
Risks and mitigations
- A cached tensor reaching a non-real execution (trace, fake, functional): every known mode is checked on the calling thread, and each has a test (
trace_then_run, with empty and filled caches, Dynamo full-graph capture included, and a two-thread case).- A stale tensor after eviction while a read is queued: the evicted tensor is released as the per-call tensor is today;
compiled_evictionchecks one evicted tensor with its read still queued.- Rollback: the change is local to
executor.pyandfx/io_mutation.py. There is no flag; removing thetransforms=argument from the executor call restores today's behaviour.
Testing plan
tests/neuron_dynamo_backend/unit/test_io_mutation.py(new cache, mode, thread, eviction, registry-override and executor-reuse tests) andtests/device/test_multi_device.py::TestNeuronDevice::test_shard_index_tensor_per_device(two devices).compiled_evictiondepends on timing and skips, after its output check, if the backlog drains first.
Open questions
- Is 16 entries the right bound, or should it follow the stream pool size?
- Should the executor pass the cached transform for other constant injected inputs later, or keep this to the shard index?
Activity