Skip to content

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

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

zouchaoqun wants to merge 2 commits into
aws-neuron:contribute-2.33from
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)

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

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

Labels

module:dynamo Touches Dynamo backend

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants