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"""Generated fixed-order Ascend Triton tree, one launch for all levels."""
16from __future__ import annotations
17
18import hashlib
19import importlib.util
20import os
21import tempfile
22from functools import lru_cache
23from pathlib import Path
24
25import torch
26import triton
27
28_TEMPLATE = '''import triton
29import triton.language as tl
30
31@triton.jit(do_not_specialize=["size", "stride"])
32def kernel({arguments}, output, size, stride, BLOCK: tl.constexpr):
33 offsets = tl.program_id(0).to(tl.int64) * BLOCK + tl.arange(0, BLOCK).to(tl.int64)
34 mask = offsets < size
35{body}
36 tl.store(output + offsets, value0, mask=mask)
37'''
38
39def _emit(low: int, high: int, depth: int, packed: bool, lines: list[str]) -> None:
40 if high - low == 1:
41 pointer = f"partials + {low} * stride.to(tl.int64)" if packed else f"input{low}"
42 lines.append(f" value{depth} = tl.load({pointer} + offsets, mask=mask, other=0.0).to(tl.float32)")
43 return
44 middle = (low + high) // 2
45 _emit(low, middle, depth, packed, lines)
46 _emit(middle, high, depth + 1, packed, lines)
47 lines.append(f" value{depth} = value{depth} + value{depth + 1}")
48
49
50@lru_cache(maxsize=None)
51def _kernel(count: int, packed: bool):
52 """Reduce each output tile with the fixed global binary tree."""
53 if count <= 0 or count & (count - 1):
54 raise ValueError("the Triton tree requires a power-of-two leaf count")
55 lines: list[str] = []
56 _emit(0, count, 0, packed, lines)
57 arguments = "partials" if packed else ", ".join(f"input{index}" for index in range(count))
58 source = _TEMPLATE.format(arguments=arguments, body="\n".join(lines))
59 digest = hashlib.sha256(source.encode()).hexdigest()[:16]
60 name = f"pik_tree_{count}_{'packed' if packed else 'pointers'}_{digest}"
61 directory = Path(os.environ.get("TRITON_CACHE_DIR", Path.home() / ".triton" / "cache")) / "pik_tree_source"
62 directory.mkdir(parents=True, exist_ok=True)
63 path = directory / f"{name}.py"
64 # Triton inspects a real source file; atomic installation also permits many
65 # ranks to compile the same immutable source concurrently.
66 if not path.exists() or path.read_text(encoding="utf-8") != source:
67 with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=directory, delete=False) as stream:
68 temporary = Path(stream.name)
69 stream.write(source)
70 try:
71 temporary.replace(path)
72 finally:
73 temporary.unlink(missing_ok=True)
74 spec = importlib.util.spec_from_file_location(name, path)
75 module = importlib.util.module_from_spec(spec)
76 spec.loader.exec_module(module)
77 return module.kernel
78
79
80def reduce_tree(partials: torch.Tensor) -> torch.Tensor:
81 """Accumulate contiguous [leaves, rows, columns] into an FP32 root."""
82 output = torch.empty(partials.shape[1:], dtype=torch.float32, device=partials.device)
83 block = 1024
84 grid = (triton.cdiv(output.numel(), block), 1, 1)
85 _kernel(partials.shape[0], True)[grid](
86 partials, output, output.numel(), partials.stride(0), BLOCK=block, enable_fp_fusion=False,
87 )
88 return output