quack-kernels 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
quack/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ __version__ = "0.1.0"
2
+
3
+ from quack.rmsnorm import rmsnorm
4
+ from quack.softmax import softmax
5
+ from quack.cross_entropy import cross_entropy
quack/cross_entropy.py ADDED
@@ -0,0 +1,221 @@
1
+ import math
2
+ import torch
3
+ import operator
4
+ from typing import Callable, Union
5
+
6
+ import cuda.bindings.driver as cuda
7
+
8
+ import cutlass
9
+ import cutlass.cute as cute
10
+ from cutlass.cute.runtime import from_dlpack
11
+
12
+ import quack.utils as utils
13
+
14
+
15
+ @cute.kernel
16
+ def cross_entropy_kernel(
17
+ mX: cute.Tensor, # (M, N)
18
+ mTarget: cute.Tensor, # (M,)
19
+ mLoss: cute.Tensor, # (M,)
20
+ tv_layout: cute.Layout,
21
+ tiler_mn: cute.Shape,
22
+ cluster_n: cutlass.Constexpr = 1,
23
+ ):
24
+ tidx, _, _ = cute.arch.thread_idx()
25
+ bidx, cluster_y, _ = cute.arch.block_idx()
26
+ gdim, _, _ = cute.arch.grid_dim()
27
+
28
+ shape: cute.Shape = mX.shape
29
+ idX = cute.make_identity_tensor(mX.shape)
30
+ gX, cX = [cute.zipped_divide(mT, tiler_mn) for mT in (mX, idX)]
31
+ blkX, blkCrd = [gT[(None, None), bidx if cluster_n == 1 else (bidx, cluster_y)] for gT in (gX, cX)]
32
+
33
+ # declare the atoms which will be used later for memory copy
34
+ copy_atom_load_X = cute.make_copy_atom(cute.nvgpu.CopyUniversalOp(), gX.element_type, num_bits_per_copy=128)
35
+ copy_atom_load_X_async = cute.make_copy_atom(cute.nvgpu.cpasync.CopyG2SOp(), gX.element_type, num_bits_per_copy=128)
36
+ copy_atom_scalar = cute.make_copy_atom(cute.nvgpu.CopyUniversalOp(), gX.element_type, num_bits_per_copy=gX.element_type.width)
37
+
38
+ thr_copy_X = cute.make_tiled_copy(copy_atom_load_X, tv_layout, tiler_mn).get_slice(tidx)
39
+ thr_copy_X_async = cute.make_tiled_copy(copy_atom_load_X_async, tv_layout, tiler_mn).get_slice(tidx)
40
+
41
+ smem = cutlass.utils.SmemAllocator()
42
+
43
+ # Don't use blkX.layout here, because the stride is N, not N_rounded
44
+ sX = smem.allocate_tensor(gX.element_type, cute.make_ordered_layout(blkX.shape, order=(1, 0)), byte_alignment=16)
45
+ num_warps = cute.size(tv_layout, mode=[0]) // cute.arch.WARP_SIZE
46
+ warps_per_row = utils.max_constexpr(tv_layout.shape[0][0] // cute.arch.WARP_SIZE, 1)
47
+
48
+ reduction_buffer_layout = cute.make_ordered_layout(
49
+ # 2 stages: 1 for max, 1 for sum
50
+ (num_warps // warps_per_row, warps_per_row if cluster_n == 1 else (warps_per_row, cluster_n), 2),
51
+ order=(1, 0, 2)
52
+ )
53
+ reduction_buffer = smem.allocate_tensor(cutlass.Float32, reduction_buffer_layout, byte_alignment=4)
54
+ if cutlass.const_expr(cluster_n > 1):
55
+ # 1 mbar for max reduction, 1 mbar for sum reduction
56
+ mbar_ptr = smem.allocate_array(cutlass.Int64, num_elems=2)
57
+ else:
58
+ mbar_ptr = None
59
+
60
+ #### Thread View
61
+ tXgX = thr_copy_X_async.partition_S(blkX)
62
+ tXsX = thr_copy_X_async.partition_S(sX)
63
+
64
+ tXcX = thr_copy_X.partition_S(blkCrd)[(0, None), None, None]
65
+
66
+ # allocate fragments for gmem->rmem
67
+ tXrX = cute.make_fragment_like(tXgX) # only logits fragment needed
68
+
69
+ if cluster_n > 1:
70
+ if tidx < 2:
71
+ cute.arch.mbarrier_init_arrive_cnt(mbar_ptr + tidx, 1)
72
+ cute.arch.mbarrier_init_fence()
73
+ if tidx < 2:
74
+ cute.arch.mbarrier_init_tx_bytes(mbar_ptr + tidx, num_warps * cluster_n * cutlass.Float32.width // 8)
75
+ # Cluster arrive after barrier init
76
+ cute.arch.cluster_arrive_relaxed()
77
+
78
+ row = tXcX[0][0]
79
+ target = cute.Int32.zero
80
+ if row < shape[0] and tXcX[0][1] == 0:
81
+ target = cute.Int32(mTarget[row])
82
+
83
+ tXpX = cute.make_fragment_like(tXgX[(0, None), None, None], cutlass.Boolean)
84
+ for i in range(cute.size(tXpX)):
85
+ tXpX[i] = cute.elem_less(tXcX[i][1], shape[1])
86
+ if row < shape[0]:
87
+ cute.copy(copy_atom_load_X_async, tXgX, tXsX, pred=tXpX)
88
+ cute.arch.cp_async_commit_group()
89
+ cute.arch.cp_async_wait_group(0)
90
+ cute.autovec_copy(tXsX, tXrX)
91
+ x = tXrX.load().to(cute.Float32)
92
+
93
+ target_logit = cute.Float32.zero
94
+ if row < shape[0] and tXcX[0][1] == 0:
95
+ target_logit = cute.Float32(mX[row, target])
96
+
97
+ max_x = utils.warp_reduce(
98
+ x.reduce(cute.ReductionOp.MAX, init_val=float('-inf'), reduction_profile=0),
99
+ cute.arch.fmax,
100
+ width=utils.min_constexpr(tv_layout.shape[0][0], cute.arch.WARP_SIZE),
101
+ )
102
+ if cutlass.const_expr(cluster_n > 1):
103
+ cute.arch.cluster_wait()
104
+ if cutlass.const_expr(warps_per_row > 1 or cluster_n > 1):
105
+ max_mbar_ptr = mbar_ptr + 0 if cluster_n > 1 else None
106
+ max_x = utils.block_or_cluster_reduce(
107
+ max_x, cute.arch.fmax, reduction_buffer[None, None, 0], max_mbar_ptr, init_val=-cutlass.Float32.inf
108
+ )
109
+ log2_e = math.log2(math.e)
110
+ # exp_x = cute.math.exp2((x - max_x) * log2_e, fastmath=True)
111
+ exp_x = utils.exp2f((x - max_x) * log2_e) # a bit faster, idk why
112
+ denom = utils.warp_reduce(
113
+ exp_x.reduce(cute.ReductionOp.ADD, init_val=0.0, reduction_profile=0),
114
+ operator.add,
115
+ width=utils.min_constexpr(tv_layout.shape[0][0], cute.arch.WARP_SIZE),
116
+ )
117
+ if cutlass.const_expr(warps_per_row > 1 or cluster_n > 1):
118
+ sum_mbar_ptr = mbar_ptr + 1 if cluster_n > 1 else None
119
+ denom = utils.block_or_cluster_reduce(
120
+ denom, operator.add, reduction_buffer[None, None, 1], sum_mbar_ptr, init_val=0.0
121
+ )
122
+
123
+ if tXcX[0][1] == 0 and row < shape[0]:
124
+ ln_2 = math.log(2.0)
125
+ loss_val = -target_logit + max_x + utils.log2f(denom) * ln_2
126
+ if cutlass.const_expr(cluster_n == 1):
127
+ mLoss[row] = loss_val.to(mLoss.element_type)
128
+ else:
129
+ if cute.arch.block_idx_in_cluster() == 0:
130
+ mLoss[row] = loss_val.to(mLoss.element_type)
131
+
132
+
133
+ @cute.jit
134
+ def cross_entropy_interface(
135
+ mX: cute.Tensor,
136
+ mTarget: cute.Tensor,
137
+ mLoss: cute.Tensor,
138
+ stream: cuda.CUstream,
139
+ N: cutlass.Constexpr,
140
+ copy_bits: cutlass.Constexpr = 128
141
+ ):
142
+ vecsize = copy_bits // mX.element_type.width
143
+ assert N % vecsize == 0, f"Input N {N} is not divisible by vector size {vecsize}"
144
+ num_threads = 128 if N <= 16384 else 256
145
+
146
+ num_warps = num_threads // cute.arch.WARP_SIZE
147
+ assert num_threads % cute.arch.WARP_SIZE == 0
148
+ threads_per_row = 8 if N <= 64 else (16 if N <= 128 else (32 if N <= 3072 else (64 if N <= 6144 else (128 if N <= 16384 else 256))))
149
+
150
+ if cutlass.const_expr(mX.element_type.width == 16):
151
+ cluster_n = 1 if N <= 16 * 1024 else (2 if N <= 32 * 1024 else (4 if N <= 64 * 1024 else (8 if N <= 128 * 1024 else 16)))
152
+ else: # fp32
153
+ cluster_n = 1 if N <= 16 * 1024 else (2 if N <= 64 * 1024 else (4 if N <= 128 * 1024 else 8))
154
+
155
+ num_blocks_N = cute.ceil_div(N // vecsize, threads_per_row * cluster_n)
156
+ cols_per_block = num_threads // threads_per_row
157
+ tiler_mn = (cols_per_block, vecsize * num_blocks_N * threads_per_row) # This rounds up N
158
+ tv_layout = cute.make_layout(
159
+ ((threads_per_row, cols_per_block), (vecsize, num_blocks_N)),
160
+ stride=((vecsize * cols_per_block, 1), (cols_per_block, cols_per_block * vecsize * threads_per_row))
161
+ )
162
+
163
+ smem_allocated = cute.size_in_bytes(mX.element_type, cute.make_layout(tiler_mn)) + 2 * num_warps * cluster_n * (cutlass.Float32.width // 8) + 2 * (cutlass.Int64.width // 8)
164
+ cross_entropy_kernel(mX, mTarget, mLoss, tv_layout, tiler_mn, cluster_n).launch(
165
+ grid=[cute.ceil_div(mX.shape[0], tiler_mn[0]), cluster_n, 1],
166
+ block=[cute.size(tv_layout, mode=[0]), 1, 1],
167
+ # Launching with cluster=[1, 1, 1] instead of None slows down the kernel by ~8us
168
+ cluster=[1, cluster_n, 1] if cluster_n > 1 else None,
169
+ smem=smem_allocated,
170
+ stream=stream,
171
+ )
172
+
173
+
174
+ torch2cute_dtype_map = {
175
+ torch.float16: cutlass.Float16,
176
+ torch.bfloat16: cutlass.BFloat16,
177
+ torch.float32: cutlass.Float32,
178
+ }
179
+
180
+
181
+ def cross_entropy(
182
+ x: torch.Tensor,
183
+ target: torch.Tensor,
184
+ ) -> torch.Tensor:
185
+ """Cross entropy forward pass.
186
+
187
+ Args:
188
+ x: Input logits tensor of shape (M, N)
189
+ target: Target class indices tensor of shape (M,)
190
+
191
+ Returns:
192
+ Cross entropy loss tensor of shape (M,)
193
+ """
194
+ assert x.dim() == 2, "Input must be 2D"
195
+ assert target.dim() == 1, "Target must be 1D"
196
+ assert x.shape[0] == target.shape[0], "Batch dimensions must match"
197
+ assert x.is_cuda and target.is_cuda, "Tensors must be on CUDA device"
198
+ assert x.dtype in [torch.float16, torch.bfloat16, torch.float32], "Unsupported input dtype"
199
+ assert target.dtype == torch.int64, "Target must be int64"
200
+ M, N = x.shape
201
+ device = x.device
202
+ loss = torch.empty(M, device=device, dtype=x.dtype)
203
+ dtype = torch2cute_dtype_map[x.dtype]
204
+ convert_from_dlpack = lambda tensor: (
205
+ from_dlpack(tensor.detach(), assumed_align=16)
206
+ .mark_compact_shape_dynamic(mode=0, stride_order=(0, 1))
207
+ )
208
+ x_tensor, = [convert_from_dlpack(tensor) for tensor in (x,)]
209
+ loss_tensor = from_dlpack(loss.detach(), assumed_align=4).mark_compact_shape_dynamic(mode=0)
210
+ target_tensor = from_dlpack(target.detach(), assumed_align=8).mark_compact_shape_dynamic(mode=0)
211
+ stream = cuda.CUstream(torch.cuda.current_stream().cuda_stream)
212
+ compile_key = (dtype, N)
213
+ if compile_key not in cross_entropy.compile_cache:
214
+ cross_entropy.compile_cache[compile_key] = cute.compile(
215
+ cross_entropy_interface, x_tensor, target_tensor, loss_tensor, stream, N
216
+ )
217
+ cross_entropy.compile_cache[compile_key](x_tensor, target_tensor, loss_tensor, stream)
218
+ return loss
219
+
220
+
221
+ cross_entropy.compile_cache = {}
quack/rmsnorm.py ADDED
@@ -0,0 +1,271 @@
1
+ # Copyright (c) 2025, Wentao Guo, Ted Zadouri, Tri Dao.
2
+
3
+ import math
4
+ import operator
5
+
6
+ import torch
7
+
8
+ import cuda.bindings.driver as cuda
9
+
10
+ import cutlass
11
+ import cutlass.cute as cute
12
+ from cutlass.cute.runtime import from_dlpack
13
+
14
+ import quack.utils as utils
15
+
16
+
17
+ @cute.kernel
18
+ def rmsnorm_kernel(
19
+ gX: cute.Tensor,
20
+ gW: cute.Tensor,
21
+ gO: cute.Tensor,
22
+ gRstd: cute.Tensor,
23
+ cX: cute.Tensor, # coordinate tensor
24
+ eps: cute.Float32,
25
+ shape: cute.Shape,
26
+ tv_layout: cute.Layout,
27
+ tiler_mn: cute.Shape,
28
+ cluster_n: cutlass.Constexpr = 1,
29
+ reload_from: cutlass.Constexpr = None,
30
+ delay_w_load: cutlass.Constexpr = False,
31
+ ):
32
+ tidx, _, _ = cute.arch.thread_idx()
33
+ bidx, cluster_y, _ = cute.arch.block_idx()
34
+ gdim, _, _ = cute.arch.grid_dim()
35
+
36
+ # slice for CTAs
37
+ # logical id -> address
38
+ blkX, blkOut, blkRstd, blkCrd = [gT[(None, None), bidx if cluster_n == 1 else (bidx, cluster_y)] for gT in (gX, gO, gRstd, cX)]
39
+ blkW = gW[(None, None), 0 if cluster_n == 1 else (0, cluster_y)]
40
+
41
+ # declare the atoms which will be used later for memory copy
42
+ copy_atom_load_X = cute.make_copy_atom(cute.nvgpu.CopyUniversalOp(), gX.element_type, num_bits_per_copy=128)
43
+ copy_atom_load_X_async = cute.make_copy_atom(cute.nvgpu.cpasync.CopyG2SOp(), gX.element_type, num_bits_per_copy=128)
44
+ copy_atom_load_W = cute.make_copy_atom(cute.nvgpu.CopyUniversalOp(), gW.element_type, num_bits_per_copy=128)
45
+ copy_atom_store_O = cute.make_copy_atom(cute.nvgpu.CopyUniversalOp(), gO.element_type, num_bits_per_copy=128)
46
+
47
+ thr_copy_X = cute.make_tiled_copy(copy_atom_load_X, tv_layout, tiler_mn).get_slice(tidx)
48
+ thr_copy_X_async = cute.make_tiled_copy(copy_atom_load_X_async, tv_layout, tiler_mn).get_slice(tidx)
49
+ thr_copy_W = cute.make_tiled_copy(copy_atom_load_W, tv_layout, tiler_mn).get_slice(tidx)
50
+ thr_copy_O = cute.make_tiled_copy(copy_atom_store_O, tv_layout, tiler_mn).get_slice(tidx)
51
+
52
+ smem = cutlass.utils.SmemAllocator()
53
+ # Don't use blkX.layout here, because the stride is N, not N_rounded
54
+ sX = smem.allocate_tensor(gX.element_type, cute.make_ordered_layout(blkX.shape, order=(1, 0)), byte_alignment=16)
55
+ num_warps = cute.size(tv_layout, mode=[0]) // cute.arch.WARP_SIZE
56
+ warps_per_row = utils.max_constexpr(tv_layout.shape[0][0] // cute.arch.WARP_SIZE, 1)
57
+ # reduction_buffer_layout = cute.make_ordered_layout((num_warps // warps_per_row, warps_per_row), order=(1, 0))
58
+ reduction_buffer_layout = cute.make_ordered_layout((num_warps // warps_per_row, warps_per_row if cluster_n == 1 else (warps_per_row, cluster_n)), order=(1, 0))
59
+ reduction_buffer = smem.allocate_tensor(cutlass.Float32, reduction_buffer_layout, byte_alignment=4)
60
+ if cutlass.const_expr(cluster_n > 1):
61
+ mbar_ptr = smem.allocate(cutlass.Int64.width // 8, byte_alignment=8)
62
+ else:
63
+ mbar_ptr = None
64
+
65
+ tWgW = thr_copy_W.partition_S(blkW)
66
+ tXgX = thr_copy_X_async.partition_S(blkX)
67
+ tXsX = thr_copy_X_async.partition_S(sX)
68
+ tXgO, tXrRstd = [thr_copy_O.partition_D(blk) for blk in (blkOut, blkRstd)]
69
+ tXcX = thr_copy_X.partition_S(blkCrd)[(0, None), None, None]
70
+
71
+ # allocate fragments for gmem->rmem
72
+ tWrW = cute.make_fragment_like(tWgW)
73
+ tXrW = thr_copy_X.retile(tWrW)
74
+ tXrX, tXrO = [cute.make_fragment_like(thr) for thr in (tXgX, tXgO)]
75
+
76
+ if cluster_n > 1:
77
+ if tidx == 0:
78
+ cute.arch.mbarrier_init_arrive_cnt(mbar_ptr, 1)
79
+ cute.arch.mbarrier_init_fence()
80
+ if tidx == 0:
81
+ cute.arch.mbarrier_init_tx_bytes(mbar_ptr, num_warps * cluster_n * cutlass.Float32.width // 8)
82
+ # Cluster arrive after barrier init
83
+ cute.arch.cluster_arrive_relaxed()
84
+
85
+ tXpX = cute.make_fragment_like(tXgX[(0, None), None, None], cutlass.Boolean)
86
+ for i in range(cute.size(tXpX)):
87
+ tXpX[i] = cute.elem_less(tXcX[i][1], shape[1])
88
+ # tXrX.fill(0.0)
89
+ if tXcX[0][0] < shape[0]:
90
+ # cute.copy(copy_atom_load_X, tXgX, tXrX, pred=tXpX)
91
+ cute.copy(copy_atom_load_X_async, tXgX, tXsX, pred=tXpX)
92
+ cute.arch.cp_async_commit_group()
93
+
94
+ tWpW = cute.make_fragment_like(tWgW[(0, None), None, None], cutlass.Boolean)
95
+ tWcX = thr_copy_W.partition_S(blkCrd)[(0, None), None, None]
96
+ for i in range(cute.size(tWpW)):
97
+ tWpW[i] = cute.elem_less(tWcX[i][1], shape[1])
98
+ if not delay_w_load:
99
+ cute.copy(copy_atom_load_W, tWgW, tWrW, pred=tWpW)
100
+
101
+ cute.arch.cp_async_wait_group(0)
102
+ cute.autovec_copy(tXsX, tXrX)
103
+ x = tXrX.load().to(cute.Float32)
104
+ sum_sq_x = utils.warp_reduce(
105
+ (x * x).reduce(cute.ReductionOp.ADD, init_val=0.0, reduction_profile=0),
106
+ operator.add,
107
+ width=utils.min_constexpr(tv_layout.shape[0][0], cute.arch.WARP_SIZE),
108
+ )
109
+ if cutlass.const_expr(cluster_n > 1):
110
+ cute.arch.cluster_wait()
111
+ if cutlass.const_expr(warps_per_row > 1 or cluster_n > 1):
112
+ sum_sq_x = utils.block_or_cluster_reduce(
113
+ sum_sq_x, operator.add, reduction_buffer, mbar_ptr, init_val=0.0
114
+ )
115
+ rstd = utils.rsqrt(sum_sq_x / shape[1] + eps)
116
+ # Only the thread corresponding to column 0 writes out the rstd to gmem
117
+ if tXcX[0][1] == 0 and tXcX[0][0] < shape[0]:
118
+ if cutlass.const_expr(cluster_n == 1):
119
+ tXrRstd[0] = rstd
120
+ else:
121
+ if cute.arch.block_idx_in_cluster() == 0:
122
+ tXrRstd[0] = rstd
123
+ if delay_w_load:
124
+ cute.copy(copy_atom_load_W, tWgW, tWrW, pred=tWpW)
125
+ if reload_from == "smem":
126
+ cute.autovec_copy(tXsX, tXrX)
127
+ x = tXrX.load().to(cute.Float32)
128
+ elif reload_from == "gmem":
129
+ cute.copy(copy_atom_load_X, tXgX, tXrX, pred=tXpX)
130
+ x = tXrX.load().to(cute.Float32)
131
+ x_hat = x * rstd
132
+ w = tXrW.load().to(cute.Float32)
133
+ y = x_hat * w
134
+ tXrO.store(y.to(tXrO.element_type))
135
+ tOcX = thr_copy_O.partition_S(blkCrd)[(0, None), None, None]
136
+ tOpO = cute.make_fragment_like(tXgO[(0, None), None, None], cutlass.Boolean)
137
+ for i in range(cute.size(tOpO)):
138
+ tOpO[i] = cute.elem_less(tOcX[i][1], shape[1])
139
+ if tXcX[0][0] < shape[0]:
140
+ cute.copy(copy_atom_store_O, tXrO, tXgO, pred=tOpO)
141
+
142
+
143
+ @cute.jit
144
+ def rmsnorm_interface(
145
+ # mX_: cute.Tensor,
146
+ mX: cute.Tensor,
147
+ mW: cute.Tensor,
148
+ mOut: cute.Tensor,
149
+ mRstd: cute.Tensor,
150
+ stream: cuda.CUstream,
151
+ N: cutlass.Constexpr,
152
+ eps: cutlass.Float32 = 1e-6,
153
+ copy_bits: cutlass.Constexpr = 128
154
+ ):
155
+ # new_shape = (mX_.shape[0], cute.assume(mX_.shape[1], 128))
156
+ # breakpoint()
157
+ # mX = cute.make_tensor(mX_.iterator, cute.make_layout(new_shape, stride=mX_.stride))
158
+ vecsize = copy_bits // mX.element_type.width
159
+ assert N % vecsize == 0, f"Input N {N} is not divisible by vector size {vecsize}"
160
+ num_threads = 128 if N <= 16384 else 256
161
+ num_warps = num_threads // cute.arch.WARP_SIZE
162
+ assert num_threads % cute.arch.WARP_SIZE == 0
163
+ threads_per_row = 8 if N <= 64 else (16 if N <= 128 else (32 if N <= 3072 else (64 if N <= 6144 else (128 if N <= 16384 else 256))))
164
+ # cluster_n = 4 is faster and cluster_n = 2 for N=64k for some reason
165
+ # Similarly cluster_n = 8 is faster for N=128k
166
+ if cutlass.const_expr(mX.element_type.width == 16):
167
+ cluster_n = 1 if N <= 16 * 1024 else (2 if N <= 32 * 1024 else (4 if N <= 64 * 1024 else (8 if N <= 128 * 1024 else 16)))
168
+ else: # fp32
169
+ cluster_n = 1 if N <= 32 * 1024 else (2 if N <= 64 * 1024 else (4 if N <= 128 * 1024 else (8 if N <= 256 * 1024 else 16)))
170
+
171
+ num_blocks_N = cute.ceil_div(N // vecsize, threads_per_row * cluster_n)
172
+ cols_per_block = num_threads // threads_per_row
173
+ tiler_mn = (cols_per_block, vecsize * num_blocks_N * threads_per_row) # This rounds up N
174
+ tv_layout = cute.make_layout(
175
+ ((threads_per_row, cols_per_block), (vecsize, num_blocks_N)),
176
+ stride=((vecsize * cols_per_block, 1), (cols_per_block, cols_per_block * vecsize * threads_per_row))
177
+ )
178
+
179
+ mW_expanded_layout = cute.prepend(mW.layout, cute.make_layout((tiler_mn[0],), stride=(0,)))
180
+ mW_expanded = cute.make_tensor(mW.iterator, mW_expanded_layout)
181
+ mRstd_expanded_layout = cute.append(mRstd.layout, cute.make_layout((N,), stride=(0,)))
182
+ mRstd_expanded = cute.make_tensor(mRstd.iterator, mRstd_expanded_layout)
183
+ idX = cute.make_identity_tensor(mX.shape)
184
+ gX, gW, gO, gRstd, cX = [cute.zipped_divide(mT, tiler_mn) for mT in (mX, mW_expanded, mOut, mRstd_expanded, idX)] # ((TileM,TileN),(RestM,RestN))
185
+
186
+ # reload_from = None if N <= 16384 else ("smem" if N <= 32768 else "gmem")
187
+ reload_from = None if N <= 16384 else "smem"
188
+ # delay_w_load = N > 64 * 1024
189
+ delay_w_load = False
190
+ N_rounded = tiler_mn[1]
191
+ rmsnorm_kernel(gX, gW, gO, gRstd, cX, eps, mX.shape, tv_layout, tiler_mn, cluster_n, reload_from).launch(
192
+ grid=[cute.size(gX, mode=[1, 0]), cluster_n, 1],
193
+ block=[cute.size(tv_layout, mode=[0]), 1, 1],
194
+ # Launching with cluster=[1, 1, 1] instead of None slows down the kernel by ~8us
195
+ cluster=[1, cluster_n, 1] if cluster_n > 1 else None,
196
+ # We don't want to use gX.layout[0] here since that has stride in N, not N_rounded, leading IMA on smem
197
+ smem=cute.size_in_bytes(mX.element_type, cute.make_layout(gX.shape[0])) + num_warps * cluster_n * (cutlass.Float32.width // 8) + (cutlass.Int64.width // 8),
198
+ stream=stream,
199
+ )
200
+
201
+
202
+ torch2cute_dtype_map = {
203
+ torch.float16: cutlass.Float16,
204
+ torch.bfloat16: cutlass.BFloat16,
205
+ torch.float32: cutlass.Float32,
206
+ }
207
+
208
+
209
+ def rmsnorm(
210
+ x: torch.Tensor,
211
+ weight: torch.Tensor,
212
+ eps: float = 1e-6,
213
+ return_rstd: bool = False,
214
+ ) -> torch.Tensor:
215
+ """RMSNorm forward pass.
216
+
217
+ Args:
218
+ x: Input tensor of shape (M, N)
219
+ weight: Weight tensor of shape (N,)
220
+ eps: Small value for numerical stability
221
+ return_rstd: Whether to return the reciprocal standard deviation
222
+
223
+ Returns:
224
+ Normalized output tensor of same shape as x
225
+ If return_rstd is True, also returns rstd tensor of shape (M,)
226
+ """
227
+ assert x.dim() == 2, "Input must be 2D"
228
+ assert weight.dim() == 1, "Weight must be 1D"
229
+ assert x.shape[-1] == weight.shape[0], "Last dimension of input must match weight dimension"
230
+ assert x.is_cuda and weight.is_cuda, "Tensors must be on CUDA device"
231
+ assert x.dtype in [torch.float16, torch.bfloat16, torch.float32], "Unsupported dtype"
232
+ assert weight.dtype == torch.float32, "Weight must be float32"
233
+ M, N = x.shape
234
+ device = x.device
235
+ out = torch.empty_like(x)
236
+ rstd = torch.empty(M, device=device, dtype=torch.float32)
237
+ dtype = torch2cute_dtype_map[x.dtype]
238
+ convert_from_dlpack = lambda x: (
239
+ from_dlpack(x.detach(), assumed_align=16)
240
+ .mark_compact_shape_dynamic(mode=0, stride_order=(0, 1))
241
+ )
242
+ x_tensor, out_tensor = [
243
+ # utils.convert_from_dlpack(t, leading_dim=t.ndim - 1, divisibility=128 // dtype.width)
244
+ convert_from_dlpack(t)
245
+ for t in (x, out)
246
+ ]
247
+ weight_tensor = utils.convert_from_dlpack(weight.detach(), leading_dim=0, divisibility=128 // cutlass.Float32.width)
248
+ rstd_tensor = from_dlpack(rstd.detach(), assumed_align=4).mark_layout_dynamic(leading_dim=0)
249
+ current_stream = cuda.CUstream(torch.cuda.current_stream().cuda_stream)
250
+ compile_key = (dtype, N)
251
+ if compile_key not in rmsnorm.compile_cache:
252
+ rmsnorm.compile_cache[compile_key] = cute.compile(
253
+ rmsnorm_interface, x_tensor, weight_tensor, out_tensor, rstd_tensor, current_stream, N
254
+ )
255
+ rmsnorm.compile_cache[compile_key](
256
+ x_tensor, weight_tensor, out_tensor, rstd_tensor, current_stream, eps
257
+ )
258
+ return (out, rstd) if return_rstd else out
259
+
260
+
261
+ rmsnorm.compile_cache = {}
262
+
263
+
264
+ def rmsnorm_ref(x, w, eps=1e-6):
265
+ x_f32 = x.float()
266
+ return (x_f32 / (torch.sqrt(torch.mean(x_f32 * x_f32, dim=-1, keepdim=True) + eps)) * w).to(x.dtype)
267
+
268
+
269
+ def rstd_ref(x, eps=1e-6):
270
+ x_f32 = x.float()
271
+ return 1.0 / torch.sqrt(torch.mean(x_f32 * x_f32, dim=-1) + eps)
quack/softmax.py ADDED
@@ -0,0 +1,202 @@
1
+ import math
2
+ import torch
3
+ import operator
4
+ from typing import Callable
5
+
6
+ import cuda.bindings.driver as cuda
7
+
8
+ import cutlass
9
+ import cutlass.cute as cute
10
+ from cutlass.cute.runtime import from_dlpack
11
+ import cutlass.torch as cutlass_torch
12
+
13
+ import quack.utils as utils
14
+
15
+
16
+ @cute.kernel
17
+ def softmax_kernel(
18
+ gX: cute.Tensor,
19
+ gO: cute.Tensor,
20
+ cX: cute.Tensor, # coordinate tensor
21
+ shape: cute.Shape,
22
+ tv_layout: cute.Layout,
23
+ tiler_mn: cute.Shape,
24
+ cluster_n: cutlass.Constexpr = 1,
25
+ ):
26
+ tidx, _, _ = cute.arch.thread_idx()
27
+ bidx, cluster_y, _ = cute.arch.block_idx()
28
+ gdim, _, _ = cute.arch.grid_dim()
29
+
30
+ # slice for CTAs
31
+ # logical id -> address
32
+ blkX, blkOut, blkCrd = [gT[(None, None), bidx if cluster_n == 1 else (bidx, cluster_y)] for gT in (gX, gO, cX)]
33
+
34
+ # declare the atoms which will be used later for memory copy
35
+ copy_atom_load_X = cute.make_copy_atom(cute.nvgpu.CopyUniversalOp(), gX.element_type, num_bits_per_copy=128)
36
+ copy_atom_load_X_async = cute.make_copy_atom(cute.nvgpu.cpasync.CopyG2SOp(), gX.element_type, num_bits_per_copy=128)
37
+ copy_atom_store_O = cute.make_copy_atom(cute.nvgpu.CopyUniversalOp(), gO.element_type, num_bits_per_copy=128)
38
+
39
+ thr_copy_X = cute.make_tiled_copy(copy_atom_load_X, tv_layout, tiler_mn).get_slice(tidx)
40
+ thr_copy_X_async = cute.make_tiled_copy(copy_atom_load_X_async, tv_layout, tiler_mn).get_slice(tidx)
41
+ thr_copy_O = cute.make_tiled_copy(copy_atom_store_O, tv_layout, tiler_mn).get_slice(tidx)
42
+
43
+ smem = cutlass.utils.SmemAllocator()
44
+ # Don't use blkX.layout here, because the stride is N, not N_rounded
45
+ sX = smem.allocate_tensor(gX.element_type, cute.make_ordered_layout(blkX.shape, order=(1, 0)), byte_alignment=16)
46
+ num_warps = cute.size(tv_layout, mode=[0]) // cute.arch.WARP_SIZE
47
+ warps_per_row = utils.max_constexpr(tv_layout.shape[0][0] // cute.arch.WARP_SIZE, 1)
48
+
49
+ reduction_buffer_layout = cute.make_ordered_layout(
50
+ # 2 stages: 1 for max, 1 for sum
51
+ (num_warps // warps_per_row, warps_per_row if cluster_n == 1 else (warps_per_row, cluster_n), 2),
52
+ order=(1, 0, 2)
53
+ )
54
+ reduction_buffer = smem.allocate_tensor(cutlass.Float32, reduction_buffer_layout, byte_alignment=4)
55
+ if cutlass.const_expr(cluster_n > 1):
56
+ # 1 mbar for max reduction, 1 mbar for sum reduction
57
+ mbar_ptr = smem.allocate_array(cutlass.Int64, num_elems=2)
58
+ else:
59
+ mbar_ptr = None
60
+
61
+ tXgX = thr_copy_X_async.partition_S(blkX)
62
+ tXsX = thr_copy_X_async.partition_S(sX)
63
+ tXgO = thr_copy_O.partition_D(blkOut)
64
+ tXcX = thr_copy_X.partition_S(blkCrd)[(0, None), None, None]
65
+
66
+ # allocate fragments for gmem->rmem
67
+ tXrX, tXrO = [cute.make_fragment_like(thr) for thr in (tXgX, tXgO)]
68
+
69
+ if cluster_n > 1:
70
+ if tidx < 2:
71
+ cute.arch.mbarrier_init_arrive_cnt(mbar_ptr + tidx, 1)
72
+ cute.arch.mbarrier_init_fence()
73
+ if tidx < 2:
74
+ cute.arch.mbarrier_init_tx_bytes(mbar_ptr + tidx, num_warps * cluster_n * cutlass.Float32.width // 8)
75
+ # Cluster arrive after barrier init
76
+ cute.arch.cluster_arrive_relaxed()
77
+
78
+ tXpX = cute.make_fragment_like(tXgX[(0, None), None, None], cutlass.Boolean)
79
+ for i in range(cute.size(tXpX)):
80
+ tXpX[i] = cute.elem_less(tXcX[i][1], shape[1])
81
+
82
+ if tXcX[0][0] < shape[0]:
83
+ cute.copy(copy_atom_load_X_async, tXgX, tXsX, pred=tXpX)
84
+ cute.arch.cp_async_commit_group()
85
+ cute.arch.cp_async_wait_group(0)
86
+
87
+ cute.autovec_copy(tXsX, tXrX)
88
+ x = tXrX.load().to(cute.Float32)
89
+ max_x = utils.warp_reduce(
90
+ x.reduce(cute.ReductionOp.MAX, init_val=float('-inf'), reduction_profile=0),
91
+ cute.arch.fmax,
92
+ width=utils.min_constexpr(tv_layout.shape[0][0], cute.arch.WARP_SIZE),
93
+ )
94
+ if cutlass.const_expr(cluster_n > 1):
95
+ cute.arch.cluster_wait()
96
+ if cutlass.const_expr(warps_per_row > 1 or cluster_n > 1):
97
+ max_mbar_ptr = mbar_ptr + 0 if cluster_n > 1 else None
98
+ max_x = utils.block_or_cluster_reduce(
99
+ max_x, cute.arch.fmax, reduction_buffer[None, None, 0], max_mbar_ptr, init_val=-cutlass.Float32.inf
100
+ )
101
+ log2_e = math.log2(math.e)
102
+ exp_x = cute.math.exp2((x - max_x) * log2_e, fastmath=True)
103
+ denom = utils.warp_reduce(
104
+ exp_x.reduce(cute.ReductionOp.ADD, init_val=0.0, reduction_profile=0),
105
+ operator.add,
106
+ width=utils.min_constexpr(tv_layout.shape[0][0], cute.arch.WARP_SIZE),
107
+ )
108
+ if cutlass.const_expr(warps_per_row > 1 or cluster_n > 1):
109
+ sum_mbar_ptr = mbar_ptr + 1 if cluster_n > 1 else None
110
+ denom = utils.block_or_cluster_reduce(
111
+ denom, operator.add, reduction_buffer[None, None, 1], sum_mbar_ptr, init_val=0.0
112
+ )
113
+ inv = 1.0 / denom
114
+ y = exp_x * inv
115
+
116
+ tXrO.store(y.to(tXrO.element_type))
117
+ tOcX = thr_copy_O.partition_S(blkCrd)[(0, None), None, None]
118
+ tOpO = cute.make_fragment_like(tXgO[(0, None), None, None], cutlass.Boolean)
119
+ for i in range(cute.size(tOpO)):
120
+ tOpO[i] = cute.elem_less(tOcX[i][1], shape[1])
121
+ if tXcX[0][0] < shape[0]:
122
+ cute.copy(copy_atom_store_O, tXrO, tXgO, pred=tOpO)
123
+
124
+
125
+ @cute.jit
126
+ def softmax_interface(
127
+ mX: cute.Tensor,
128
+ mOut: cute.Tensor,
129
+ stream: cuda.CUstream,
130
+ N: cutlass.Constexpr,
131
+ copy_bits: cutlass.Constexpr = 128
132
+ ):
133
+ vecsize = copy_bits // mX.element_type.width
134
+ assert N % vecsize == 0, f"Input N {N} is not divisible by vector size {vecsize}"
135
+ num_threads = 128 if N <= 16384 else 256
136
+ num_warps = num_threads // cute.arch.WARP_SIZE
137
+ assert num_threads % cute.arch.WARP_SIZE == 0
138
+ threads_per_row = 8 if N <= 64 else (16 if N <= 128 else (32 if N <= 3072 else (64 if N <= 6144 else (128 if N <= 16384 else 256))))
139
+ if cutlass.const_expr(mX.element_type.width == 16):
140
+ cluster_n = 1 if N <= 16 * 1024 else (2 if N <= 32 * 1024 else (4 if N <= 64 * 1024 else (8 if N <= 128 * 1024 else 16)))
141
+ else: # fp32
142
+ cluster_n = 1 if N <= 32 * 1024 else (2 if N <= 64 * 1024 else (4 if N <= 128 * 1024 else (8 if N <= 256 * 1024 else 16)))
143
+
144
+ num_blocks_N = cute.ceil_div(N // vecsize, threads_per_row * cluster_n)
145
+ cols_per_block = num_threads // threads_per_row
146
+ tiler_mn = (cols_per_block, vecsize * num_blocks_N * threads_per_row) # This rounds up N
147
+ tv_layout = cute.make_layout(
148
+ ((threads_per_row, cols_per_block), (vecsize, num_blocks_N)),
149
+ stride=((vecsize * cols_per_block, 1), (cols_per_block, cols_per_block * vecsize * threads_per_row))
150
+ )
151
+
152
+ idX = cute.make_identity_tensor(mX.shape)
153
+ gX, gO, cX = [cute.zipped_divide(mT, tiler_mn) for mT in (mX, mOut, idX)] # ((TileM,TileN),(RestM,RestN))
154
+
155
+ smem_allocated = cute.size_in_bytes(mX.element_type, cute.make_layout(gX.shape[0])) + 2 * num_warps * cluster_n * (cutlass.Float32.width // 8) + 2 * (cutlass.Int64.width // 8)
156
+ softmax_kernel(gX, gO, cX, mX.shape, tv_layout, tiler_mn, cluster_n).launch(
157
+ grid=[cute.size(gX, mode=[1, 0]), cluster_n, 1],
158
+ block=[cute.size(tv_layout, mode=[0]), 1, 1],
159
+ # Launching with cluster=[1, 1, 1] instead of None slows down the kernel by ~8us
160
+ cluster=[1, cluster_n, 1] if cluster_n > 1 else None,
161
+ smem=smem_allocated,
162
+ stream=stream,
163
+ )
164
+
165
+
166
+ torch2cute_dtype_map = {
167
+ torch.float16: cutlass.Float16,
168
+ torch.bfloat16: cutlass.BFloat16,
169
+ torch.float32: cutlass.Float32,
170
+ }
171
+
172
+
173
+ def softmax(x: torch.Tensor) -> torch.Tensor:
174
+ """Softmax forward pass.
175
+ Args:
176
+ x: Input tensor of shape (M, N)
177
+ Returns:
178
+ Softmax output tensor of same shape as x
179
+ """
180
+ assert x.dim() == 2, "Input must be 2D"
181
+ assert x.is_cuda, "Tensor must be on CUDA device"
182
+ assert x.dtype in [torch.float16, torch.bfloat16, torch.float32], "Unsupported dtype"
183
+ M, N = x.shape
184
+ device = x.device
185
+ out = torch.empty_like(x)
186
+ dtype = torch2cute_dtype_map[x.dtype]
187
+ convert_from_dlpack = lambda tensor: (
188
+ from_dlpack(tensor.detach(), assumed_align=16)
189
+ .mark_compact_shape_dynamic(mode=0, stride_order=(0, 1))
190
+ )
191
+ x_tensor, out_tensor = [convert_from_dlpack(tensor) for tensor in (x, out)]
192
+ current_stream = cuda.CUstream(torch.cuda.current_stream().cuda_stream)
193
+ compile_key = (dtype, N)
194
+ if compile_key not in softmax.compile_cache:
195
+ softmax.compile_cache[compile_key] = cute.compile(
196
+ softmax_interface, x_tensor, out_tensor, current_stream, N
197
+ )
198
+ softmax.compile_cache[compile_key](x_tensor, out_tensor, current_stream)
199
+ return out
200
+
201
+
202
+ softmax.compile_cache = {}
quack/utils.py ADDED
@@ -0,0 +1,190 @@
1
+ # Copyright (c) 2025, Wentao Guo, Ted Zadouri, Tri Dao.
2
+
3
+ import math
4
+ from typing import Type, Callable, Optional
5
+
6
+ import cutlass
7
+ import cutlass.cute as cute
8
+
9
+ from cutlass.cutlass_dsl import T, dsl_user_op
10
+ from cutlass._mlir.dialects import nvvm, llvm
11
+ from cutlass.cute.runtime import from_dlpack
12
+
13
+
14
+ def convert_from_dlpack(x, leading_dim, alignment=16, divisibility=1) -> cute.Tensor:
15
+ return (
16
+ from_dlpack(x, assumed_align=alignment)
17
+ .mark_layout_dynamic(leading_dim=leading_dim)
18
+ .mark_compact_shape_dynamic(
19
+ mode=leading_dim, stride_order=x.dim_order(), divisibility=divisibility
20
+ )
21
+ )
22
+
23
+
24
+ @cute.jit
25
+ def max_constexpr(
26
+ a: cutlass.Constexpr[cute.Numeric], b: cutlass.Constexpr[cute.Numeric]
27
+ ) -> cutlass.Constexpr[cute.Numeric]:
28
+ return a if a > b else b
29
+
30
+
31
+ @cute.jit
32
+ def min_constexpr(
33
+ a: cutlass.Constexpr[cute.Numeric], b: cutlass.Constexpr[cute.Numeric]
34
+ ) -> cutlass.Constexpr[cute.Numeric]:
35
+ return a if a < b else b
36
+
37
+
38
+ def warp_reduce(
39
+ val: cute.TensorSSA | cute.Numeric,
40
+ op: Callable,
41
+ width: cutlass.Constexpr[int] = cute.arch.WARP_SIZE
42
+ ) -> cute.TensorSSA | cute.Numeric:
43
+ if isinstance(val, cute.TensorSSA):
44
+ res = cute.make_fragment(val.shape, val.dtype)
45
+ res.store(val)
46
+ for i in range(cute.size(val.shape)):
47
+ res[i] = warp_reduce(res[i], op, width)
48
+ return res.load()
49
+ else:
50
+ for i in range(int(math.log2(width))):
51
+ val = op(val, cute.arch.shuffle_sync_bfly(val, offset=1 << i))
52
+ return val
53
+
54
+
55
+ @cute.jit
56
+ def block_reduce(val: cute.Numeric, op: Callable, reduction_buffer: cute.Tensor, init_val: cute.Numeric = 0.0) -> cute.Numeric:
57
+ """reduction_buffer has shape (num_warps / warp_per_row, warps_per_row)
58
+ """
59
+ lane_idx, warp_idx = cute.arch.lane_idx(), cute.arch.warp_idx()
60
+ warps_per_row = reduction_buffer.shape[1]
61
+ row_idx, col_idx = warp_idx // warps_per_row, warp_idx % warps_per_row
62
+ if lane_idx == 0:
63
+ reduction_buffer[row_idx, col_idx] = val
64
+ cute.arch.barrier()
65
+ block_reduce_val = init_val
66
+ if lane_idx < warps_per_row:
67
+ block_reduce_val = reduction_buffer[row_idx, lane_idx]
68
+ return warp_reduce(block_reduce_val, op)
69
+
70
+
71
+ @dsl_user_op
72
+ def elem_pointer(x: cute.Tensor, coord: cute.Coord, *, loc=None, ip=None) -> cute.Pointer:
73
+ return x.iterator + cute.crd2idx(coord, x.layout, loc=loc, ip=ip)
74
+
75
+
76
+ @dsl_user_op
77
+ def set_block_rank(smem_ptr: cute.Pointer, peer_cta_rank_in_cluster: cute.Int32, *, loc=None, ip=None) -> cutlass.Int32:
78
+ """Map the given smem pointer to the address at another CTA rank in the cluster.
79
+ """
80
+ smem_ptr_i32 = smem_ptr.toint(loc=loc, ip=ip).ir_value()
81
+ return cutlass.Int32(
82
+ llvm.inline_asm(
83
+ T.i32(),
84
+ [smem_ptr_i32, peer_cta_rank_in_cluster.ir_value()],
85
+ "mapa.shared::cluster.u32 $0, $1, $2;",
86
+ "=r,r,r",
87
+ has_side_effects=False,
88
+ is_align_stack=False,
89
+ asm_dialect=llvm.AsmDialect.AD_ATT,
90
+ )
91
+ )
92
+
93
+
94
+ @dsl_user_op
95
+ def store_shared_remote(
96
+ val: float | cute.Float32, smem_ptr: cute.Pointer, mbar_ptr: cute.Pointer,
97
+ peer_cta_rank_in_cluster: cute.typing.Int, *, loc=None, ip=None
98
+ ) -> None:
99
+ remote_smem_ptr_i32 = set_block_rank(smem_ptr, peer_cta_rank_in_cluster, loc=loc, ip=ip).ir_value()
100
+ remote_mbar_ptr_i32 = set_block_rank(mbar_ptr, peer_cta_rank_in_cluster, loc=loc, ip=ip).ir_value()
101
+ llvm.inline_asm(
102
+ None,
103
+ [remote_smem_ptr_i32, cute.Float32(val).ir_value(loc=loc, ip=ip), remote_mbar_ptr_i32],
104
+ "st.async.shared::cluster.mbarrier::complete_tx::bytes.f32 [$0], $1, [$2];",
105
+ "r,f,r",
106
+ has_side_effects=True,
107
+ is_align_stack=False,
108
+ asm_dialect=llvm.AsmDialect.AD_ATT,
109
+ )
110
+
111
+
112
+ @cute.jit
113
+ def cluster_reduce(val: cute.Numeric, op: Callable, reduction_buffer: cute.Tensor, mbar_ptr: cute.Pointer, init_val: cute.Numeric = 0.0) -> cute.Numeric:
114
+ """reduction_buffer has shape (num_warps / warps_per_row, (warps_per_row, cluster_n))
115
+ """
116
+ cta_rank_in_cluster = cute.arch.block_idx_in_cluster()
117
+ lane_idx, warp_idx = cute.arch.lane_idx(), cute.arch.warp_idx()
118
+ warps_per_row, cluster_n = reduction_buffer.shape[1]
119
+ row_idx, col_idx = warp_idx // warps_per_row, warp_idx % warps_per_row
120
+ if lane_idx < cluster_n:
121
+ store_shared_remote(
122
+ val, elem_pointer(reduction_buffer, (row_idx, (col_idx, cta_rank_in_cluster))),
123
+ mbar_ptr, peer_cta_rank_in_cluster=lane_idx
124
+ )
125
+ cute.arch.mbarrier_wait(mbar_ptr, phase=0)
126
+ block_reduce_val = init_val
127
+ num_iter = cute.ceil_div(warps_per_row * cluster_n, cute.arch.WARP_SIZE)
128
+ for i in cutlass.range_constexpr(num_iter):
129
+ idx = lane_idx + i * cute.arch.WARP_SIZE
130
+ if idx < cute.size(reduction_buffer, mode=[1]):
131
+ block_reduce_val = op(block_reduce_val, reduction_buffer[row_idx, idx])
132
+ return warp_reduce(block_reduce_val, op)
133
+
134
+
135
+ @cute.jit
136
+ def block_or_cluster_reduce(val: cute.Numeric, op: Callable, reduction_buffer: cute.Tensor, mbar_ptr: Optional[cute.Pointer], init_val: cute.Numeric = 0.0) -> cute.Numeric:
137
+ """Perform either block or cluster reduction based on whether mbar_ptr is provided.
138
+ """
139
+ if cutlass.const_expr(mbar_ptr is None):
140
+ return block_reduce(val, op, reduction_buffer, init_val=init_val)
141
+ else:
142
+ return cluster_reduce(val, op, reduction_buffer, mbar_ptr, init_val=init_val)
143
+
144
+
145
+ def exp2f(x: cute.TensorSSA | cutlass.Float32) -> cute.TensorSSA | cutlass.Float32:
146
+ """exp2f calculation for both vector and scalar.
147
+
148
+ :param x: input value
149
+ :type x: cute.TensorSSA or cutlass.Float32
150
+ :return: exp2 value
151
+ :rtype: cute.TensorSSA or cutlass.Float32
152
+ """
153
+ if isinstance(x, cute.TensorSSA):
154
+ res = cute.make_fragment(x.shape, cutlass.Float32)
155
+ res.store(x)
156
+ for i in range(cute.size(x.shape)):
157
+ res[i] = cute.arch.exp2(res[i])
158
+ return res.load()
159
+ else:
160
+ return cute.arch.exp2(x)
161
+
162
+
163
+ @dsl_user_op
164
+ def log2f(a: float | cutlass.Float32, *, loc=None, ip=None) -> cutlass.Float32:
165
+ return cutlass.Float32(
166
+ llvm.inline_asm(
167
+ T.f32(),
168
+ [cutlass.Float32(a).ir_value(loc=loc, ip=ip)],
169
+ "lg2.approx.ftz.f32 $0, $1;",
170
+ "=f,f",
171
+ has_side_effects=False,
172
+ is_align_stack=False,
173
+ asm_dialect=llvm.AsmDialect.AD_ATT,
174
+ )
175
+ )
176
+
177
+
178
+ @dsl_user_op
179
+ def rsqrt(a: float | cute.Float32, *, loc=None, ip=None) -> cute.Float32:
180
+ return cute.Float32(
181
+ llvm.inline_asm(
182
+ T.f32(),
183
+ [cute.Float32(a).ir_value(loc=loc, ip=ip)],
184
+ "rsqrt.approx.ftz.f32 $0, $1;",
185
+ "=f,f",
186
+ has_side_effects=False,
187
+ is_align_stack=False,
188
+ asm_dialect=llvm.AsmDialect.AD_ATT,
189
+ )
190
+ )
@@ -0,0 +1,7 @@
1
+ Metadata-Version: 2.4
2
+ Name: quack-kernels
3
+ Version: 0.1.0
4
+ Requires-Python: >=3.9
5
+ License-File: LICENSE
6
+ Requires-Dist: nvidia-cutlass-dsl==4.0.0
7
+ Dynamic: license-file
@@ -0,0 +1,10 @@
1
+ quack/__init__.py,sha256=ByNPsC-VY-f9BAa8IIS6dXlrwBQnzPPTiQqAZY6rYB8,137
2
+ quack/cross_entropy.py,sha256=V0kG8DCNh2735sPIDwe68NB50rAqDF3XQApnGyo-sKg,9220
3
+ quack/rmsnorm.py,sha256=RNqcT-q4uvMbF6ejpzuqQH8l8VVuTRlnueXf28V47sc,11954
4
+ quack/softmax.py,sha256=QABgOESH5JjDm3yuUkyZZKXXpzn7CTuMSs0NEBnFD80,8536
5
+ quack/utils.py,sha256=ofV7QLDuq80h3nEA3TwZW-ti8CnYwMgnz1dpxpvhHpk,6859
6
+ quack_kernels-0.1.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
7
+ quack_kernels-0.1.0.dist-info/METADATA,sha256=M4DjZ2lD1in6Wo9cPeAXiT0fY9sDxX1m9RQtR5b8OFg,165
8
+ quack_kernels-0.1.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
9
+ quack_kernels-0.1.0.dist-info/top_level.txt,sha256=6e4Jr_vNJbZTYwlO_Ahf_sDeHDE0zcqcf7Le11FKxxo,6
10
+ quack_kernels-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1 @@
1
+ quack