Skip to content

Extending the stack: ATen lowerings, patch registry, plugins

45 min read

Prerequisites: Custom kernels with Pallas, Correctness: parity gates and numerical checks

Sooner or later the stack is missing something your model needs. A layer calls an ATen op that has no TPU lowering and the run stops. An upstream vLLM function assumes CUDA. A new architecture has to train in TorchTitan's TPU lane. You want the router to prefer a different replica. Each of these has a proper fix, and it is almost never a local monkey-patch in your own script. Each of the five repositories in this book (torch_tpu, vLLM-TorchTPU, SGLang-TorchTPU, TorchTitan and the llm-d router) has a designated place for extensions, a registration mechanism, tests that prove the change and a CI gate that keeps it working. This chapter maps those places, shows how an ATen op reaches the TPU and what happens when it cannot, and walks through each repository's mechanism and contribution workflow, with the exact commands from its own guides. The order of work is fixed, and it is chapter 23's order: write the parity test first, make the smallest change at the layer that owns the defect, prove that the change is exercised, and only then claim speed. The chapter ends with a design exercise: add a missing op to torch_tpu end to end.

What this chapter covers

  • Which repository and extension point own a given gap, and why a fix one layer higher only works around it.
  • The change set that adds an ATen lowering to torch_tpu: op files, registration, the list of known unregistered ops, op tests against the CPU, and the check that CI runs them on a TPU.
  • vLLM-TorchTPU's patch registry: lifecycle stages, the False-means-retry contract, refresh targets for stale bindings, and testing a patch on a CPU.
  • llm-d EPP scheduling profiles that weight a custom scorer against the built-in ones, and the endpoint they pick.
  • Each repository's contribution path: build, tests, type checks, CI labels, review and sign-off rules.
  • Parity-first test plans with negative controls that show an extension computes the right thing and is exercised, before any performance claim.

A map of the extension points

Three rows of dashed containers. Top row, centred: a purple dashed container labelled llm-d EPP holding two purple blocks, Filter plugin and Scorer plugin. Middle row, left to right: an amber dashed container labelled TorchTitan TPU lane holding an amber block Model wrapper and a teal block StateDictAdapter; an amber dashed container labelled vLLM-TorchTPU holding an amber block Patch registry and a blue block register_oot layer; an amber dashed container labelled SGLang-TorchTPU holding an amber block HookRegistry hook and a blue block Backend registry. Bottom row: a wide blue dashed container labelled torch_tpu holding two blue blocks, ATen lowering and jax_op kernel. Two arrows labelled routes to run down from the llm-d EPP container to the vLLM-TorchTPU and SGLang-TorchTPU containers. Three arrows labelled runs on run down from the TorchTitan, vLLM-TorchTPU and SGLang-TorchTPU containers to the torch_tpu container.

Every engine stands on torch_tpu. A missing ATen op is therefore fixed once at the bottom, in an ATen lowering, not patched separately in each engine above it. Each box inside a container is a door that repository has built for extensions; the sections below take them one at a time.

The map is also a rule about where a fix belongs. vLLM-TorchTPU's coding guidance says it plainly: "When the defect is upstream, fix it upstream (vLLM, torch-tpu, JAX)", with a local workaround acceptable only alongside a filed upstream fix and a TODO that references it (R-3.4). SGLang-TorchTPU's contributing guide says the same about its own fork: generic engine changes go upstream first, and a core change the TPU needs is made through the first of an existing platform method, a registry, subclass-and-override, or a small upstream "seam" PR carried as a hook until it merges. TorchTitan's onboarding skill puts every TPU change under torchtitan/experiments/tpu/ and treats a change outside it as an exception that needs a written reason. The pattern in all three is the same: the extension point is a door; anything else is a workaround that someone will have to remove.

Repository What you add Where the code goes How it is registered The test that proves it
torch_tpu An ATen op lowering csrc/ops/<op>/<op>_aten_kernels.{h,cc} and a BUILD ImplStable<OpName::kFoo>(m, AtenFoo) in TORCH_LIBRARY_IMPL(aten, PrivateUse1, m), csrc/eager/tpu_aten_kernels.cc tests/ops_unit_test.py (assert_close_tpu_vs_cpu), tests/ops_test.py (GPU goldens)
torch_tpu A TPU custom op C++ op registered as torch.ops.tpu._foo, re-exported as torch.tpu.ops.foo ImplInternal, ImplExperimental, ImplStable or ImplDeprecated Op tests plus the API-stage checks
any repo A Pallas kernel The repo that uses it; in vLLM-TorchTPU, kernels/ with no torch imports jax_op (chapter 12) Interpreter and TPU parity, verify
vLLM-TorchTPU A TPU layer or a fix to upstream behaviour layers/adapter/, models/vllm/<model>_patch.py, or the module that owns it register_oot / CustomOp first; else one Patch entry in PATCHES, src/vllm_torchtpu/patch_registry.py Behaviour tests plus tests/platforms/test_patch_registry.py
SGLang-TorchTPU A TPU backend change sglang_tpu/ only Platform method or registry from init_backend(); else a HookRegistry hook in sglang_tpu/hooks/ A registered test (register_tpu_ci)
TorchTitan TPU lane A model experiments/tpu/<name>/ (wrap) or experiments/tpu/examples/<name>/ (port) Import in experiments/tpu/train.py and train_minimal.py The reference-parity test on BaseAcceleratorDeviceTest
llm-d router A routing policy A Go plugin in the router's pkg/epp/framework/plugins/scheduling/ tree A plugins entry and a pluginRef with a weight in EndpointPickerConfig A scheduling decision you can observe in the EPP's metrics

When you are not sure which row you are in, this is the order to ask the questions in:

A decision tree of six white rounded questions down the left, each No leading down to the next and each Yes leading right to a blue card that names the repository and its extension point. Does an ATen op raise NotImplementedError? Yes: torch_tpu: add an ATen lowering. Correct but slow, and would a fused kernel help? Yes: Pallas kernel via jax_op, in the repo that uses it. Does upstream vLLM code misbehave on TPU? Yes: vLLM-TorchTPU: register_oot or CustomOp, else PATCHES. Does upstream SGLang code misbehave on TPU? Yes: SGLang-TorchTPU: platform method or registry, else seam PR and hook. Must a new model train on TPU? Yes: TorchTitan TPU lane: wrap or port. Should requests go to other replicas? Yes: llm-d EPP: filter or scorer plugin. No leads down to a grey card: None of these: fix it in the project that owns the code.

Ask the questions in this order and stop at the first Yes: a gap low in the stack is fixed once in the layer that owns it, not worked around in every layer above. The table above gives each card's directory, registration and test.

If no question fits, the gap is not at one of these extension points: fix it in the project that owns the code (torch_tpu, vLLM, SGLang, JAX), as R-3.4 asks, and carry a local workaround only with that fix filed and a TODO that references it.

How an ATen op reaches the TPU, and what happens when it cannot

torch_tpu is an out-of-tree PyTorch backend. It registers a C++ backend under the dispatcher key PrivateUse1, and when the wheel autoloads it renames that key to tpu (docs/how_torchtpu_works.md). Every ATen op on a TPU tensor is therefore looked up in the PrivateUse1 slot of the dispatcher, and the table that fills that slot is one block in csrc/eager/tpu_aten_kernels.cc. At torch_tpu commit f2aa01706 (2026-11-04) the block registers 685 ATen ops, every one with the same line shape:

// csrc/eager/tpu_aten_kernels.cc
TORCH_LIBRARY_IMPL(aten, PrivateUse1, m) {
  // All entries should be registered by ImplStable() as we don't want to
  // generate any warning for standard aten ops.
  // go/keep-sorted start
  ImplStable<OpName::kAbsOut>(m, AtenAbsOut);
  ...
  ImplStable<OpName::kHardswish>(m, AtenHardswish);
  ...
  ImplStable<OpName::kXlogyOutTensor>(m, AtenXlogyOutTensor);
  // go/keep-sorted end
}

OpName is an enum in csrc/ops/op_names.h, and a ToString switch in the same header maps kHardswish to the schema name "hardswish". ImplStable is a template defined at the top of tpu_aten_kernels.cc that calls m.impl with that name; its siblings ImplInternal, ImplExperimental and ImplDeprecated are for TPU custom ops and add the stage warnings of the API policy. A standard ATen op always uses ImplStable.

The kernel itself lives in its own directory. Here is the core of csrc/ops/hardswish/hardswish_aten_kernels.cc, trimmed:

absl::StatusOr<mlir::MlirOp> BuildHardswishShlo(mlir::MlirOp input_op) {
  auto type = GetTensorTypeOrDie(input_op);
  TT_ASSIGN_OR_RETURN(auto element_type,
                      ConvertTo<mlir::ElementType>(type.getElementType()));
  mlir::MlirOp three = MakeConstantLike(input_op, 3.0, element_type);
  mlir::MlirOp six = MakeConstantLike(input_op, 6.0, element_type);
  mlir::MlirOp zero = MakeConstantLike(input_op, 0.0, element_type);
  mlir::MlirOp x_plus_3 = mlir::stablehlo::Add(input_op, three);
  mlir::MlirOp relu6 = mlir::stablehlo::Clamp(zero, x_plus_3, six);
  mlir::MlirOp num = mlir::stablehlo::Mul(input_op, relu6);
  return mlir::stablehlo::Div(num, six);
}

at::Tensor AtenHardswish(const at::Tensor& self) {
  TT_KERNEL(OpName::kHardswish, _, (self), {
    TT_CHECK_THROW(self.is_floating_point(), error::kInvalidArgument)
        << "expected the input dtype to be floating point, got "
        << ToString(self.scalar_type());
    TT_ASSIGN_OR_THROW(
        at::Tensor result,
        UnaryOp(self, BuildHardswishShlo,
                {.op_param_cache_keys = OpParamCacheKeys::Empty()}));
    return result;
  });
}

Two functions, two jobs. BuildHardswishShlo is a StableHLO builder: given an MLIR value for the input it emits add, clamp, multiply and divide. AtenHardswish is what the dispatcher calls: it validates the arguments with error messages that say what was expected, and hands the builder to a helper (UnaryOp here; BinaryOpOut for a binary op such as xlogy.OutTensor) that does not run anything yet. As chapter 4 described, the result is a deferred op: an at::Tensor whose storage points at a StableHLO builder and the static parameters for its cache key. At a synchronization point, the runtime analyzes the region of deferred ops, fingerprints it, fetches the executable from the compilation cache or compiles it with XLA, and dispatches it.

torch.compile(backend="tpu") does not use a second set of lowerings. The torch_tpu docs say the backend traces the FX graph "as if we were in eager mode, but with all ops deferred and no execution on the TPU", then compiles one StableHLO program for the whole graph. One lowering serves both modes, which is also why one missing lowering breaks both.

A flow chart. Two amber entry blocks at the top, Eager: F.hardswish(x) with x on torch.device("tpu"), and torch.compile(backend="tpu") with FX graph traced as eager, ops deferred, both point down to a purple block PyTorch dispatcher, dispatch key PrivateUse1, renamed "tpu". A blue arrow labelled kernel registered goes left to a blue block TORCH_LIBRARY_IMPL(aten, PrivateUse1, m), ImplStable<OpName::kHardswish>(m, AtenHardswish), csrc/eager/tpu_aten_kernels.cc; then down to AtenHardswish(self), TT_KERNEL + UnaryOp(self, BuildHardswishShlo), stablehlo Add, Clamp, Mul, Div, csrc/ops/hardswish/hardswish_aten_kernels.cc; then to a teal block DeferredOp, StableHLO builder + cache-key params, returned as an at::Tensor; then to At a sync point, fingerprint, compilation cache, XLA compile, one program for the region or FX graph; then to a green block TPU executable runs. An orange arrow labelled no kernel goes right to an orange block TORCH_LIBRARY_IMPL(_, PrivateUse1, m), m.fallback(TpuMissingOpFallback); then to a grey decision block enable_cpu_fallback?, torch_tpu._internal.execution_mode, internal knob, default False. Its False branch leads to an orange block NotImplementedError (default): operator 'aten::linalg_matrix_exp' is not implemented for TPU. Please file a feature request. Its True branch leads to an amber block ABSL_LOG(WARNING) ... Falling back to CPU, at::native::cpu_fallback(op, stack), the CPU kernel runs on host copies.

Follow the left column for an op that is registered: the dispatcher finds ImplStable, the kernel builds StableHLO, and nothing runs until a sync point compiles the region. The right column is the only other way out of the dispatcher, and by default it ends in an error, not on the CPU.

When no kernel is registered

The same file registers a catch-all for every op that has no entry:

// csrc/eager/tpu_aten_kernels.cc, trimmed
void TpuMissingOpFallback(const c10::OperatorHandle& op,
                          torch::jit::Stack* const stack) {
  const auto& op_name = op.schema().operator_name();
  if (!IsCpuFallbackEnabled()) {
    TT_CHECK_THROW(false, error::kPythonNotImplementedError)
        << "operator '" << op_name
        << "' is not implemented for TPU. Please file a feature request";
  } else {
    ABSL_LOG(WARNING) << "operator '" << op_name
                      << "' is not implemented for TPU. Falling back to CPU";
    at::native::cpu_fallback(op, stack);
  }
}

TORCH_LIBRARY_IMPL(_, PrivateUse1, m) {
  m.fallback(
      torch::CppFunction::makeFromBoxedFunction<&TpuMissingOpFallback>());
}

The comment above it explains the intent: the CPU fallback "is mostly for testing and debugging", so that models keep running while an op is missing, and "By default, the fallback is disabled." The flag behind IsCpuFallbackEnabled() starts false, and the Python switch for it lives in an internal module, torch_tpu._internal.execution_mode, whose enable_cpu_fallback property sets it for the whole process (a test in tests/execution_mode_test.py checks that it is global across threads). torch_tpu's own error test shows the default:

# tests/tpu_errors_test.py, trimmed
execution_mode.enable_cpu_fallback = False
# raises: operator 'aten::linalg_matrix_exp' is not implemented for TPU.
#         Please file a feature request
torch.ops.aten.matrix_exp(x)

So the common belief that unsupported ops "silently fall back to the CPU" is wrong for torch_tpu as shipped: an unsupported op raises NotImplementedError (a subclass of RuntimeError) and names itself. The slow path appears only when someone turns the internal knob on, and then every call logs a WARNING with the op's name and runs the CPU kernel on host copies of its inputs. If you inherit a training script that is mysteriously slow, search its logs for Falling back to CPU before you open a profile.

Three more mechanisms decide whether an op needs its own entry.

  • Out-variants carry the functional ops. Most torch_tpu registrations are out= variants: abs.out, add.out, mm.out, xlogy.OutTensor. PyTorch builds the functional and in-place forms of these structured ops from the out variant through a CompositeExplicitAutogradNonFunctional kernel, so registering add.out makes add.Tensor work. (You can see the kernel with torch._C._dispatch_has_kernel_for_dispatch_key("aten::add.Tensor", "CompositeExplicitAutogradNonFunctional"), which returns True on torch 2.15.0.)
  • Composite ops decompose. Ops such as t, expand and permute have CompositeExplicitAutograd kernels and decompose into other ops before they reach the backend.
  • A lowering may not delegate. Inside TT_KERNEL, a new op must build StableHLO itself. csrc/common/op_name_stack.cc keeps a list of 148 legacy ops that are allowed to call other TPU ops, with a check that crashes if the list grows ("DO NOT fix this crash by increasing the expected size!"), and a fatal CompositeOpCheck error for any other op that decomposes into another: "please implement the ... op by lowering it to SHLO instead." A lowering that calls at::add inside its kernel is rejected at run time, not in review.

Finding the gaps before you hit them

torch_tpu keeps its own record of the gap. tests/native_functions_data.py lists, in UNREGISTERED_OPS, the ATen ops that PyTorch's registration declarations say a backend must register and torch_tpu does not yet: 362 entries at commit f2aa01706, including logaddexp.out and linalg_matrix_exp. tests/native_functions_test.py maintains the invariant "ops requiring registration + overrides = registered ops + unregistered ops", reading the registered side from torch._C._dispatch_get_registrations_for_dispatch_key("PrivateUse1"). Its BUILD rule gives it PyTorch's RegistrationDeclarations.h only outside the open-source build (if_oss([], [...])), so in a GitHub checkout it skips; the list still has to be kept exact, because the change is tested again after the Copybara import.

You do not need a TPU to find out whether your model will hit one of those 362. code/ch25_extending/missing_op_check.py traces a model's forward and backward to ATen ops on the CPU with make_fx, and classifies each op against a list of registrations as registered, via_out (built from a registered out variant), composite (decomposes on the backend) or missing. The list it ships, data/torch_tpu_privateuse1_aten_ops.txt, was read from the TORCH_LIBRARY_IMPL(aten, PrivateUse1, m) block of the source by registrations_from_source.py. Its demo model is a small block with two ops that torch_tpu lists as unregistered: torch.logaddexp, which SGLang-TorchTPU's ring-attention log-sum-exp merges use, and torch.linalg.matrix_exp, the op torch_tpu's own error test uses. The CPU smoke run prints, trimmed:

DemoBlock forward + backward vs torch_tpu_privateuse1_aten_ops.txt (685 ops)
op                                calls  status      detail
aten::linalg_matrix_exp               2  missing
aten::logaddexp                       1  missing     needs one of: aten::logaddexp.out
aten::t                               6  composite   decomposes on the backend
...
aten::add.Tensor                      2  via_out     aten::add.out
aten::gelu_backward                   1  via_out     aten::gelu_backward.grad_input
aten::mm                              4  via_out     aten::mm.out
...
aten::gelu                            1  registered
aten::native_layer_norm               1  registered
summary: registered 6, via_out 13, composite 8, missing 2
clean model (Linear, GELU, LayerNorm, fwd+bwd): 0 missing
cpu-smoke: OK

Read it from the top. Two ops are missing, and the detail column names the registration that would close each gap: for logaddexp it is the out variant, logaddexp.out, exactly the entry in UNREGISTERED_OPS. The script exits 1 when anything is missing, so it can gate a CI job that runs on CPU. The source-derived list is good enough to plan with; the authority is the list from the process you will run in, which you get on a TPU VM with missing_op_check.py --dump-registrations tpu_ops.txt, and then a run on the TPU with the fallback off, which raises on the first op the trace missed.

Adding an ATen lowering to torch_tpu

A recent commit shows the whole change set for one op. Commit 6b693afb3, "Implement native StableHLO lowering for aten::linalg_cholesky_ex.L", touched twelve files:

File What changed
csrc/ops/linalg/cholesky/BUILD, linalg_cholesky_kernels.h, .cc New: a torch_tpu_cc_library, the Aten... declaration, the builder and kernel
csrc/ops/op_names.h kLinalgCholeskyExL in the enum and "linalg_cholesky_ex.L" in ToString, both in keep-sorted blocks
csrc/eager/tpu_aten_kernels.cc The #include and ImplStable<OpName::kLinalgCholeskyExL>(m, AtenLinalgCholeskyExL);
csrc/eager/BUILD The new library added to the tpu_aten_kernels deps
tests/native_functions_data.py 'linalg_cholesky_ex.L' removed from UNREGISTERED_OPS
tests/ops_unit_test.py New tests comparing the TPU with the CPU
tests/ops_test.py do_test_op("linalg.cholesky_ex", ...) against GPU goldens, with an accuracy override
tests/goldens.pin Re-pinned GPU golden files
tests/errors_test.py Tests of the error messages
tests/dynamism_test_utils.py Two deny-list entries for dynamic shapes

That is the pattern. In order:

  1. Write the kernel directory. Copy the shape of an op like yours: hardswish/ for unary, xlogy/ for a binary op with broadcasting (its builder calls ApplyBroadcastIfNeeded and its kernel BinaryOpOut with .force_float_inputs = true). The builder emits StableHLO with mlir::stablehlo::* calls; the kernel validates inputs with TT_CHECK_THROW and wraps everything in TT_KERNEL(OpName::kFoo, ...). Do not call other ATen ops inside it: the composite-op check above is fatal.
  2. Name the op in op_names.h, enum and ToString, keeping both sorted.
  3. Register it with ImplStable in the dense PrivateUse1 block, add the include and the Bazel dep.
  4. Remove it from UNREGISTERED_OPS, or the registration invariant breaks.
  5. Test it against the CPU. tests/ops_unit_test.py tests use self.assert_close_tpu_vs_cpu(compute), where compute(device) builds the inputs on a device and returns the result; the helper runs it on both and also checks that an exception on one side is matched on the other. The hardswish tests are the pattern: parameterize over float32 and bfloat16, scale the inputs so every branch is hit (* 5 covers both sides of -3 and 3), test the functional, in-place and out= forms and the backward, and give bf16 an explicit tolerance. Then add ops_test.py's OpInfo-driven do_test_op, which compares against goldens recorded on a GPU.
  6. Build and run. The README's wheel build is bazel build --config=wheel_common //ci/wheel:torch_tpu_wheel, with --config=no_rbe appended if you have no remote-build credentials (order matters: no_rbe must come after wheel_common), and -c dbg ... --//:allow_unoptimized_wheel=True for a debug build. Tests are Bazel targets: bazel test //tests:ops_unit_test --test_filter=<test name> on a TPU VM (the target's run_on_accelerators names v6e and v5e). CI runs bazel test --config=<job> //....
  7. Confirm CI runs your tests. python ci/tools/list_ci_tests.py --test=//tests:ops_unit_test lists the CI jobs whose tag filters select a target, without running anything; --jobs=ci_tpu_v7_presubmit lists a job's targets. The guide's example shows why this matters: a tag such as presubmit-v7 is what pulls a target into a presubmit job, and without it the target runs only after merge.

A TPU custom op, as opposed to an ATen op, follows the API design guide instead: register it in C++ as torch.ops.tpu._foo with a leading underscore, and re-export it in torch.tpu.ops as foo = torch.ops.tpu._foo, so that it has one public path. New public APIs start internal or experimental, never stable (CONTRIBUTING.md, "Stability Lifecycle").

The contribution path. torch_tpu's CONTRIBUTING.md asks for a signed Google CLA, an issue before anything "more complicated than trivial fixes", small PRs ("A concise 100-line diff gets reviewed far faster than a 1,000-line rewrite"), and a link to the issue in every non-trivial PR; AGENTS.md adds that a PR body is built from .github/pull_request_template.md with its ## Description and ## Test Plan headings. Review runs through Google's Copybara: an oncall triages the PR and adds a domain expert, the domain expert approves and adds a quality champion as reviewer and assignee, and the champion approves and applies the pull ready label, which turns the PR into an internal change. Copybara then closes the PR and lands the commit on main separately, so the PR never shows as merged. On AI assistance the policy is that "The author is fully responsible for the code they submit", that you may add an Assisted-by: trailer, and that "AI assistants should not be considered co-authors on any commits".

Patching a serving engine: vLLM-TorchTPU's patch registry

vLLM-TorchTPU is "a vLLM platform plugin, not a fork" (coding guidance, section 2). vLLM installs as a plain wheel, and the plugin enters through Python entry points declared in its pyproject.toml: vllm.platform_plugins (torchtpu = "vllm_torchtpu.platforms:register_tpu_platform") and vllm.general_plugins (torchtpu_layers = "vllm_torchtpu.layers:register_layers"). Before you reach for a patch, use vLLM's own extension points: R-3.5 lists "vLLM's plugin hooks, register_oot registration, AttentionBackendEnum registration", and R-3.1 sets the search order "vLLM upstream, then vllm-torchtpu, then JAX/Pallas utilities, then write it", subclassing the deepest applicable vLLM class and overriding only what differs on TPU.

When none of those reaches the code that has to change, the change becomes one entry in the registry. Every runtime patch of upstream code is declared in the ordered PATCHES tuple in src/vllm_torchtpu/patch_registry.py, and the plugin's lifecycle entry points call apply(stage, model_config=...) to install them:

Stage Called from Use
import env_override.py, after early environment setup Import-time prerequisites; keep it light, it must not load TorchTPU or resolve vLLM's platform
platform_activation TpuPlatform.check_and_update_config Shared TPU patches, and model patches with vllm_config.model_config
engine_core _run_engine_core_with_tpu_patches Scheduler, KV-cache, offloading and multimodal patches in the engine-core process
worker_init TPUWorker.__init__, before WorkerBase.__init__ Shared patches in each worker, including spawned workers
model_load TPUWorker.load_model, before the runner loads the model Model-specific patches with self.model_config

These are entry points in different processes, "not a sequence that every process necessarily executes", which is why most entries name two or three stages. _ACTIVE is ("platform_activation", "worker_init"), because "Parent platform activation alone does not cover a spawned worker"; _ENGINE adds engine_core for patches the scheduler process also reads. At commit fab09bd7a the tuple holds 47 entries: 29 use _ACTIVE, 13 use _ENGINE, 4 are model-specific with ("platform_activation", "model_load"), and one runs at import.

An entry is a frozen dataclass with four fields:

@dataclass(frozen=True)
class Patch:
    target: str                     # "module:callable", or a bare module imported for side effects
    stages: tuple[Stage, ...]       # where the entry is eligible
    model_config: bool = False      # pass model_config=... (possibly None) to the callback
    refresh: str | None = None      # lazy target called on later eligible stages once complete

and apply keeps a contract you have to design against:

  • Tuple order is application order within a stage, so a patch that builds on another comes after it.
  • Completion is keyed by the target string and kept for the process. Only the literal False leaves an entry eligible for another attempt; None, including "this model is not mine", marks it complete. A model patch that returns None for the wrong model will never run for the right one in that process.
  • An exception propagates and stops that stage's pass; earlier completions stay recorded, the failing entry stays eligible, and nothing is rolled back. A callback that can fail halfway must be safe to run again.
  • Refresh handles late bindings. A module that did from upstream import fn holds its own reference, which replacing upstream.fn does not update. A refresh target runs on every later eligible apply, so it must be idempotent.
  • Processes. Spawned processes start with an empty registry; forked ones inherit the installed patches and the completion records. One RLock serializes application, and re-entering a stage that is already being applied returns at once.
  • The log line is not evidence. Completed TPU patch callbacks at <stage>: ... lists completed callbacks, and completion "includes permanent no-ops, so this log does not prove that a wrapper was installed or a feature was exercised".

A model-specific patch follows a fixed recipe from the developer guide: put the callback in src/vllm_torchtpu/models/vllm/<model_name>_patch.py, accept model_config, return False when it is None or does not match, apply the patch and return None when it does, and append the entry under # Model-specific patches with ("platform_activation", "model_load") and model_config=True. The Qwen2 patch is a complete example:

# src/vllm_torchtpu/models/vllm/qwen2_patch.py
def maybe_patch_qwen2(model_config: Optional["ModelConfig"] = None) -> bool | None:
    if model_config is None or "Qwen2ForCausalLM" not in (
        getattr(model_config, "architectures", None) or []
    ):
        return False

    import vllm.model_executor.models.qwen2 as qwen2_mod

    from vllm_torchtpu.models.vllm.qwen2 import TPUTPPaddedQwen2Attention

    qwen2_mod.Qwen2Attention = TPUTPPaddedQwen2Attention
    logger.info("Applied TPU patch: Qwen2 GQA query-head padding attention.")
    return None

Notice that the imports are inside the callback, so the registry module stays cheap to import and the import stage never pulls in vLLM's model code.

An animation in eleven frames. Each frame has a PATCHES panel on the left listing three entries, patch_rmsnorm_forward with _ACTIVE, patch_rms_norm_function with _ENGINE and a refresh target, and maybe_patch_llama with (platform_activation, model_load) and model_config=True, each with a status chip; and a panel on the right, What upstream code now calls, with four rows: layernorm.RMSNorm.forward_oot, models.llama rms_norm binding, models.qwen rms_norm binding and models.llama.LlamaAttention.forward, each showing upstream original, TPU implementation or not imported yet. Frame 1: nothing patched. Frames 2 to 4: apply("platform_activation", model_config=None) applies the first two entries, turning RMSNorm.forward_oot and the llama binding to TPU, while maybe_patch_llama returns False and shows retry later. Frame 5: the completion log line. Frame 6: models.qwen is imported later and holds the upstream original, shown in orange. Frame 7: apply("engine_core") runs the refresh target and the qwen binding turns TPU. Frame 8: apply("worker_init") skips completed entries and notes that a spawned worker starts with an empty registry. Frame 9: apply("model_load", model_config=llama) applies maybe_patch_llama and LlamaAttention.forward turns TPU. Frame 10: a second model_load runs nothing, because completion is per target. Frame 11: unpatch(), the book's addition, restores the 5 recorded originals.

Watch the right-hand panel: each green row appears only when an entry's stage comes round (four of the table's stages, in the order one process reaches them; import comes before them all). The orange row in frame 6 is the late-binding problem, and frame 7 is the refresh that fixes it. The companion registry records the same events, so you can replay them on a laptop.

The companion code/ch25_extending/registry.py reproduces this contract in plain Python, so you can design and test a patch on a laptop with no vLLM installed. Its --cpu-smoke run walks a fake upstream engine through the stages, and its output is the animation above in text form:

apply('platform_activation')               completed: patch_rmsnorm_forward, patch_rms_norm_function
    RMSNorm.forward_oot=TPU  llama.rms_norm=TPU  LlamaAttention.forward=upstream
late import of models.qwen                 completed: -
    ...  qwen.rms_norm=upstream
apply('engine_core')                       completed: -
    ...  qwen.rms_norm=TPU
apply('model_load', model_config=llama)    completed: maybe_patch_llama
    RMSNorm.forward_oot=TPU  llama.rms_norm=TPU  LlamaAttention.forward=TPU  qwen.rms_norm=TPU

It adds two things the real registry does not have, and says so: a register() helper (in vLLM-TorchTPU you edit the tuple) and swap()/unpatch(), which record and restore originals. The real registry never rolls back; its tests load a fresh copy of the module for each test instead.

Testing a patch. Two test files change with every new entry. The behaviour test lives with the patch implementation. The registry test, tests/platforms/test_patch_registry.py, holds manifest assertions on stages and dependencies, and tests for retry, refresh, model selection, process state, concurrency and import order; the guide's command is pytest -q tests/platforms/test_patch_registry.py. For a change to where a patch runs, the guide also asks you to verify the startup path itself, "including spawned workers when applicable".

The contribution path. From the contributing, testing and type-checking guides:

# Every commit carries a DCO sign-off
git commit -s

# Install for development (uv): CPU torch, vLLM from source
export UV_TORCH_BACKEND=cpu
VLLM_TARGET_DEVICE="empty" uv pip install -e . --group vllm
uv pip install --prerelease=allow -e . --group vllm --group test   # test dependencies

# Hooks: ruff, pyrefly (no third-party packages), env-read and kernel checks
pre-commit install --hook-type pre-commit --hook-type commit-msg
pre-commit run --all-files

# Full-environment type check against real torch, jax and vllm (Docker, no TPU)
bash tools/typecheck_full.sh

# CPU unit tests, exactly as CI runs them
JAX_PLATFORMS=cpu pytest tests/ -m "not tpu_test and not multichip and not nightly"

Type-checking runs twice, against two baselines: .pyrefly-baseline.json for the pre-commit hook, where every import of torch, jax or vLLM is Any, and .pyrefly-baseline-full.json for the full check. A change may only delete baseline entries; "An added entry means your change introduced that error; fix it instead." Tests that need a TPU carry @pytest.mark.tpu_test (one v7x chip in CI) or multichip; an unmarked test runs on a CPU pod, and module imports must work on a CPU because pytest collects before it filters. TPU CI on Buildkite runs only after a maintainer applies the ready label, and on a PR from a fork every push removes it again. PRs over 500 lines of core logic need an RFC issue first. PR titles take a prefix such as [Kernel] or [Model]. The AI policy differs from torch_tpu's: vLLM-TorchTPU asks you to disclose AI help in the PR description and to add Co-authored-by: trailers for the tools next to your sign-off.

Extending SGLang-TorchTPU: platform, hooks and the ratchet

SGLang-TorchTPU is in the middle of a migration, and the migration decides where your code goes. The plugin is sglang_tpu/, discovered through the sglang.srt.platforms entry point (tpu_oot = "sglang_tpu:activate" in the plugin's pyproject.toml), and "All new TPU code goes here". The engine still runs on a fork of SGLang in python/, synced weekly, because some TPU behaviour still lives in is_tpu() branches in shared engine code. Each branch is being moved out. The contributing guide gives the order of choices for a core change the TPU needs:

Two rows of boxes. Top row, left to right, three white numbered cards joined by arrows labelled else: 1, Platform, existing SRTPlatform method or capability flag; 2, Registry, filled from init_backend(); 3, Subclass, and override through a factory. From card 3 an arrow labelled else runs down, left along the gap between the rows and down into card 4 at the start of the second row: 4, Seam PR, under about 300 lines, no TPU code, CPU test. An arrow labelled meanwhile leads right to a grey box, Carried as a hook, sglang_tpu/hooks/. An arrow labelled seam synced leads right to a green card, Cleanup PR, deletes the hook.

Use the first choice that reaches the code. Only the last one changes upstream, and the hook it needs in the meantime is debt with an end: once the seam arrives with the weekly sync, a cleanup PR deletes it.

The registries are filled through register_attention_backend, register_oot_forward and get_quantization_config; the hook's header links the seam PR, and the cleanup PR follows once the weekly sync brings the seam into the fork.

Hooks go through SGLang's HookRegistry (python/sglang/srt/plugins/hook_registry.py), which takes a dotted target and one of four hook types: BEFORE (may change the arguments), AFTER (may change the return value), AROUND (wraps the original with full control) and REPLACE (swaps a function or a whole class; a class may only be replaced, not wrapped). sglang_tpu/hooks/__init__.py collects them in a HOOKS list and registers them only when current_platform.is_tpu(). One difference from vLLM-TorchTPU is worth knowing when you port a patch between the two: SGLang's registry propagates a replaced function to every module in sys.modules that still holds a stale from X import Y binding, while vLLM-TorchTPU asks you to write a refresh target.

The ratchet keeps the migration moving. tools/plugin/check_tpu_branches.py, run by pre-commit, "rejects any PR that raises a per-file count of is_tpu branches or sglang_tpu imports in core", against tools/plugin/tpu_debt_baseline.json; lowering a count is "always welcome" with --write-baseline, raising one needs a linked upstream seam and a maintainer's approval. tools/plugin/inventory.py lists every hook and runtime patch, and its docstring states the policy: "Both counts are migration debt and only go down". tools/plugin/scoreboard.py prints the full set of counts, and tools/plugin/gate_audit.py checks the is_out_of_tree() gates for the out-of-tree mode.

The contribution path. Install both distributions (pip install -e python/, then pip install --no-deps -e .) and pre-commit. CPU unit tests run with python3 test/run_suite.py --hw cpu --suite base-a-test-cpu; the kernel suite needs a TPU (--hw tpu --suite stage-a-test-tpu-unit); the single-host end-to-end PR gate needs a 4-chip TPU7x host (--suite stage-b-test-tpu-4-v7). Every TPU test file starts with a register_tpu_ci(...) marker naming its suite and labels, and SUPPORT_MATRIX.md is generated from those markers (python3 scripts/ci/tpu/support_matrix.py --strict --check SUPPORT_MATRIX.md), so "a feature counts as supported only when a registered test backs it". A new kernel ships with a correctness test against a reference, a new feature with a registered end-to-end test. TPU tests run on request: an authorized user adds the run-ci label and comments /tag-and-rerun-ci.

Adding a model to TorchTitan's TPU lane

TorchTitan's TPU lane is torchtitan/experiments/tpu/, and its model onboarding skill (.claude/skills/tpu_model_onboarding/) is the procedure. Onboarding "is a ladder". Rung 1 makes the model correct on the plain SDPA path and trains it end to end, as a PR of its own, "because everything later is measured against it". Each later rung is "one feature behind one flag, with one parity test and one end-to-end case, as one commit" (Muse Glimmer's onboarding is the worked example the skill cites, commit 8be9902531 and its rung commits).

Three decisions come before any code. Where does it run (this TPU VM, a VM over ssh, or GKE)? What is the reference and how do the weights arrive (HF transformers in-process on the CPU is the common case; Megatron, MaxText or custom code usually needs a script that dumps weights, tokens, logits, loss and gradients for the test to consume)? And wrap or port: if upstream TorchTitan has the model, add only experiments/tpu/<name>/ with a registry wrapper, config_registry.py, infra/parallelize.py and tests/; otherwise port it under experiments/tpu/examples/<name>/, subclassing torchtitan/models/common/ rather than copying it. A port writes a StateDictAdapter subclass with from_hf and to_hf, and the key table goes into the PR description before the code.

Registration is two imports: experiments/tpu/train.py imports the package for its side effects and adds model_spec.name to the tuple that passes the compile mode to the trainer, and train_minimal.py needs the import too. The test that matters is the reference-parity test: identical weights and inputs through the reference and the TorchTitan model, one forward and one backward, logits, loss and every parameter gradient compared at stated tolerances, and the weight mapping checked both ways (no missing keys, no unexpected keys). It is one class on BaseAcceleratorDeviceTest, and chapter 23 used its tolerances. Each later rung adds a parity test against the path it replaces "plus the control that proves the test can fail".

The CI rules are easy to get wrong. CI classifies a test module by the base class of its test cases: BaseDistributedDeviceTest goes to the multi-chip shard (and the file name must end in _distributed.py), BaseAcceleratorDeviceTest to the single-TPU shard, anything else to a CPU shard on a host with no chip. A plain TestCase with a skipUnless(<detect tpu>) lands on the CPU shard and "skips on every run, green". Run touched modules the way CI does, python -m <module> --device=tpu on a chip or --device=cpu, never under bare pytest. The lane has no lint job and no pre-commit config; "CI green" means the shards in .github/workflows/tpu-test.yml. And the PR description is the onboarding record: the ladder table, the numerics class of each rung, and every command.

Writing an llm-d EPP scorer

The llm-d router's Endpoint Picker (EPP) picks a model server for each request through a plugin pipeline (chapter 20). The scheduler runs a Filter, Score, Pick lifecycle inside each scheduling profile, and a ProfileHandler decides which profiles run and merges their results. The extension points are named in the scheduling docs: ProfilePicker (implemented by ProfileHandler), Filter, Scorer, Picker and ProcessResults. A scorer "Assigns a score between 0.0 and 1.0 to each filtered endpoint", and a profile combines its scorers by weight:

\[\text{score}(e) = \sum_i w_i \, s_i(e), \qquad s_i(e) \in [0, 1]\]

The docs' own example: scorer A with weight 2.0 returns 0.8 and scorer B with weight 1.0 returns 0.5, so the endpoint scores \(0.8 \times 2.0 + 0.5 \times 1.0 = 2.1\). The default picker, max-score-picker, takes the highest total.

The built-in plugins live in the llm-d-router repository under pkg/epp/framework/plugins/scheduling/ (scorers in scorer/queuedepth, scorer/prefix, scorer/kvcacheutilization and so on, at tag v1.0.0). A scorer of your own is a Go plugin in that tree. The scheduling docs do not show the Go interface a scorer implements or the registration call that makes a new type name known to the EPP binary, so read both from a built-in scorer at the tag you build against, and copy its structure, its parameter parsing and its tests. Once the binary knows your type, wiring it in is configuration only:

apiVersion: llm-d.ai/v1
kind: EndpointPickerConfig
plugins:
- type: prefix-cache-scorer
- type: queue-scorer
- name: tpu-shape-fit              # your instance name
  type: my-tpu-shape-scorer        # the type your plugin registers
  parameters:
    maxCompiledTokens: 8192        # whatever your plugin parses
schedulingProfiles:
- name: default
  plugins:
  - pluginRef: prefix-cache-scorer
    weight: 2
  - pluginRef: queue-scorer
    weight: 1
  - pluginRef: tpu-shape-fit
    weight: 1

Each plugins entry instantiates a plugin (the name defaults to the type), each pluginRef must name an instance, and the profile above gets max-score-picker injected because it references no picker. The configuration "is not a Kubernetes CRD": the EPP reads it once at startup from --config-file or --config-text, and a change needs a restart. To see that your scorer is doing something, the EPP exports llm_d_epp_plugin_duration_seconds, labelled with extension_point, plugin_type and plugin_name, and llm_d_epp_scheduler_attempts_total with the chosen endpoint; a scorer with a duration histogram and no change in where requests land is a scorer whose scores do not separate the endpoints.

Keep the scores honest. A scorer that returns 1.0 for every endpoint adds the same constant to every total and changes nothing; one that returns values outside \([0, 1]\) breaks the weighting the profile author reasoned about. Test the scorer on a fixed set of fake endpoints with known metrics and assert the order it produces, then check in a cluster that the decision metrics move.

Designing an extension: parity first, then performance

Every extension in this chapter follows the same five steps, and the order is what makes the result trustworthy.

  1. Locate the owner. Use the decision tree above. If the fix belongs in a lower layer, file it there, and if you must carry a workaround meanwhile, give it a removal condition: a TODO with the upstream issue, as R-3.4 and SGLang's seam rule require.
  2. Write the parity test first, with negative controls. Decide the reference (the CPU op, the upstream path, an HF model), the tolerance and where it comes from, and at least one wrong candidate the test must reject. For a new lowering the reference is the CPU op; assert_close_tpu_vs_cpu is built for it. The design exercise below starts here.
  3. Make the smallest change at the extension point. One op, one patch entry, one hook, one rung. vLLM-TorchTPU caps a PR at 500 lines of core logic before it needs an RFC; torch_tpu asks for the 100-line diff over the 1,000-line one; TorchTitan wants one rung per commit.
  4. Prove it is exercised. A green test proves little if the code under test never ran. Each repository has its own evidence, collected in the table below.
  5. Only then, performance. Measure the way chapter 24 does: steady state, compilation excluded, repeated runs, compared against the path you replaced. For a lowering that replaces a CPU fallback the win is usually large and obvious; for one that replaces an existing lowering, it is often not.

On the left, five white numbered cards top to bottom, joined by arrows down. 1, Locate the owner: fix it in the layer that owns the gap. 2, Write the parity test first: with a wrong candidate it must reject. 3, Make the smallest change: one op, patch entry, hook or rung. 4, Prove it is exercised: a green test must have run the code. 5, Only then, performance: steady state, compile excluded, repeats. On the right, a grey dashed container with the step badge 4 before its title, Evidence that it is exercised, holds five white boxes, one per repository: torch_tpu, test in a TPU presubmit job; vLLM-TorchTPU, test fails without the patch; SGLang-TorchTPU, test listed in SUPPORT_MATRIX.md; TorchTitan TPU lane, custom_call kernels in the HLO; llm-d EPP, decisions change with its weight.

The same five steps for every extension, in this order. Step 4 is the one each repository answers differently, and the panel on the right gives one piece of its evidence per repository; the table below lists the rest.

Repository Evidence that the extension is exercised
torch_tpu The op is gone from UNREGISTERED_OPS; missing_op_check.py on the real registration list reports it registered; the model runs with CPU fallback off; list_ci_tests.py --test=... shows the test in a TPU presubmit job
vLLM-TorchTPU A behaviour test that fails without the patch (R-8.2); the patched path observed in a startup that includes spawned workers, not only the "Completed TPU patch callbacks" log; the test marked tpu_test if it needs a chip
SGLang-TorchTPU The test registered with register_tpu_ci and visible in SUPPORT_MATRIX.md; the ratchet counts unchanged or lower
TorchTitan TPU lane The parity test's control fails when the feature is removed; the HLO dump contains the enabled kernels' custom_calls ("Eager log lines do not fire under compile; trust the HLO")
llm-d EPP The plugin's duration histogram is populated and scheduling decisions differ when its weight changes

Failure modes

Symptom Cause Fix
NotImplementedError: operator 'aten::...' is not implemented for TPU No PrivateUse1 kernel; the default fallback raises Find all gaps first with missing_op_check.py; add the lowering, or decompose in your model while it lands
A run is slow and the log repeats Falling back to CPU Someone set enable_cpu_fallback Turn it off; every such op is a missing lowering to file or write
Fatal CompositeOpCheck: Op X is decomposed into Y The new kernel calls another TPU op instead of building StableHLO Emit the StableHLO yourself in the builder
native_functions_test fails after adding an op The op is still listed in UNREGISTERED_OPS Remove it in the same change
The functional op works but out= raises, or the reverse Only one variant registered, and the other has no composite path Register the out variant; check both forms in the unit test
A green op test that never ran on a TPU The target lacks the tag that puts it in a TPU job list_ci_tests.py --test=//tests:<target> before merging
A vLLM patch works in-process but not in multiprocess serving Registered only at platform_activation; spawned workers start with an empty registry Use _ACTIVE, or _ENGINE if the scheduler process reads it
A model patch never applies to the model it targets The callback returned None for an earlier, non-matching or missing config, and completion is keyed by target Return False until the config matches
A patched function is still the old one in some module The module took a from X import fn binding before the patch Add a refresh target that rebinds idempotently (vLLM); SGLang's registry does this for its hooks
AttributeError at startup after a vLLM or SGLang upgrade The patch targets a symbol upstream renamed or moved Pin the version (R-2.5: pins are load-bearing), fix the patch, and check whether the upstream change makes it unnecessary
A stopgap keeps running after the real fix shipped No removal condition Give every stopgap an issue link and delete it when the pin advances
A new pyrefly baseline entry in the diff The change introduced a type error Fix the code; baselines may only shrink
check_tpu_branches.py rejects the PR A new is_tpu() branch or sglang_tpu import in core Move the code into sglang_tpu/ through a platform method, registry or hook
A scorer changes no decision It returns the same score for every endpoint, or its weight is negligible Test the order on fake endpoints; watch the decision metrics

The stopgap row has a live example. SGLang-TorchTPU's sglang_tpu/patches.py registers four Python kernels on the PrivateUse1 key with torch.library.register_kernel, under a docstring that says they "should eventually move into torch_tpu's C++ kernel set": aten::count_nonzero.dim_IntList, aten::masked_scatter_, aten::logaddexp and aten::upsample_bicubic2d, the last one by running the CPU kernel and copying back. In torch_tpu at commit f2aa01706, three of the four have native registrations (count_nonzero.dim_IntList, masked_scatter_, and upsample_bicubic2d.out, which the functional op is built from), and they were already registered in torch_tpu's history before the 0.2.1.dev20261028201649 build SGLang-TorchTPU pins. Only masked_scatter_'s stopgap carries a TODO with the torch_tpu issue that justifies keeping it. Only logaddexp.out is still in UNREGISTERED_OPS. That is the next section's exercise.

Design exercise: add aten::logaddexp.out to torch_tpu

The brief. Make torch.logaddexp run natively on the TPU, in eager mode and under torch.compile, for float32 and bfloat16 inputs with broadcasting, so that SGLang-TorchTPU's Python stopgap can be deleted when its torch_tpu pin advances. Deliver a pull request to torch_tpu and a follow-up plan for SGLang-TorchTPU.

What you build.

  1. The parity test, before any C++. Start from code/solutions/ch25/logaddexp_reference.py. It writes the lowering as one PyTorch op per StableHLO builder call (Max, Compare, Select, Subtract, Abs, Neg, Exp, Log1p, Add), compares it with torch.logaddexp on the CPU over random values, equal inputs, broadcast shapes and every pair of special values (\(\pm\infty\), NaN, \(0\), \(\pm 10^4\)), and runs two negative controls. Its smoke run is the first design review:

    lowering plan (float32 compute), torch.float32: PASS
    lowering plan (float32 compute), torch.bfloat16: PASS
    design alternative: compute in bfloat16: FAIL
        FAIL random N(0, 1)  (Tensor-likes are not close!)
        ...
        worst error / assert_close bound: float32-compute 0.00, bfloat16-compute 72.52
    negative control: naive log(exp(a) + exp(b)), float32: FAIL
    negative control: no equality guard, float32: FAIL
        FAIL special pairs  (Tensor-likes are not close!)
    cpu-smoke: OK
    

    The test settled two design questions before a line of C++. Computing every intermediate in bfloat16 misses assert_close's default tolerance by up to 73 times on these inputs, so bf16 inputs are converted to float32, computed, and converted back once, the way xlogy asks BinaryOpOut for float inputs. And the equality guard from SGLang's stopgap is required: without it, equal infinite inputs give inf - inf = NaN. The naive formula overflows as soon as \(e^{a}\) does.

  2. The lowering. csrc/ops/logaddexp/ with BUILD, header and kernel, modelled on xlogy/: a BuildLogaddexpShlo(mlir::MlirOp a, mlir::MlirOp b) that broadcasts with ApplyBroadcastIfNeeded and emits the formulation above, and an AtenLogaddexpOut(self, other, out) inside TT_KERNEL(OpName::kLogaddexpOut, ...) that checks out is on the TPU, rejects complex inputs with an actionable message, and calls BinaryOpOut with float compute. No calls to other ATen ops inside the kernel.

  3. The registration. kLogaddexpOut and "logaddexp.out" in op_names.h, ImplStable<OpName::kLogaddexpOut>(m, AtenLogaddexpOut) in the dense block, the dep in csrc/eager/BUILD, and 'logaddexp.out' removed from UNREGISTERED_OPS. The functional torch.logaddexp then comes from the out variant: confirm with missing_op_check.py against a fresh --dump-registrations list.

  4. The tests. In tests/ops_unit_test.py, assert_close_tpu_vs_cpu cases for functional, out= and broadcast forms in float32 and bfloat16, the special-value pairs, and a backward test if autograd reaches the op; in tests/ops_test.py, do_test_op("logaddexp"); error tests for the rejected dtypes; run --tpu mode of the solution script on a TPU VM.

  5. The path to merge and the follow-up. An issue first, then the PR with ## Description and ## Test Plan, the list_ci_tests.py output that shows the test target in a TPU presubmit job, and a note for SGLang-TorchTPU: when its pin includes the change, delete the aten::logaddexp stopgap and run its ring-attention tests.

Deliverables. A finished solution contains:

Area What it contains
Ownership A fix in torch_tpu, not in the engine or the model, and a plan to remove SGLang-TorchTPU's stopgap once its pin includes the change
Parity test first A test, written before the kernel, that covers special values, broadcast shapes and both dtypes; at least one negative control that fails; and measured errors against the dtype's tolerance behind the compute-dtype decision
Lowering A kernel that emits StableHLO only, with no calls to other ATen ops; broadcasting; float32 compute for bf16 inputs; actionable input errors; and NaN and infinity handling by construction, with each guard explained
Registration One change that updates the enum, ToString, ImplStable, include, Bazel dep and UNREGISTERED_OPS, and a missing_op_check.py run against a real registration list that reports the op as via_out
Tests and CI Unit and OpInfo tests in both dtypes, in eager mode and under torch.compile, including the backward if autograd reaches the op, and list_ci_tests.py output that shows a TPU job running them
Evidence of use A run of the model that needed the op with the CPU fallback off and, where the op is on a hot path, a before-and-after step time measured as in chapter 24
Contribution An issue linked from a small PR that follows the PR template and the authorship rules, and a follow-up issue or PR for the downstream stopgap

Verifying the result

An extension works when all of these hold, and the companion code checks the CPU half:

python code/ch25_extending/registry.py --cpu-smoke                 # ends "cpu-smoke: OK"
python code/ch25_extending/missing_op_check.py --cpu-smoke         # 2 known gaps found, clean model clean
python code/solutions/ch25/logaddexp_reference.py --cpu-smoke      # plan passes, controls fail
pytest tests/ch25 -q
  1. The op test passes against the CPU reference. For a lowering: assert_close_tpu_vs_cpu in both dtypes, with special values and every form you registered, and the negative controls in the design-time test failing as intended. For a patch, hook or model: the behaviour or parity test passes, and fails when you revert the change (R-8.2).
  2. Nothing falls back. The model runs on the TPU with enable_cpu_fallback off, the log has no Falling back to CPU line, and missing_op_check.py against the registration list dumped from that environment reports zero missing ops.
  3. The extension is exercised. The evidence in the table above for your repository: the op absent from UNREGISTERED_OPS, the patched function observed in a spawned worker, the hook in inventory.py, the kernel's custom_call in the HLO dump, the scorer's metrics moving.
  4. CI checks pass, on the right hardware. torch_tpu: list_ci_tests.py --test=... lists a TPU job, and Copybara presubmits pass. vLLM-TorchTPU: pre-commit run --all-files, tools/typecheck_full.sh, CPU tests, then TPU CI after ready, with baselines that only shrank. SGLang-TorchTPU: the ratchet, CPU suite and run-ci suite. TorchTitan: the shards in tpu-test.yml, with your test on the base class that places it on a chip.
  5. Only then, a performance claim, measured as chapter 24 prescribes against the path you replaced.

Worked problems

Problem 1. missing_op_check.py reports, for a model's forward and backward, aten::_softmax as via_out (aten::_softmax.out), aten::t as composite, aten::upsample_bicubic2d as via_out, and aten::logaddexp as missing (needs one of: aten::logaddexp.out). Which of these need work before the model runs on a TPU, and what single registration closes the gap?

Answer

Only aten::logaddexp. via_out means PyTorch builds the functional op from a registered out variant through its CompositeExplicitAutogradNonFunctional kernel; composite means the op decomposes into others before the backend. The gap closes with one registration, ImplStable<OpName::kLogaddexpOut>, because the functional op is then built from it. Two caveats: the composite row is only as good as the ops it decomposes into, which the trace does not show, and the list you checked against was read from source. Dump the real list with --dump-registrations on the TPU VM and run once with the fallback off.

Problem 2. A vLLM-TorchTPU patch that swaps a layer's forward is registered as Patch("vllm_torchtpu.foo:patch_forward", ("platform_activation",)). Single-process tests pass. In a multiprocess server, outputs show the upstream behaviour. Explain, and fix the entry.

Answer

platform_activation runs in the parent. Spawned workers start with an empty registry and execute the model, and the only stage that runs at their start is worker_init, which this entry does not name, so the swap never happens where the forward runs. (A forked worker would inherit it, which is why the bug can depend on the start method.) Use _ACTIVE, ("platform_activation", "worker_init"), as 29 of the 47 entries do; use _ENGINE if the engine-core process also reads the symbol. Then update the manifest assertions in tests/platforms/test_patch_registry.py and check the startup path with spawned workers, as the guide asks.

Problem 3. A model patch is written as below and registered at ("platform_activation", "model_load") with model_config=True. The engine serves the target model, but the patch never applies. Why?

def maybe_patch_mymodel(model_config=None):
    if model_config is None:
        return None
    if "MyModelForCausalLM" not in model_config.architectures:
        return None
    ...
Answer

Only the literal False leaves an entry eligible. Any other value, including None, marks it complete, and completion is keyed by the target string for the life of the process. If platform_activation runs with model_config=None (or with another model's config), the first return None completes the entry, and model_load with the right config skips it. Return False in both early exits, as maybe_patch_qwen2 does. tests/ch25/test_registry.py::test_completion_is_keyed_by_target_not_model reproduces the bug.

Problem 4. SGLang-TorchTPU registers a Python aten::upsample_bicubic2d kernel on PrivateUse1 that runs the CPU kernel and copies back. The torch_tpu you pin registers upsample_bicubic2d.out. A teammate wants to keep the stopgap "because it works". Evaluate.

Answer

It works, but it is no longer justified and it costs something. The stopgap's own comment justified it by "no TPU kernel", and its docstring says these fallbacks "should eventually move into torch_tpu's C++ kernel set"; that condition has been met. It does a host round trip in float32 on every call, which the comment accepted because the inputs were small, and it leaves two implementations of one op, only one of which torch_tpu's op tests cover. The right move is a change that deletes the stopgap, runs the vision-tower tests that use the op (position-embedding resizing), and compares outputs with the CPU at bf16 tolerance. Keep a stopgap only with a removal condition, as masked_scatter_'s TODO with its torch_tpu issue does.

Problem 5. An EPP profile weights prefix-cache-scorer at 2, queue-scorer at 1 and your tpu-shape-fit scorer at 1. For three endpoints the scorers return: A (0.9, 0.2, 0.0), B (0.6, 0.8, 1.0), C (0.0, 1.0, 1.0). Which endpoint does max-score-picker choose, and what changes if your scorer returns 1.0 for every endpoint?

Answer

Totals: A \(= 2(0.9) + 0.2 + 0 = 2.0\); B \(= 2(0.6) + 0.8 + 1.0 = 3.0\); C \(= 0 + 1.0 + 1.0 = 2.0\). B wins. Without your scorer the totals are A 2.0, B 2.0, C 1.0, a tie between A and B; your scorer broke it towards the endpoint whose compiled shapes fit. If it returned 1.0 everywhere it would add 1 to each total and decide nothing: A 3.0, B 3.0, C 2.0, the same tie as without it. A scorer is only as useful as the spread of its scores, which is why its test should assert an order on endpoints with different metrics.

Problem 6. Before writing the C++ for aten::logaddexp.out, write the parity test: the formulation in StableHLO-shaped steps, the cases, the tolerance, and the negative controls. Decide from evidence whether bfloat16 inputs are computed in bfloat16 or float32.

Answer

The solution is code/solutions/ch25/logaddexp_reference.py. Formulation: \(p = \max(a, b)\); \(g = 0\) where \(a = b\), else \(-|a - b|\); result \(p + \operatorname{log1p}(e^{g})\), one PyTorch op per builder (Max, Compare, Select, Subtract, Abs, Neg, Exp, Log1p, Add), with broadcast_tensors for ApplyBroadcastIfNeeded. Cases: \(N(0, 1)\) and \(N(0, 50)\) random values, equal inputs, a \((64, 1) \times (1, 64)\) broadcast, and all 144 pairs of 12 special values including \(\pm\infty\) and NaN. Tolerance: torch.testing.assert_close defaults with equal_nan=True, the dtype's own bound. Controls: the naive \(\log(e^a + e^b)\), which fails on the \(N(0, 50)\) inputs by overflow, and the formula without the equality guard, which fails only on the special pairs (equal infinities give NaN). Evidence for the compute dtype: with float32 compute both dtypes pass; computing in bfloat16 fails three of five cases, with a worst error 72.5 times the default bound, so the lowering converts bf16 to float32 and back once. tests/ch25 runs all of this.

Problem 7. Design the vLLM-TorchTPU change that makes a new model family, FooForCausalLM, use a TPU attention class that pads query heads when they do not divide the tensor-parallel size. Give the files, the callback, the registry entry and the tests.

Answer

First check whether a register_oot layer or an upstream subclass hook covers it (R-3.5, R-3.1); a whole-class swap for one model family is what the registry's model-specific section is for, so assume it does not. Files: the TPU class in src/vllm_torchtpu/models/vllm/foo.py, subclassing the upstream attention and overriding only the padding (R-3.2: no copied layers); the callback in src/vllm_torchtpu/models/vllm/foo_patch.py, maybe_patch_foo(model_config=None) -> bool | None, returning False when the config is missing or its architectures lacks FooForCausalLM, and otherwise importing the upstream module inside the function, assigning the class and returning None. Entry, appended under # Model-specific patches: Patch("vllm_torchtpu.models.vllm.foo_patch:maybe_patch_foo", ("platform_activation", "model_load"), model_config=True). Tests: a CPU unit test that the callback returns False for None and for another architecture and swaps the class for Foo; a test that the padded attention matches the unpadded one when heads divide evenly and matches a CPU reference when they do not, marked tpu_test if it needs a chip; the manifest assertion in tests/platforms/test_patch_registry.py updated; pre-commit run --all-files and tools/typecheck_full.sh clean, with no new baseline entries.

Quick questions

  1. Which dispatcher key do TPU tensors use, and where in torch_tpu is the table that fills it?
  2. What does torch_tpu do by default when an ATen op has no TPU kernel, and what changes when enable_cpu_fallback is set?
  3. Why do most torch_tpu registrations name an out variant, and how does the functional op get a kernel?
  4. What does the composite-op check forbid inside a new lowering, and how does it enforce it?
  5. Name the files that change when an ATen op is added to torch_tpu, and the test that fails if UNREGISTERED_OPS is not updated.
  6. For the five vLLM-TorchTPU patch stages, which process runs each, and why do most entries use _ACTIVE or _ENGINE?
  7. What return value keeps a patch eligible for a later stage, and what is completion keyed by?
  8. What problem does a refresh target solve, and how does SGLang's HookRegistry solve the same problem differently?
  9. In what order does SGLang-TorchTPU's guide tell you to try extension mechanisms for a core change, and what does the ratchet forbid?
  10. How does TorchTitan's TPU CI decide whether a test runs on a chip, and what goes wrong with a skipUnless TPU check?
  11. How does an EPP profile combine scorer outputs, and what does a scorer that returns a constant contribute?
  12. Why is "Completed TPU patch callbacks" in a log not evidence that a patch works?

Key takeaways

  • Each repository has a door for extensions: an ATen lowering in torch_tpu, register_oot or a PATCHES entry in vLLM-TorchTPU, a platform method, registry or hook in SGLang-TorchTPU, a wrapped or ported model under experiments/tpu/ in TorchTitan, and a scorer or filter plugin in the llm-d EPP. Fix a defect at the layer that owns it; a workaround above it needs a removal condition.
  • An ATen op on a TPU tensor is looked up in TORCH_LIBRARY_IMPL(aten, PrivateUse1, m), 685 ImplStable registrations whose kernels build StableHLO and return deferred ops; torch.compile uses the same lowerings. A missing op raises NotImplementedError by default; the CPU fallback is an internal debugging knob that logs every use.
  • Adding an op is a fixed change set: kernel directory, OpName and ToString, ImplStable, Bazel dep, removal from UNREGISTERED_OPS, assert_close_tpu_vs_cpu and OpInfo tests, and proof with list_ci_tests.py that a TPU job runs them. The kernel must emit StableHLO itself.
  • vLLM-TorchTPU patches are staged, ordered and keyed by target: name every stage the patched code runs in, return False until a model patch applies, refresh late bindings idempotently, and never read the completion log as proof.
  • Find op gaps on a laptop before you book a TPU: trace to ATen ops, classify against the registration list dumped from the environment you will run in, and confirm with one run with the fallback off.
  • Write the parity test before the extension, with a negative control, and let it settle design choices: for logaddexp, float32 compute for bf16 inputs and an equality guard for infinities, both decided on a CPU.
  • Contribution rules differ by repository and are part of the design: torch_tpu's CLA, issue-first and Copybara review with Assisted-by:; vLLM-TorchTPU's DCO, shrinking type baselines, test markers and ready label; SGLang-TorchTPU's ratchet and registered tests; TorchTitan's base-class CI placement and the PR as onboarding record.

Chapter 26 hands this kind of work to agents, and asks you to judge their results by the same gates.

References