You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@mahout.apache.org by "Tcc0403 (via GitHub)" <gi...@apache.org> on 2026/04/16 18:28:46 UTC
Re: [PR] [Feature][QDP] Add AMD GPU support via Triton backend [mahout]
Tcc0403 commented on code in PR #1158:
URL: https://github.com/apache/mahout/pull/1158#discussion_r3095320594
##########
qdp/qdp-python/benchmark/benchmark_triton_amd.py:
##########
@@ -0,0 +1,93 @@
+#!/usr/bin/env python3
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Baseline benchmark for Triton AMD backend (ROCm)."""
+
+from __future__ import annotations
+
+import argparse
+import time
+
+import torch
+
+from qumat_qdp import TritonAmdEngine, is_triton_amd_available
+
+
+def _build_input(method: str, batch_size: int, qubits: int) -> torch.Tensor:
+ if method == "basis":
+ return torch.randint(
+ low=0,
+ high=1 << qubits,
+ size=(batch_size,),
+ device="cuda",
+ dtype=torch.int64,
+ )
+ if method == "angle":
+ return torch.randn(batch_size, qubits, device="cuda", dtype=torch.float32)
+ return torch.randn(batch_size, 1 << qubits, device="cuda", dtype=torch.float32)
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description="Benchmark Triton AMD backend throughput/latency.")
+ parser.add_argument("--qubits", type=int, default=12)
+ parser.add_argument("--batch-size", type=int, default=64)
+ parser.add_argument("--batches", type=int, default=200)
+ parser.add_argument(
+ "--encoding-method",
+ type=str,
+ default="amplitude",
+ choices=["amplitude", "angle", "basis"],
+ )
+ parser.add_argument("--precision", type=str, default="float32", choices=["float32", "float64"])
+ args = parser.parse_args()
+
+ if not is_triton_amd_available():
+ raise SystemExit("triton_amd backend is unavailable (requires ROCm + Triton HIP target).")
+
+ engine = TritonAmdEngine(device_id=0, precision=args.precision)
+ data = _build_input(args.encoding_method, args.batch_size, args.qubits)
+
+ # Warmup
+ for _ in range(10):
+ _ = engine.encode(data, args.qubits, args.encoding_method)
+ torch.cuda.synchronize()
+
+ t0 = time.perf_counter()
+ processed = 0
+ for _ in range(args.batches):
+ _ = engine.encode(data, args.qubits, args.encoding_method)
+ processed += args.batch_size
+ torch.cuda.synchronize()
+ dt = time.perf_counter() - t0
Review Comment:
cuda.Event instead of time.perf_counter for more accurate benchmarking?
https://docs.pytorch.org/docs/stable/generated/torch.cuda.Event.html
##########
qdp/qdp-python/qumat_qdp/triton_amd.py:
##########
@@ -0,0 +1,281 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Triton AMD backend for QDP encodings on ROCm."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Any
+
+import torch
+import triton
+import triton.language as tl
+
+
+def _is_rocm_runtime() -> bool:
+ return bool(getattr(torch.version, "hip", None)) and torch.cuda.is_available()
+
+
+def is_triton_amd_available() -> bool:
+ """Return True when Triton is available and active target is HIP/ROCm."""
+ if not _is_rocm_runtime():
+ return False
+ try:
+ target = triton.runtime.driver.active.get_current_target()
+ return str(getattr(target, "backend", "")).lower() == "hip"
+ except Exception:
+ # Conservative fallback: ROCm torch build + triton import available.
+ return True
+
+
+@triton.jit
+def _amplitude_pack_kernel(
+ input_ptr,
+ inv_norms_ptr,
+ out_ptr,
+ sample_size,
+ state_len,
+ total_elems,
+ BLOCK: tl.constexpr,
+):
+ pid = tl.program_id(axis=0)
+ offs = pid * BLOCK + tl.arange(0, BLOCK)
+ mask = offs < total_elems
+
+ sample_idx = offs // state_len
+ elem_idx = offs % state_len
+ in_idx = sample_idx * sample_size + elem_idx
+
+ vals = tl.load(input_ptr + in_idx, mask=mask & (elem_idx < sample_size), other=0.0)
+ inv = tl.load(inv_norms_ptr + sample_idx, mask=mask, other=0.0)
+ real = vals * inv
+
+ out_base = offs * 2
+ tl.store(out_ptr + out_base, real, mask=mask)
+ tl.store(out_ptr + out_base + 1, 0.0, mask=mask)
+
+
+@triton.jit
+def _angle_kernel(
+ angles_ptr,
+ out_ptr,
+ state_len,
+ total_elems,
+ NQ: tl.constexpr,
+ FP64: tl.constexpr,
+ BLOCK: tl.constexpr,
+):
+ pid = tl.program_id(axis=0)
+ offs = pid * BLOCK + tl.arange(0, BLOCK)
+ mask = offs < total_elems
+
+ sample_idx = offs // state_len
+ elem_idx = offs % state_len
+
+ amp = tl.full([BLOCK], 1.0, dtype=tl.float64 if FP64 else tl.float32)
+ angles_base = sample_idx * NQ
+ for bit in range(NQ):
+ ang = tl.load(angles_ptr + angles_base + bit, mask=mask, other=0.0)
+ bit_set = ((elem_idx >> bit) & 1) != 0
+ factor = tl.where(bit_set, tl.sin(ang), tl.cos(ang))
+ amp = amp * factor
Review Comment:
Replace loop with this?
```py
bit_offsets = tl.arange(padded_NQ)
angles = tl.load(angles_ptr + angles_base + offsets, mask=bit_offsets<NQ, other=0.0)
bit_sets = ((elem_idx >> bit_offsets) & 1) != 0
factors = tl.where(bit_sets, tl.sin(angles), tl.cos(angles))
amp = tl.reduce(factors, combine_fn=jit_product_callable) # https://triton-lang.org/main/python-api/generated/triton.language.reduce.html#triton.language.reduce
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@mahout.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org