This repository has been archived by the owner on Feb 24, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsigmoid.py
95 lines (79 loc) · 2.51 KB
/
sigmoid.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# Copyright 2023 ⓒ Daemyung Jang.
#
# Licensed 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
#
# https://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.
import torch
import triton
import triton.language as tl
@triton.jit
def base(
y_ptr: tl.tensor,
x_ptr: tl.tensor,
x_size: tl.int32,
block_size: tl.constexpr,
):
y_block_ptr = tl.make_block_ptr(
y_ptr,
shape=(x_size,),
strides=(1,),
offsets=(0,),
block_shape=(block_size,),
order=(0,),
)
x_block_ptr = tl.make_block_ptr(
x_ptr,
shape=(x_size,),
strides=(1,),
offsets=(0,),
block_shape=(block_size,),
order=(0,),
)
x = tl.load(x_block_ptr, boundary_check=(0,))
y = tl.sigmoid(x)
tl.store(y_block_ptr, y, boundary_check=(0,))
def dispatch(kernel: triton.jit, y: torch.Tensor, x: torch.Tensor):
kernel[(1,)](y, x, x.numel(), triton.next_power_of_2(x.numel()))
def verify_result():
factory_kwargs = {"device": "cuda", "dtype": torch.float32}
x = torch.rand(10, **factory_kwargs)
y = torch.rand(10, **factory_kwargs)
z = torch.sigmoid(x)
dispatch(base, y, x)
torch.allclose(z, y)
@triton.testing.perf_report(
[
triton.testing.Benchmark(
x_names=["x_size"],
x_vals=[256 * i for i in range(1, 31, 1)],
line_arg="backend",
line_vals=["torch", "base"],
line_names=["torch", "base"],
ylabel="milliseconds",
plot_name="sigmoid",
args={"dtype": torch.float32},
)
]
)
def benchmark(x_size, dtype, backend):
factory_kwargs = {"device": "cuda", "dtype": dtype}
x = torch.rand(x_size, **factory_kwargs)
y = torch.empty_like(x)
if backend == "torch":
return triton.testing.do_bench_cudagraph(lambda: torch.sigmoid(x))
else:
return triton.testing.do_bench_cudagraph(lambda: dispatch(base, y, x))
def main():
torch.cuda.set_stream(torch.cuda.Stream())
verify_result()
benchmark.run(show_plots=True, print_data=True)
if __name__ == "__main__":
main()