Skip to content

Reuse the shard index tensor in the Neuron executor - #1047

Open
zouchaoqun wants to merge 2 commits into
aws-neuron:mainfrom
zouchaoqun:submit/shard-index-contribute-2.33-v2
Open

zouchaoqun wants to merge 2 commits into
aws-neuron:mainfrom
zouchaoqun:submit/shard-index-contribute-2.33-v2

Conversation

@zouchaoqun

Copy link
Copy Markdown
Collaborator

Description

The executor now reuses the vocab_shard_index tensor that it injects, instead of a new tensor at each call. It keeps one tensor for each (device index, current stream id, shard index) in an LRU cache of 16 entries. TRANSFORM_REGISTRY["shard_index"], the CPU fallback and every other caller still get a new tensor at each call, as before.

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.

ShardIndexInjection adds a vocab_shard_index input to a graph with a vocab-parallel embedding when it can infer the shard index from the graph's vocabulary-sharding constants (vocab_sharding_spmd.py#L421). The executor filled it at each call with torch.tensor(shard_index, device=...) (executor.py#L421, fx/io_mutation.py#L101), an 8-byte host-to-device write (CopyUtils.cpp#L64). The write runs on a different execution unit than a graph, and the runtime submits an operation on a different unit only after the previous operation on the stream retires (StreamImpl::IsScheduleGatedByPriorOp, case (c) at line 422). Thus the next graph cannot be submitted while the previous graph runs, when the caller queues graphs without a synchronize at each call. For the graphs where the pass injects the shard index, a cache hit removes the write, so the runtime can submit the next graph while the previous one runs. The shard index is fixed for a given injected input, so a tensor can be reused for the same device, stream and shard index.

  • The cache key holds the stream id, because the first upload is ordered only on its own stream, and the device index, because stream ids repeat across devices.
  • The executor passes the cached transform to apply_input_mutations through a new optional transforms argument, and only uses the tensor as a graph input. apply_input_mutations takes an override when the key is present.
  • The executor reuses its tensor only while TRANSFORM_REGISTRY["shard_index"] is the original factory, and only for real execution on a Neuron device. A call on a thread with a dispatch mode on its stack, the PreDispatch or Functionalize key in its include set, a torch function mode, a functorch transform, or under Dynamo gets a new tensor. The Dynamo check comes first, because Dynamo cannot trace the dispatch state checks. The torch function mode check comes before torch.device(), because the mode can intercept it.

Type of Change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update
  • Refactoring (no functional changes)

A performance change. The outputs do not change. The template has no box for it.

Testing

Paths: torch.compile (the executor), the CPU fallback, and eager calls of the transform. One and two NeuronCores, and two devices.

Ran locally (no Neuron hardware needed):

pre-commit run --all-files    # all hooks pass

Ran on Neuron hardware (trn2.48xlarge, torch 2.14.0, torch-neuronx 2.14.3.0 (Neuron 2.33.0), neuronx-cc 2.28.4568.0, pytest 9.2.0. The installed io_mutation.py, executor.py, backend.py and vocab_sharding_spmd.py are byte-identical to contribute-2.33's; the head commit's (3bf0c73) io_mutation.py and executor.py are mounted over them, and the tests are its tests):

# repository layout (root pyproject.toml and conftest.py), from the repository root
NEURON_RT_VISIBLE_CORES=62-63 python3 -m pytest -p no:cacheprovider -rA tests/neuron_dynamo_backend/unit/test_io_mutation.py
NEURON_RT_VISIBLE_CORES=62-63 python3 -m pytest -p no:cacheprovider -rA tests/device/test_multi_device.py::TestNeuronDevice::test_shard_index_tensor_per_device
# the file alone: test_io_mutation.py copied into an empty directory, run from there
K='shard_index or executor_ or transforms_selected'
NEURON_RT_VISIBLE_CORES=62-63 python3 -m pytest -p no:cacheprovider -rA -o addopts= test_io_mutation.py
NEURON_RT_VISIBLE_CORES=62-63 TORCH_NEURONX_ENABLE_STREAMS=0 python3 -m pytest -p no:cacheprovider -rA -o addopts= test_io_mutation.py -k "$K"
NEURON_RT_VISIBLE_CORES=62-63 TORCH_NEURONX_ENABLE_STREAMS=1 python3 -m pytest -p no:cacheprovider -rA -o addopts= test_io_mutation.py -k "$K"
NEURON_RT_VISIBLE_CORES=63 python3 -m pytest -p no:cacheprovider -rA -o addopts= test_io_mutation.py -k "$K"
for i in 1 2 3; do NEURON_RT_VISIBLE_CORES=62-63 python3 -m pytest -p no:cacheprovider -rA -o addopts= test_io_mutation.py -k 'executor_reuses_injected_shard_index or executor_uses_replaced or executor_transform_honors'; done
for i in 1 2 3; do NEURON_RT_VISIBLE_CORES=62-63 python3 -m pytest -p no:cacheprovider -rA -o addopts= test_io_mutation.py -k 'trace_then_run or fake_mode_in_other_thread'; done
for i in 1 2 3; do NEURON_RT_VISIBLE_CORES=62-63 python3 -m pytest -p no:cacheprovider -rA -o addopts= test_io_mutation.py -k compiled_eviction; done
# the standalone Dynamo check (dynamo_check.py below), once with each io_mutation.py in place: contribute-2.33's, 2f72621's, this commit's
NEURON_RT_VISIBLE_CORES=63 python3 dynamo_check.py
Run Result
Repository layout (root pyproject.toml and conftest.py), whole file 142 passed
File alone, whole file 142 passed
TORCH_NEURONX_ENABLE_STREAMS=0 / =1, -k 'shard_index or executor_ or transforms_selected' 53 passed / 53 passed
One NeuronCore (63), same selection 53 passed
test_shard_index_tensor_per_device (two devices) passed
Executor tests, 3 repeats 4 passed, 3 of 3
trace_then_run (Dynamo full-graph capture included) and fake_mode_in_other_thread, 3 repeats 38 passed, 3 of 3
compiled_eviction, 3 repeats passed, 3 of 3, none skipped
Dynamo full-graph capture of the injection on neuron:0, capture-only backend, empty and warm cache captured, value 1 on neuron:0, cache unchanged (contribute-2.33 and 3bf0c73); Unsupported at _len_torch_dispatch_stack() on 2f72621

Benchmark (torch.compile, inference, bf16, vocabulary 32768, one token for each call; the model and TP plan come from tests/distributed/neuron_dynamo_backend/tensor_parallel/test_embedding_grad_compile.py). 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. "After" is revision 8aa18dc of this change:

Model TP Before After (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

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: 0.8391 / 0.8434 ms before, 0.8242 / 0.9348 ms after). Three library changes came after 8aa18dc. The executor uses its cache only while the registry holds the original factory. apply_input_mutations selects an override when the key is present, not when the value is truthy. The cached transform checks for Dynamo before the dispatch state checks; a real call makes the same checks as before. On hardware, the cached transform takes 6.90 µs p50 for each call with the registry check and 6.78 µs without it. Host time for apply_input_mutations with one shard index, measured on 2f72621 (20,000 calls on neuron:0, p50 / p99): 25.4 / 46.4 µs before, 7.8 / 13.9 µs after. torch.equal matched the saved rank-0 outputs of all arms. The same_outputs.py below now also compares shape, dtype and bytes, and exits 1 on a difference.

bench_shard_index.py, same_outputs.py and dynamo_check.py

bench_shard_index.py:

"""Per-call cost of the ShardIndexInjection input on a vocab-parallel model (Neuron SDK 2.33.0, torch-neuronx 2.14.3.0, inference).

The model and TP plan follow tests/distributed/neuron_dynamo_backend/tensor_parallel/test_embedding_grad_compile.py
(a RowwiseParallel tok_embeddings followed by a Colwise / Rowwise SwiGLU feed-forward), at larger sizes and with
several feed-forward layers, so that ShardIndexInjection injects vocab_shard_index into the compiled graph.

  torchrun --nproc-per-node 4 bench_shard_index.py [--steps 400] [--layers 4]

Two timings per configuration, in ms per forward call:
  queued: STEPS calls enqueued back to back (each output feeds nothing on the host), one synchronize at the end;
  synced: each call followed by torch.neuron.synchronize(), p50 / p99.
--save: rank 0's last output, to compare runs bitwise (same_outputs.py).
"""

import argparse
import json
import logging
import os
import statistics
import time

import torch
import torch.distributed as dist
import torch.nn as nn
from torch.distributed.device_mesh import init_device_mesh
from torch.distributed.tensor import Replicate
from torch.distributed.tensor.parallel import ColwiseParallel, RowwiseParallel, parallelize_module


class FeedForward(nn.Module):
    def __init__(self, hidden, ffn):
        super().__init__()
        self.w1 = nn.Linear(hidden, ffn, bias=False)
        self.w2 = nn.Linear(ffn, hidden, bias=False)
        self.w3 = nn.Linear(hidden, ffn, bias=False)

    def forward(self, x):
        return x + self.w2(torch.nn.functional.silu(self.w1(x)) * self.w3(x))


class Model(nn.Module):
    def __init__(self, vocab, hidden, ffn, layers):
        super().__init__()
        self.tok_embeddings = nn.Embedding(vocab, hidden)
        self.layers = nn.ModuleList(FeedForward(hidden, ffn) for _ in range(layers))

    def forward(self, ids):
        x = self.tok_embeddings(ids)
        for layer in self.layers:
            x = layer(x)
        return x


def main():
    p = argparse.ArgumentParser()
    p.add_argument("--vocab", type=int, default=32768)
    p.add_argument("--hidden", type=int, default=2048)
    p.add_argument("--ffn", type=int, default=8192)
    p.add_argument("--layers", type=int, default=4)
    p.add_argument("--seq", type=int, default=1)
    p.add_argument("--steps", type=int, default=400)
    p.add_argument("--repeats", type=int, default=5)
    p.add_argument("--save", default="", help="rank 0 saves its last output here, for a bitwise check across runs")
    args = p.parse_args()

    dist.init_process_group(backend="neuron")
    rank, world = dist.get_rank(), dist.get_world_size()
    if rank == 0:
        logging.basicConfig(level=logging.INFO)
        logging.getLogger("torch_neuronx.neuron_dynamo_backend.fx.passes.vocab_sharding_spmd").setLevel(logging.DEBUG)
    device = torch.device(f"neuron:{torch.neuron.current_device()}")
    mesh = init_device_mesh("neuron", (world,))

    torch.manual_seed(1)
    model = Model(args.vocab, args.hidden, args.ffn, args.layers).to(torch.bfloat16)
    plan = {"tok_embeddings": RowwiseParallel(input_layouts=Replicate(), output_layouts=Replicate())}
    for i in range(args.layers):
        plan[f"layers.{i}.w1"] = ColwiseParallel()
        plan[f"layers.{i}.w3"] = ColwiseParallel()
        plan[f"layers.{i}.w2"] = RowwiseParallel(output_layouts=Replicate())
    parallelize_module(model, mesh, plan)
    model = model.to(device).eval()
    forward = torch.compile(model, backend="neuron", fullgraph=True, dynamic=False)

    ids = torch.randint(0, args.vocab, (1, args.seq), dtype=torch.long, device=device)
    with torch.no_grad():
        ref = forward(ids)
        for _ in range(20):
            forward(ids)
        torch.neuron.synchronize()
        queued, synced = [], []
        for _ in range(args.repeats):
            dist.barrier()
            t0 = time.perf_counter()
            for _ in range(args.steps):
                out = forward(ids)
            torch.neuron.synchronize()
            queued.append((time.perf_counter() - t0) * 1e3 / args.steps)
            dist.barrier()
            for _ in range(args.steps):
                t0 = time.perf_counter()
                out = forward(ids)
                torch.neuron.synchronize()
                synced.append((time.perf_counter() - t0) * 1e3)
        same = bool(torch.equal(out.to_local().cpu() if hasattr(out, "to_local") else out.cpu(), ref.to_local().cpu() if hasattr(ref, "to_local") else ref.cpu()))

    synced.sort()
    res = {
        "rank": rank,
        "disable_env": os.environ.get("TORCH_NEURONX_VOCAB_SHARDING_SPMD_DISABLE", ""),
        "queued_ms_per_call": [round(x, 4) for x in queued],
        "queued_median": round(statistics.median(queued), 4),
        "synced_p50": round(synced[len(synced) // 2], 4),
        "synced_p99": round(synced[int(len(synced) * 0.99)], 4),
        "output_repeatable": same,
        "checksum": float((out.to_local() if hasattr(out, "to_local") else out).float().sum().cpu()),
    }
    print("RESULT " + json.dumps(res), flush=True)
    if args.save and rank == 0:
        torch.save((out.to_local() if hasattr(out, "to_local") else out).cpu(), args.save)
    dist.barrier()
    dist.destroy_process_group()


if __name__ == "__main__":
    main()

same_outputs.py:

"""Compare the benchmark outputs saved with --save byte for byte: every file of a model against the first one.
Exit 1 if a file differs in shape, dtype or bytes.
  python3 same_outputs.py out/*.pt"""
import collections, sys

import torch


def same_bytes(a, b):
    if a.shape != b.shape or a.dtype != b.dtype:
        return False
    return torch.equal(a.contiguous().reshape(-1).view(torch.uint8), b.contiguous().reshape(-1).view(torch.uint8))


groups = collections.defaultdict(list)
for f in sorted(sys.argv[1:]):
    groups[f.rsplit("/", 1)[-1].split(".")[1]].append(f)     # <variant>.<model>.<run>.pt
differ = []
for model, files in groups.items():
    ref = torch.load(files[0])
    same = [same_bytes(ref, torch.load(f)) for f in files]
    differ += [f for f, s in zip(files, same) if not s]
    print(f"{model}: {sum(same)} of {len(files)} outputs byte-identical to {files[0].rsplit('/', 1)[-1]}, shape {tuple(ref.shape)}, "
          f"dtype {ref.dtype}; differing {[f.rsplit('/', 1)[-1] for f, s in zip(files, same) if not s]}")
sys.exit(1 if differ else 0)

dynamo_check.py:

# Dynamo full-graph capture of the shard index injection on neuron:0 with a capture-only backend, for the io_mutation.py
# in place. Prints CAPTURED or FAILED for an empty and a warm cache, and whether the cache changed.
import torch, torch_neuronx  # noqa: F401
from torch_neuronx.neuron_dynamo_backend.fx import io_mutation as M
p = [M.PassMutations(pass_name="P", input_mutations=[M.IOMutation(kind=M.MutationKind.ADD, indices=[1], transform_key="shard_index", transform_params={"shard_index": 1}, pass_name="P")])]
dev = f"neuron:{torch.neuron.current_device()}"
extra = (M._EXECUTOR_INPUT_TRANSFORMS,) if hasattr(M, "_EXECUTOR_INPUT_TRANSFORMS") else ()
def inject(tokens):
    return M.apply_input_mutations([tokens], p, dev, *extra)[1]
for warm in (False, True):
    torch._dynamo.reset()
    if hasattr(M, "_shard_index_on"):
        M._shard_index_on.cache_clear()
        if warm:
            inject(torch.tensor([1, 5, 9]))
    before = M._shard_index_on.cache_info() if hasattr(M, "_shard_index_on") else None
    graphs = []
    try:
        out = torch.compile(inject, fullgraph=True, backend=lambda gm, ex: (graphs.append(gm), gm.forward)[1])(torch.tensor([1, 5, 9]))
        after = M._shard_index_on.cache_info() if hasattr(M, "_shard_index_on") else None
        print("CAPTURED", "warm" if warm else "empty", "value", out.item(), "device", out.device, "graphs", len(graphs), "cache unchanged", before == after)
    except Exception as e:
        print("FAILED", "warm" if warm else "empty", type(e).__name__, " | ".join(l for l in str(e).splitlines() if l.strip())[:300])

Checklist

  • Added or updated tests for this change
  • I've performed a self-review for my code
  • Ran the tests, or explained under Testing why I could not
  • Updated the corresponding documentation
  • My changes generate no new warnings
  • Said under Description if an AI assistant helped with this change (see AI_POLICY.md)

@github-actions github-actions Bot added the module:dynamo Touches Dynamo backend label Nov 23, 2026
@zouchaoqun

Copy link
Copy Markdown
Collaborator Author

I ran the CI test nodes myself while the PR waits for safe-to-test. This is not a CI run.

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 executor.py and fx/io_mutation.py, which are byte-identical to contribute-2.33. Head mounts the two files of 3bf0c73 over them. Each node ran in a fresh container with the repository's runner and config:

TEST_TIMEOUT=1800 python3 tests/pytorch_tests_native/runner/run_upstream_tests.py --node <node> --output-dir <dir>

Two changes were necessary on my host. I used pytest<9 (8.4.2), because pytest 9.2.0 rejects the --json_report option of conftest.py next to the --json-report option of pytest-json-report. The NEFF cache was cold, so I set CLASS_TIMEOUT=14400.

Node Base: passed / failed / error Head: passed / failed / error Only with head
aten-unit-tests 18368 / 9 / 142 18503 / 9 / 0 1, does not reproduce (below)
aten-tail-tests 449 / 0 / 1 455 / 0 / 0 0
dist-unit-tests 832 / 23 / 0 832 / 23 / 0 1, fails on base too (below)
dynamic-nki-unit-tests 945 / 0 / 0 945 / 0 / 0 0

Result: no test fails only with this change.

  • The base-only failures are the new tests in test_io_mutation.py and test_multi_device.py. They need the new code.
  • The failures in both arms come from my environment: test_version.py needs setup.py, test_replicate_pp.py needs EFA, and test_auto_compile_distributed.py needs _zstd. Some latency ceilings in test_strided_collectives_perf.py also fail.
  • The first head-only failure was test_cumsum_ops.py::TestCummaxCumminCompile::test_compile[nan-cummin], a compiler error in the parallel run. Each arm had 6 compile errors of this type on different tests in that run. I ran the test alone, with its class and with its file, 3 times in each arm, and all 18 runs passed.
  • The second head-only failure was test_strided_collectives_perf.py::TestStridedCollectivesPerf::test_all_reduce_perf[1024x1024], with 0.332 ms against a 0.330 ms ceiling. I ran the file 3 times in each arm, and this case failed on base in all 3 runs. On my host the same latency cases fail in both arms.

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. pre-commit run --all-files passes.

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.
@kunind-aws

Copy link
Copy Markdown
Collaborator

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 main? From release-2.34 we only accept PRs to main (contributing guide). Thank you!

@zouchaoqun
zouchaoqun changed the base branch from contribute-2.33 to main December 3, 2026 02:24
@zouchaoqun
zouchaoqun force-pushed the submit/shard-index-contribute-2.33-v2 branch from 3bf0c73 to 9960d2d Compare December 3, 2026 02:24
@github-actions github-actions Bot added the stat:awaiting-requester The author must reply label Dec 3, 2026
@zouchaoqun zouchaoqun closed this Dec 3, 2026
@zouchaoqun zouchaoqun reopened this Dec 3, 2026
@github-actions github-actions Bot added stat:awaiting-reviewers A pull request waits for a maintainer to review and removed stat:awaiting-requester The author must reply labels Dec 3, 2026
@zouchaoqun

Copy link
Copy Markdown
Collaborator Author

@kunind-aws thanks! I retargeted this PR to main and rebased it onto c2c6277 (the 2.34.0 release). The library change is the same as before.

On the new head (9960d2d), the pull_request_target workflows (PR gate, CI approved dispatch, PR Labeler, Turn labels) end in startup_failure with no jobs. A close and reopen gave the same result. Lint and pre-commit pass. Could you help fix this, or start CI when you review?

@kunind-aws

kunind-aws commented Dec 3, 2026 •

Copy link
Copy Markdown
Collaborator

Assigning @vthkumar-aws to help review the PR

On the new head (9960d2d), the pull_request_target workflows (PR gate, CI approved dispatch, PR Labeler, Turn labels) end in startup_failure with no jobs

I'll take a look. Thank you for bringing this up!

@github-actions github-actions Bot added stat:awaiting-requester The author must reply and removed stat:awaiting-reviewers A pull request waits for a maintainer to review labels Dec 3, 2026

@vthkumar-aws vthkumar-aws left a comment

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.

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.

Comment on lines +152 to +174
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"]))

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.

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.

Comment on lines +100 to +110
# 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.

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.

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.

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

Labels

module:dynamo Touches Dynamo backend stat:awaiting-requester The author must reply

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants