Repository navigation
Reuse the shard index tensor in the Neuron executor - #1047
zouchaoqun wants to merge 2 commits into
Conversation
|
I ran the CI test nodes myself while the PR waits for Setup: trn2.48xlarge with the released Neuron SDK 2.33.0 stack (torch 2.14.0, torch-neuronx 2.14.3.0, neuronx-cc 2.28.4568.0, Python 3.14.6). The test tree is the head commit's (3bf0c73). Base uses the installed Two changes were necessary on my host. I used
Result: no test fails only with this change.
I did not run the C++ and MLIR LIT tests, because they need a Bazel build and this change is Python only. I did not run the op-accuracy sweep, because it tests eager ops, which this change does not touch. |
ShardIndexInjection adds a vocab_shard_index input to a graph. The executor filled this input at each call with a new torch.tensor(shard_index, device=...). This is an 8-byte host-to-device write before each graph. The runtime submits an operation on a different execution unit only after the previous operation on the stream retires, and the write runs on a different unit than the graph. Thus the write stops the next graph from being submitted while the previous graph runs. Executor.__call__ now passes a cached transform for the shard index it injects. The cache holds one tensor for each (device index, current stream id, shard index), in an LRU of 16 entries. The executor only uses the tensor as a graph input. TRANSFORM_REGISTRY["shard_index"] still makes a new tensor at each call, so the CPU fallback and every other caller behave as before. The executor reuses its tensor only while the registry holds the original factory, and only for real execution on a Neuron device: a call under a dispatch mode, a pre-dispatch capture, native functionalization, a torch function mode, a functorch transform or Dynamo gets a new tensor. apply_input_mutations takes an override from transforms when the key is present.
Dynamo full-graph capture of the executor's shard index injection failed with Unsupported at torch._C._len_torch_dispatch_stack(). The check for torch.compiler.is_compiling() came after that call, so it did not prevent it. Dynamo cannot trace the call because it returns an int. The cached transform now checks is_compiling() first, after it honors a replacement registry factory. A compiled call gets a new tensor, as before this change. The trace-then-run test now includes Dynamo full-graph capture with an empty and a warm cache.
|
Hi @zouchaoqun thanks for your PR, i'll assign someone from the team to help review your PR and RFC. Meanwhile, could you please retarget your PR to |
3bf0c73 to
9960d2d
Compare
|
@kunind-aws thanks! I retargeted this PR to On the new head (9960d2d), the |
|
Assigning @vthkumar-aws to help review the PR
I'll take a look. Thank you for bringing this up! |
vthkumar-aws
left a comment
There was a problem hiding this comment.
Thank you for making this change! We should definitely eliminate the host->device transfer of these scalars from the critical path. Below is the root cause as I traced it through the runtime, and a proposal that gets the same overlap with less new code.
The Neuron runtime keeps a separate hardware queue for each kind of work on a stream. Graphs (kHLO) go to the COMPUTE execution unit (XU), and copies and writes (kWrite) go to the TENSOR_OP XU (GetXUIndex). Ops on one queue run in order on the device. Ops on two different queues have no order between them. To keep the in-order contract of the stream, the runtime worker thread applies rule (c) in IsScheduleGatedByPriorOp: an op on a different XU than the previous op is held on the host, not submitted, until the previous op completes (the scheduler pre-check returns nullptr). The Python thread never waits: torch.tensor(shard_index, device=...) copies the 8 bytes into a host staging buffer (use_bounce for a one-element tensor) and returns. So when calls are queued back to back, each call costs two host round trips, and the device has nothing queued during them:
G1 submitted to COMPUTE ............ device runs G1
W2 held on the host (not submitted; its 8 bytes sit in a host buffer)
G1 completes -> worker thread wakes
W2 submitted to TENSOR_OP .......... 8-byte transfer happens now
G2 held on the host (rule (c) again: different queue than W2)
W2 completes -> worker thread wakes
G2 submitted to COMPUTE ............ device runs G2
On the device timeline, that gives a gap between each pair of graphs:
Before (a new write W at each call):
COMPUTE [==== G1 ====] [==== G2 ====] [==== G3 ====]
TENSOR_OP ...[W2]... ...[W3]...
^ host round trips, device idle
After (one cached tensor, written once by W1 on the first call on the stream):
COMPUTE [==== G1 ====][==== G2 ====][==== G3 ====]
TENSOR_OP [W1]
With the cache, calls 2 and later have no write, so G2 goes on the same COMPUTE queue as G1 and waits on the device instead of the host. The cost was never the 8 bytes. It was that graph N+1 could not be queued behind graph N. That matches the benchmark in the description (0.50 -> 0.40 ms per call, against 0.35 ms with the pass disabled).
The repository already has a device cache for this case: ScalarDeviceMemoryCache, used through createCachedScalarTensor. It keeps one device slot per (device, value) for the whole process. On first use, each stream queues its own alloc and value write, and later uses on that stream skip the write. That is the same (device, stream) ordering that the new LRU key handles. Eager dispatch already uses it for scalar arguments (PreprocessArgs.cpp). It is deliberately not used where the result goes back to the caller, because the caller could write the shared slot in place. The injected shard index never goes back to the caller and the NEFF only reads it, which is the same reason this PR gives for its cache. So a small Python binding to createCachedScalarTensor gives the same overlap, and the whole change reduces to one transform (the binding name is only an illustration):
def _cached_shard_index_tensor(index, device, params, original_inputs):
value = int(params["shard_index"])
t = None
if not torch.compiler.is_compiling() and not torch._C._is_torch_function_mode_enabled():
# Returns None in compile-only mode and under a dispatch, functional or functorch mode.
t = torch_neuronx._C._cached_scalar_tensor(value, torch.int64, torch.device(device).index)
return t if t is not None else torch.tensor(value, dtype=torch.int64, device=device)That removes the 16-entry LRU, the stream id lookup, the device index normalization, the registry identity check and _new_shard_index_tensor. The existing cache already owns the (device, stream) ordering. createCachedScalarTensor already returns nullopt in compile-only mode and when TORCH_NEURONX_ENABLE_SCALAR_CACHE=0. The binding should also return None under a dispatch, functional or functorch mode, so a trace gets a new tensor as today. Dynamo and torch function modes are checked in Python, because C++ cannot see them. In all of these cases, the torch.tensor fallback keeps today's behavior. Another advantage: a common _cached_scalar_tensor binding is easy to extend to the other scalar allocations in the executor. For example, the Python scalar inputs in _prepare_input make a new one-element write at each call and hit the same rule (c) hold. One-element CPU inputs (L230) can use it too, when the graph does not write them in place. With the explicit cache in this PR, each of these cases needs its own cache and its own set of checks.
What do you think of the above proposal? I would still be happy to use the current explicit caching approach, in which case just the other nit comments would need to be addressed. In both cases, please rerun the listed tests on the current head (9960d2d): the hardware results in the description are for 3bf0c73 and 8aa18dc on the 2.33 stack, before the rebase onto 2.34.
Generated with Claude Code.
| def _cached_shard_index_tensor(index, device, params, original_inputs): | ||
| """Return the cached int64 scalar tensor holding ``params["shard_index"]`` on ``device``.""" | ||
| # A caller that replaces TRANSFORM_REGISTRY["shard_index"] gets its factory here too, as | ||
| # without the cache: the executor and the CPU fallback inject the same value. | ||
| factory = TRANSFORM_REGISTRY["shard_index"] | ||
| if factory is not _new_shard_index_tensor: | ||
| return factory(index, device, params, original_inputs) | ||
| # Dynamo cannot trace the dispatch state checks below. A compiled call gets a new tensor. | ||
| if torch.compiler.is_compiling(): | ||
| return torch.tensor(params["shard_index"], dtype=torch.int64, device=device) | ||
| # A torch function mode can intercept torch.device() itself, so this check comes before it. | ||
| # Under any such mode, torch.device() and set_default_device() included, a call gets a new | ||
| # tensor made from the original argument, as without the cache. | ||
| if torch._C._is_torch_function_mode_enabled(): | ||
| return torch.tensor(params["shard_index"], dtype=torch.int64, device=device) | ||
| device = torch.device(device) | ||
| if not _reuse_shard_index(device): | ||
| return torch.tensor(params["shard_index"], dtype=torch.int64, device=device) | ||
| # Stream ids repeat across devices, so a key without the device index can match another device. | ||
| if device.type == "neuron" and device.index is None: | ||
| device = torch.device("neuron", torch.neuron.current_device()) | ||
| device = str(device) | ||
| return _shard_index_on(device, _current_stream_id(device), int(params["shard_index"])) |
There was a problem hiding this comment.
Nit: This function has a lot of redundant code. The three fallback branches (L161, L166, L169) are the same torch.tensor(...) call, which is also the body of _new_shard_index_tensor. The device.index is None normalization at L170-L172, the None return of _current_stream_id and _SHARD_INDEX_CACHE_DEVICE_TYPES handle devices that the executor, the only caller, never passes: it always passes f"neuron:{device_id}". Only the tests reach those branches, by adding "cpu" to the set. With one fallback and a direct device.type == "neuron" check in _reuse_shard_index, the function becomes:
def _cached_shard_index_tensor(index, device, params, original_inputs):
factory = TRANSFORM_REGISTRY["shard_index"]
if (
factory is not _new_shard_index_tensor
or torch.compiler.is_compiling()
or torch._C._is_torch_function_mode_enabled()
or not _reuse_shard_index(torch.device(device))
):
return factory(index, device, params, original_inputs)
stream_id = torch.neuron.current_stream(device).stream_id
return _shard_index_on(device, stream_id, int(params["shard_index"]))The checks keep their order, so Dynamo and torch function modes are still handled before torch.device(). _current_stream_id, _SHARD_INDEX_CACHE_DEVICE_TYPES and the CPU monkeypatching in the tests can then go. This applies only if the explicit cache stays; see the overall comment for the alternative.
Generated with Claude Code.
| # The executor reuses one tensor for each (device, stream, shard index) when it injects the shard | ||
| # index (_EXECUTOR_INPUT_TRANSFORMS). TRANSFORM_REGISTRY["shard_index"] still makes a new tensor at | ||
| # each call, so a caller that changes the tensor it gets never changes a later call's. The executor | ||
| # only passes the tensor to the graph as an input. A new tensor at each call is a | ||
| # host-to-device write. Python enqueues the write and the next graph without waiting. The runtime | ||
| # submits a device op on another execution unit only after the previous op retires: the write | ||
| # after the previous graph, then the next graph after the write. The first upload is asynchronous | ||
| # on the current stream. Only graphs on that stream are ordered after it. Each new stream gets a | ||
| # new id, so the cache is an LRU of fixed size. An evicted tensor is released as the per-call | ||
| # tensor was before. The cache is process-wide. With more than 16 keys in use, each call can miss | ||
| # and upload a new tensor again. The results stay the same. |
There was a problem hiding this comment.
Nit: Big block comments like this one, and the one at L130-L137, are discouraged. The scheduling and dispatch details belong in the PR description and the RFC. Please cut each block to one or two lines that give the reason, for example: # Reuse one tensor per (device, stream). A new H2D write at each call makes the next graph wait for the previous one.
Generated with Claude Code.
|
Thanks @vthkumar-aws for the review! Yes your proposal sounds better and I will update to use yours. |
Description
Claude drafted the change, the benchmark scripts, and the blockquoted passages.
Related Issue
RFC: #1046
Motivation and Context
I noticed this issue while optimizing latency for my real-time model. The Trainium2 benchmark confirmed that reusing the shard-index tensor reduced the average time per queued graph call, which is why I’m proposing this change upstream.
Type of Change
Testing
bench_shard_index.py, same_outputs.py and dynamo_check.py
bench_shard_index.py:same_outputs.py:dynamo_check.py:Checklist