|
| 1 | +# Copyright 2026 FlagOS Contributors |
| 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 | +import torch |
| 16 | +import triton |
| 17 | +import triton.language as tl |
| 18 | + |
| 19 | + |
| 20 | +@triton.jit |
| 21 | +def arctanh_kernel(x_ptr, out_ptr, n_elements, BLOCK_SIZE: tl.constexpr): |
| 22 | + pid = tl.program_id(axis=0) |
| 23 | + block_start = pid * BLOCK_SIZE |
| 24 | + offsets = block_start + tl.arange(0, BLOCK_SIZE) |
| 25 | + mask = offsets < n_elements |
| 26 | + |
| 27 | + x = tl.load(x_ptr + offsets, mask=mask, other=0) |
| 28 | + x_f32 = x.to(tl.float32) |
| 29 | + |
| 30 | + one = 1.0 |
| 31 | + # atanh(x) = 0.5 * (log(1 + x) - log(1 - x)) |
| 32 | + y_f32 = 0.5 * (tl.log(one + x_f32) - tl.log(one - x_f32)) |
| 33 | + y = y_f32.to(x.dtype) |
| 34 | + |
| 35 | + tl.store(out_ptr + offsets, y, mask=mask) |
| 36 | + |
| 37 | + |
| 38 | +def _launch_arctanh(x: torch.Tensor, out: torch.Tensor): |
| 39 | + assert x.is_cuda and out.is_cuda, "Input and output must be CUDA tensors" |
| 40 | + assert x.shape == out.shape, "Input and output shapes must match" |
| 41 | + assert out.dtype == x.dtype, "Output dtype must match input dtype" |
| 42 | + assert x.dtype in ( |
| 43 | + torch.float16, |
| 44 | + torch.bfloat16, |
| 45 | + torch.float32, |
| 46 | + ), "Supported dtypes: float16, bfloat16, float32" |
| 47 | + |
| 48 | + x_contig = x.contiguous() |
| 49 | + out_contig = out if out.is_contiguous() else torch.empty_like(out) |
| 50 | + |
| 51 | + n_elements = x_contig.numel() |
| 52 | + if n_elements == 0: |
| 53 | + if out_contig is not out: |
| 54 | + out.copy_(out_contig) |
| 55 | + return out |
| 56 | + |
| 57 | + grid = lambda meta: (triton.cdiv(n_elements, meta["BLOCK_SIZE"]),) |
| 58 | + arctanh_kernel[grid](x_contig, out_contig, n_elements, BLOCK_SIZE=1024) |
| 59 | + |
| 60 | + if out_contig is not out: |
| 61 | + out.copy_(out_contig) |
| 62 | + return out |
| 63 | + |
| 64 | + |
| 65 | +def arctanh(x: torch.Tensor): |
| 66 | + out = torch.empty_like(x) |
| 67 | + _launch_arctanh(x, out) |
| 68 | + return out |
| 69 | + |
| 70 | + |
| 71 | +def arctanh_out(x: torch.Tensor, out: torch.Tensor): |
| 72 | + _launch_arctanh(x, out) |
| 73 | + return out |
0 commit comments