1# Copyright 2026 Huawei Technologies Co., Ltd
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ============================================================================
15"""Opaque compiler boundary for the fixed FP32 tree; no device dependency at import."""
16import torch
17from torch._subclasses.fake_tensor import FakeTensor
18from torch.fx.experimental.proxy_tensor import get_proxy_mode
19
20
21def _run_tree(partials: torch.Tensor) -> torch.Tensor:
22 """Launch exactly the same kernel in eager execution and compiled graphs."""
23 if partials.device.type != "npu":
24 raise ValueError("PIK fixed tree requires an NPU tensor")
25 # Triton is optional for CPU-only model/configuration tools.
26 from ._triton_reduction import reduce_tree # pylint: disable=import-outside-toplevel
27
28 return reduce_tree(partials)
29
30
31@torch.library.custom_op("hyper_parallel::pik_tree", mutates_args=())
32def _tree_op(partials: torch.Tensor) -> torch.Tensor:
33 """Keep Triton opaque to Dynamo/AOT while exposing a Fake/Meta implementation."""
34 return _run_tree(partials)
35
36
37@_tree_op.register_fake
38def _tree_fake(partials: torch.Tensor) -> torch.Tensor:
39 """Expose dtype and shape to the inference/training compiler."""
40 return partials.new_empty(partials.shape[1:], dtype=torch.float32)
41
42
43def fixed_tree(partials: torch.Tensor) -> torch.Tensor:
44 """Combine packed BF16 leaves or FP32 rank roots without rank-dependent casts."""
45 if partials.ndim != 3 or partials.shape[0] < 1 or partials.shape[0] & (partials.shape[0] - 1):
46 raise ValueError("tree requires [power-of-two leaves, rows, columns]")
47 if partials.dtype not in (torch.bfloat16, torch.float32):
48 raise ValueError("tree accepts only BF16 leaves or FP32 internal nodes")
49 if partials.shape[0] == 1:
50 return partials[0].float()
51 inputs = partials.contiguous()
52 if torch.compiler.is_compiling() or isinstance(inputs, FakeTensor) or get_proxy_mode() is not None:
53 return _tree_op(inputs)
54 # Avoid Python custom-op dispatch overhead when no compiler is tracing.
55 return _run_tree(inputs)