flash_api.cpp 244 KB
Newer Older
zhangshao's avatar
zhangshao committed
1
/******************************************************************************
hly's avatar
hly committed
2
3
* Copyright (c) 2023, Tri Dao.
******************************************************************************/
zhangshao's avatar
zhangshao committed
4
5
6
7

#include "flash_c_api.h"

#ifndef BUILD_C_INTERFACE
hly's avatar
hly committed
8
9
10
11
12
13
14
15
16
17
18
// Include these 2 headers instead of torch/extension.h since we don't need all of the torch headers.
// #include <torch/python.h>
#include <torch/nn/functional.h>
#include <torch/types.h>
#include <torch/extension.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/iostream.h>
#include <pybind11/complex.h>
#include <pybind11/functional.h>
#include <pybind11/chrono.h>
zhangshao's avatar
zhangshao committed
19
#include <ATen/ATen.h>
hly's avatar
hly committed
20
#include <ATen/hip/impl/HIPGuardImplMasqueradingAsCUDA.h>
zhangshao's avatar
zhangshao committed
21
22
23
#include <ATen/TensorIndexing.h>
#include <ATen/core/Tensor.h>

hly's avatar
hly committed
24
#if defined(USE_ROCM)
zhangshao's avatar
zhangshao committed
25
26
#include <ATen/hip/HIPGeneratorImpl.h>
#else
hly's avatar
hly committed
27
28
29
30
#ifndef TORCH_CUDA_CPP_API
#define TORCH_CUDA_CPP_API TORCH_API
#endif
#include <ATen/cuda/CUDAGeneratorImpL.h>
zhangshao's avatar
zhangshao committed
31
32
#endif

hly's avatar
hly committed
33
34
35
#define CHECK_DEVICE(x)     TORCH_CHECK(x.is_cuda(), #x " must be on CUDA (", __FILE__, ":", __LINE__, ")")
#define CHECK_SHAPE(x, ...) TORCH_CHECK(x.sizes() == at::IntArrayRef({__VA_ARGS__}), #x " must have shape (", at::IntArrayRef({__VA_ARGS__}), "), but got ", x.sizes(), " (", __FILE__, ":", __LINE__, ")")
#define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x " must be contiguous (", __FILE__, ":", __LINE__, ")")
zhangshao's avatar
zhangshao committed
36

hly's avatar
hly committed
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
static inline bool is_runtime_gfx92a(const std::string &gcn_arch_name) {
    return gcn_arch_name.rfind("gfx92a", 0) == 0;
}

static inline int runtime_gfx_arch_id(const std::string &gcn_arch_name) {
    return is_runtime_gfx92a(gcn_arch_name) ? 930 : std::stoi(gcn_arch_name.substr(3, 3));
}

static inline bool is_supported_hg_mla_arch(const std::string &gcn_arch_name, const int gcn_arch) {
    return is_runtime_gfx92a(gcn_arch_name) || gcn_arch >= 936;
}


void set_params_fprop(Flash_fwd_params &params,
                      // sizes
                      const size_t b,
                      const size_t seqlen_q,
                      const size_t seqlen_k,
                      const size_t seqlen_q_rounded,
                      const size_t seqlen_k_rounded,
                      const size_t h,
                      const size_t h_k,
                      const size_t d,
                      const size_t d_rounded,
                      const int d_v,
                      const int d_v_rounded,
                      // device pointers
                      const at::Tensor q,
                      const at::Tensor k,
                      const at::Tensor v,
                      at::Tensor out,
                      void *cu_seqlens_q_d,
                      void *cu_seqlens_k_d,
                      void *seqused_k,
                      void *p_d,
                      void *softmax_lse_d,
                      float p_dropout,
                      float softmax_scale,
                      int window_size_left,
                      int window_size_right,
                      float softcap=0.0,
                      bool seqlenq_ngroups_swapped=false,
                      const bool unpadded_lse=false,
                      const bool is_kvcache=false,
                      const bool is_seqlens_k_cumulative=false,
                      const int layout=0,
                      const bool is_flashmla=false,
                      const bool is_prefix=false
                    ) {

    // Reset the parameters
    memset(&params, 0, sizeof(params));

    params.is_int8 = q.dtype() == at::ScalarType::Char;
    if (!params.is_int8) {
        params.is_bf16 = q.dtype() == at::ScalarType::BFloat16;
zhangshao's avatar
zhangshao committed
93
    }
hly's avatar
hly committed
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
    params.is_e4m3 = q.dtype() == at::ScalarType::Float8_e4m3fn;

    // Set the pointers and strides.
    params.q_ptr = q.data_ptr();
    params.k_ptr = k.data_ptr();
    params.v_ptr = v.data_ptr();
    // All stride are in elements, not bytes.
    params.o_ptr = out.data_ptr();
    params.layout = layout;
    if (cu_seqlens_k_d == nullptr and !is_kvcache) {
        params.q_batch_stride = q.stride(0);
        params.k_batch_stride = k.stride(0);
        params.v_batch_stride = v.stride(0);
        params.o_batch_stride = out.stride(0);

        params.q_row_stride = params.layout ? q.stride(1): q.stride(2);
        params.k_row_stride = params.layout ? k.stride(1): k.stride(2);
        params.v_row_stride = params.layout ? v.stride(1): v.stride(2);
        params.o_row_stride = params.layout ? out.stride(1): out.stride(2);

        params.q_head_stride = params.layout ? q.stride(2): q.stride(1);
        params.k_head_stride = params.layout ? k.stride(2): k.stride(1);
        params.v_head_stride = params.layout ? v.stride(2): v.stride(1);
        params.o_head_stride = params.layout ? out.stride(2): out.stride(1);
        params.is_seqlens_k_cumulative = false;
        // params.varlen_proj_qkv_head = h; // uniform computation to reduce vgpr/sgpr
    }
    else {
        params.is_seqlens_k_cumulative = is_seqlens_k_cumulative;
        if (is_kvcache) {
            // when kvcache, q/o shape is different from training/prefill
            params.q_batch_stride = q.stride(0);
            params.o_batch_stride = out.stride(0);
            params.q_head_stride  = (layout == 1) ? q.stride(2): q.stride(1);
            params.k_head_stride  = (layout == 1) ? k.stride(2): k.stride(1);
            params.v_head_stride  = (layout == 1) ? v.stride(2): v.stride(1);
            params.o_head_stride  = (layout == 1) ? out.stride(2): out.stride(1);
            params.q_row_stride   = (layout == 1) ? q.stride(1): q.stride(2);
            params.k_row_stride   = (layout == 1) ? k.stride(1): k.stride(2);
            params.v_row_stride   = (layout == 1) ? v.stride(1): v.stride(2);
            params.o_row_stride   = (layout == 1) ? out.stride(1): out.stride(2);
        } else if (is_flashmla) {
            params.q_batch_stride = q.stride(0);
            params.o_batch_stride = out.stride(0);
            params.q_head_stride  = (layout == 1) ? q.stride(2): q.stride(1);
            params.k_head_stride  = (layout == 1) ? k.stride(2): k.stride(1);
            params.v_head_stride  = params.k_head_stride;
            params.o_head_stride  = (layout == 1) ? out.stride(2): out.stride(1);
            if (seqlenq_ngroups_swapped) params.o_head_stride *= seqlen_q;
            params.q_row_stride   = (layout == 1) ? q.stride(1): q.stride(2);
            params.k_row_stride   = (layout == 1) ? k.stride(1): k.stride(2);
            params.v_row_stride   = params.k_row_stride;
            params.o_row_stride   = (layout == 1) ? out.stride(1): out.stride(2);
        } else if (is_prefix) {
            params.q_head_stride = params.layout ? q.stride(-2): q.stride(0);
            params.k_head_stride = params.layout ? k.stride(-2): k.stride(0);
            params.v_head_stride = params.layout ? v.stride(-2): v.stride(0);
            params.o_head_stride = params.layout ? out.stride(1): out.stride(0);
            params.q_row_stride  = params.layout ? q.stride(0): params.q_head_stride;
            params.k_row_stride  = params.layout ? k.stride(1): params.k_head_stride;
            params.v_row_stride  = params.layout ? v.stride(1): params.v_head_stride;
            params.o_row_stride  = params.layout ? out.stride(0): params.o_head_stride;
        } else {
            params.q_head_stride = params.layout ? q.stride(-2): q.stride(0);
            params.k_head_stride = params.layout ? k.stride(-2): k.stride(0);
            params.v_head_stride = params.layout ? v.stride(-2): v.stride(0);
            params.o_head_stride = params.layout ? out.stride(1): out.stride(0);
            params.q_row_stride = params.layout ? q.stride(0): params.q_head_stride/*also .stride(0)*/;
            params.k_row_stride = params.layout ? k.stride(0): params.k_head_stride;
            params.v_row_stride = params.layout ? v.stride(0): params.v_head_stride;
            params.o_row_stride = params.layout ? out.stride(0): params.o_head_stride;
            // params.varlen_proj_qkv_head = params.layout ? k.stride(-3) / k.stride(-2): 0;
            // in vllm, K and V is not contiguous due to rope, but Q is contiguous. However, in some sceniros, K is contiguous but V is not contiguous()
        }
    }
    params.cu_seqlens_q = static_cast<int *>(cu_seqlens_q_d);
    params.cu_seqlens_k = static_cast<int *>(cu_seqlens_k_d);
    params.seqused_k = static_cast<int *>(seqused_k);
    params.p_ptr = p_d;

    // Softmax sum
    params.softmax_lse_ptr = softmax_lse_d;

    // Set the dimensions.
    params.b = b;
    params.h = h;
    params.h_k = h_k;
    params.h_h_k_ratio = h / h_k;
    params.seqlen_q = seqlen_q;
    params.seqlen_k = seqlen_k;
    params.seqlen_q_rounded = seqlen_q_rounded;
    params.seqlen_k_rounded = seqlen_k_rounded;
    params.d = d;
    params.d_rounded = d_rounded;
    params.d_value = d_v;
    params.d_value_rounded = d_v_rounded;
    params.seqlenq_ngroups_swapped = seqlenq_ngroups_swapped;

zhangshao's avatar
zhangshao committed
192
    // Set the different scale values.
hly's avatar
hly committed
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
    #ifdef FLASHATTENTION_DISABLE_SOFTCAP
        TORCH_CHECK(softcap <= 0.0, "This flash attention build does not support softcap.");
    #endif
    if (softcap > 0.0) {
        params.softcap = softmax_scale / softcap;
        params.scale_softmax = softcap;
        params.scale_softmax_log2 = softcap * M_LOG2E;
    } else{
        // Remove potential NaN
        params.softcap = 0.0;
        // Set the different scale values.
        params.scale_softmax = softmax_scale;
        params.scale_softmax_log2 = softmax_scale * M_LOG2E;
    }
    // Set this to probability of keeping an element to simplify things.
    params.p_dropout = 1.f - p_dropout;
    // Convert p from float to int so we don't have to convert the random uint to float to compare.
    // [Minor] We want to round down since when we do the comparison we use <= instead of <
    // params.p_dropout_in_uint = uint32_t(std::floor(params.p_dropout * 4294967295.0));
    // params.p_dropout_in_uint16_t = uint16_t(std::floor(params.p_dropout * 65535.0));
    params.p_dropout_in_uint8_t = uint8_t(std::floor(params.p_dropout * 255.0));
    params.rp_dropout = 1.f / params.p_dropout;
    params.scale_softmax_rp_dropout = params.rp_dropout * params.scale_softmax;
    TORCH_CHECK(p_dropout < 1.f);

    // Causal is the special case where window_size_right == 0 and window_size_left < 0.
    // Local is the more general case where window_size_right >= 0 or window_size_left >= 0.
    params.is_causal = window_size_left < 0 && window_size_right == 0;

    if (window_size_left < 0 && window_size_right >= 0) { window_size_left = seqlen_k; }
    if (window_size_left >= 0 && window_size_right < 0) { window_size_right = seqlen_k; }
    params.window_size_left = window_size_left;
    params.window_size_right = window_size_right;
zhangshao's avatar
zhangshao committed
226
227
}

hly's avatar
hly committed
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
void set_params_dgrad(Flash_bwd_params &params,
                      // sizes
                      const size_t b,
                      const size_t seqlen_q,
                      const size_t seqlen_k,
                      const size_t seqlen_q_rounded,
                      const size_t seqlen_k_rounded,
                      const size_t h,
                      const size_t h_k,
                      const size_t d,
                      const size_t d_rounded,
                      const int d_v,
                      const int d_v_rounded,
                      // device pointers
                      const at::Tensor q,
                      const at::Tensor k,
                      const at::Tensor v,
                      const at::Tensor out,
                      const at::Tensor dout,
                      at::Tensor dq,
                      at::Tensor dk,
                      at::Tensor dv,
                      void *cu_seqlens_q_d,
                      void *cu_seqlens_k_d,
                      void *p_d,
zhangshao's avatar
zhangshao committed
253
#ifdef DEBUGING
hly's avatar
hly committed
254
255
256
257
                      void *kq_ptr,
                      void *s_ptr,
                      void *dp_ptr,
                      void *ds_ptr,
zhangshao's avatar
zhangshao committed
258
#endif
hly's avatar
hly committed
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
                      void *dq_accum_d,
                      void *dk_accum_d,
                      void *dv_accum_d,
                      void *softmax_lse_d,
                      void *dsoftmax_sum_d,
                      float p_dropout,
                      float softmax_scale,
                      int window_size_left,
                      int window_size_right,
                      const float softcap=0.0,
                      bool deterministic=false,
                      const bool unpadded_lse=false,
                      const int layout=0) {

    set_params_fprop(params,
                     b, seqlen_q, seqlen_k, seqlen_q_rounded, seqlen_k_rounded, h, h_k, d, d_rounded,
                     d_v, d_v_rounded,
                     q, k, v, out,
                     cu_seqlens_q_d,
                     cu_seqlens_k_d,
                     nullptr,
                     nullptr,
                     softmax_lse_d,
                     p_dropout,
                     softmax_scale,
                     window_size_left,
                     window_size_right,
                     softcap,
                     false, // seqlenq_ngroups_swapped
                     unpadded_lse,
                     false,
                     true,
                     layout);
    // Set the pointers and strides.
    params.do_ptr = dout.data_ptr();
    params.dq_ptr = dq.data_ptr();
    params.dk_ptr = dk.data_ptr();
    params.dv_ptr = dv.data_ptr();

    if (cu_seqlens_q_d == nullptr) {
        params.do_batch_stride = dout.stride(0);
        params.dq_batch_stride = dq.stride(0);
        params.dk_batch_stride = dk.stride(0);
        params.dv_batch_stride = dv.stride(0);

        params.dq_row_stride = params.layout ? dq.stride(-3):dq.stride(-2);
        params.dk_row_stride = params.layout ? dk.stride(-3):dk.stride(-2);
        params.dv_row_stride = params.layout ? dv.stride(-3):dv.stride(-2);
        params.do_row_stride = params.layout ? dout.stride(-3):dout.stride(-2);
        params.dq_head_stride = params.layout ? dq.stride(-2) : dq.stride(-3);
        params.dk_head_stride = params.layout ? dk.stride(-2) : dk.stride(-3);
        params.dv_head_stride = params.layout ? dv.stride(-2) : dv.stride(-3);
        params.do_head_stride = params.layout ? dout.stride(-2) : dout.stride(-3);
    }
    else {
        params.q_batch_stride = q.stride(0);
        params.o_batch_stride = out.stride(0);

        params.dq_head_stride = dq.stride(-2);
        params.dk_head_stride = dk.stride(-2);
        params.dv_head_stride = dv.stride(-2);
        params.do_head_stride = dout.stride(-2);

        params.dq_row_stride = params.layout ? dq.stride(-3) : dq.stride(-2);
        params.dk_row_stride = params.layout ? dk.stride(-3) : dk.stride(-2);
        params.dv_row_stride = params.layout ? dv.stride(-3) : dv.stride(-2);
        params.do_row_stride = params.layout ? dout.stride(-3) : dout.stride(-2);
    }
    params.dq_accum_ptr = dq_accum_d;
    params.dk_accum_ptr = dk_accum_d;
    params.dv_accum_ptr = dv_accum_d;
zhangshao's avatar
zhangshao committed
330

hly's avatar
hly committed
331
332
    // Softmax sum
    params.dsoftmax_sum = dsoftmax_sum_d;
zhangshao's avatar
zhangshao committed
333

hly's avatar
hly committed
334
335
336
    // deterministic
    params.deterministic = deterministic;
    // PRINT_BWD_PARAMS
zhangshao's avatar
zhangshao committed
337
#ifdef DEBUGING
hly's avatar
hly committed
338
339
340
341
    params.kq_ptr = kq_ptr;
    params.s_ptr = s_ptr;
    params.dp_ptr = dp_ptr;
    params.ds_ptr = ds_ptr;
zhangshao's avatar
zhangshao committed
342
343
344
#endif
}

hly's avatar
hly committed
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376

// Find the number of splits that maximizes the occupancy. For example, if we have
// batch * n_heads = 48 and we have 108 SMs, having 2 splits (efficiency = 0.89) is
// better than having 3 splits (efficiency = 0.67). However, we also don't want too many
// splits as that would incur more HBM reads/writes.
// So we find the best efficiency, then find the smallest number of splits that gets 85%
// of the best efficiency.
inline int num_splits_heuristic(int batch_nheads_mblocks, int num_SMs, int num_n_blocks, int max_splits) {
    // If we have enough to almost fill the SMs, then just use 1 split
    if (batch_nheads_mblocks >= 0.8f * num_SMs) { return 1; }
    max_splits = std::min({max_splits, num_SMs, num_n_blocks});
    float max_efficiency = 0.f;
    std::vector<float> efficiency;
    efficiency.reserve(max_splits);
    auto ceildiv = [](int a, int b) { return (a + b - 1) / b; };
    // Some splits are not eligible. For example, if we have 64 blocks and choose 11 splits,
    // we'll have 6 * 10 + 4 blocks. If we choose 12 splits, we'll have 6 * 11 + (-2) blocks
    // (i.e. it's 11 splits anyway).
    // So we check if the number of blocks per split is the same as the previous num_splits.
    auto is_split_eligible = [&ceildiv, &num_n_blocks](int num_splits) {
        return num_splits == 1 || ceildiv(num_n_blocks, num_splits) != ceildiv(num_n_blocks, num_splits - 1);
    };
    for (int num_splits = 1; num_splits <= max_splits; num_splits++) {
        if (!is_split_eligible(num_splits)) {
            efficiency.push_back(0.f);
        } else {
            float n_waves = float(batch_nheads_mblocks * num_splits) / num_SMs;
            float eff = n_waves / ceil(n_waves);
            // printf("num_splits = %d, eff = %f\n", num_splits, eff);
            if (eff > max_efficiency) { max_efficiency = eff; }
            efficiency.push_back(eff);
        }
zhangshao's avatar
zhangshao committed
377
    }
hly's avatar
hly committed
378
379
380
381
382
383
    for (int num_splits = 1; num_splits <= max_splits; num_splits++) {
        if (!is_split_eligible(num_splits)) { continue; }
        if (efficiency[num_splits - 1] >= 0.85 * max_efficiency) {
            // printf("num_splits chosen = %d\n", num_splits);
            return num_splits;
        }
zhangshao's avatar
zhangshao committed
384
    }
hly's avatar
hly committed
385
    return 1;
zhangshao's avatar
zhangshao committed
386
387
}

hly's avatar
hly committed
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409

void set_params_dropout(Flash_fwd_params& params, float p_dropout, int counter_offset, at::Tensor& rng_state, c10::optional<at::Generator> gen_, at::TensorOptions opts, at::Tensor& dropout_debug_count) {
    if (p_dropout > 0) {
        rng_state = at::empty({2}, opts.dtype(at::ScalarType::Long));
        // Forward kernel will populate memory with the seed and offset.
        params.rng_state = reinterpret_cast<uint64_t*>(rng_state.data_ptr());
        auto gen = at::get_generator_or_default<at::CUDAGeneratorImpl>(
            gen_, at::cuda::detail::getDefaultCUDAGenerator());
        // See Note [Acquire lock when using random generators]
        std::lock_guard<std::mutex> lock(gen->mutex_);
        at::PhiloxCudaState philox_args = gen->philox_cuda_state(counter_offset);
        // at::cuda::philox::unpack(philox_args) not supported on ROCm
        params.rand_seed = philox_args.seed_.val;
        params.rand_offset = philox_args.offset_.val;
        // For dropout debugging tensor
        #ifdef FA_DEBUG
        dropout_debug_count = at::zeros({2}, opts.dtype(at::ScalarType::UInt32));
        params.dropout_debug_count = reinterpret_cast<uint32_t*>(dropout_debug_count.data_ptr());
        #endif
    } else {
        params.rng_state = nullptr;
    }
zhangshao's avatar
zhangshao committed
410
411
}

hly's avatar
hly committed
412
413

void set_params_alibi(Flash_fwd_params &params, c10::optional<at::Tensor> &alibi_slopes_, int batch_size, int num_heads){
zhangshao's avatar
zhangshao committed
414
#ifdef FLASHATTENTION_DISABLE_ALIBI
hly's avatar
hly committed
415
    TORCH_CHECK(!alibi_slopes_.has_value(), "This flash attention build does not support alibi.");
zhangshao's avatar
zhangshao committed
416
    params.alibi_slopes_ptr = nullptr;
hly's avatar
hly committed
417
418
419
420
421
422
423
424
425
426
427
428
#else
    if (alibi_slopes_.has_value()) {
        auto alibi_slopes = alibi_slopes_.value();
        TORCH_CHECK(alibi_slopes.dtype() == at::ScalarType::Float, "ALiBi slopes must have dtype fp32");
        CHECK_DEVICE(alibi_slopes);
        TORCH_CHECK(alibi_slopes.stride(-1) == 1, "ALiBi slopes tensor must have contiguous last dimension");
        TORCH_CHECK(alibi_slopes.sizes() == at::IntArrayRef({num_heads}) || alibi_slopes.sizes() == at::IntArrayRef({batch_size, num_heads}));
        params.alibi_slopes_ptr = alibi_slopes.data_ptr();
        params.alibi_slopes_batch_stride = alibi_slopes.dim() == 2 ? alibi_slopes.stride(0) : 0;
    } else {
        params.alibi_slopes_ptr = nullptr;
    }
zhangshao's avatar
zhangshao committed
429
430
431
#endif
}

hly's avatar
hly committed
432
433


zhangshao's avatar
zhangshao committed
434
std::vector<at::Tensor>
hly's avatar
hly committed
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
fwd_base(at::Tensor &q,
        const at::Tensor &k,
        const at::Tensor &v,
        c10::optional<at::Tensor> &out_,
        c10::optional<at::Tensor> &alibi_slopes_,
        const float p_dropout,
        const float softmax_scale,
        bool is_causal,
        int window_size_left,
        int window_size_right,
        const float softcap,
        const bool return_softmax,
        c10::optional<at::Generator> gen_,
        const int layout,
        c10::optional<at::Tensor> q_descale_,
        c10::optional<at::Tensor> k_descale_,
        c10::optional<at::Tensor> v_descale_,
        const bool is_bf16_output) {
zhangshao's avatar
zhangshao committed
453
#if defined(BUILD_FA_FWD)
hly's avatar
hly committed
454
455
456
457
458
459
460
461
462
463
464
465
    const at::cuda::HIPGuardMasqueradingAsCUDA device_guard(q.device().index());

    auto q_dtype = q.dtype();
    const bool fp8_used = q_dtype == at::ScalarType::Float8_e4m3fn;
    TORCH_CHECK(q_dtype == at::ScalarType::Half || q_dtype == at::ScalarType::BFloat16 || fp8_used,
                "FlashAttention only supports fp16, bf16, and fp8_e4m3 data type");
    TORCH_CHECK(k.dtype() == q_dtype, "query and key must have the same dtype");
    TORCH_CHECK(v.dtype() == q_dtype, "query and value must have the same dtype");
    if (fp8_used) {
        TORCH_CHECK(q_descale_.has_value() && k_descale_.has_value() && v_descale_.has_value(),
                    "FP8 forward requires q_descale, k_descale, and v_descale");
    }
zhangshao's avatar
zhangshao committed
466

hly's avatar
hly committed
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
    CHECK_DEVICE(q); CHECK_DEVICE(k); CHECK_DEVICE(v);

    TORCH_CHECK(q.stride(-1) == 1, "Input tensor must have contiguous last dimension");
    TORCH_CHECK(k.stride(-1) == 1, "Input tensor must have contiguous last dimension");
    TORCH_CHECK(v.stride(-1) == 1, "Input tensor must have contiguous last dimension");

    const bool use_bshd_layout = bool(layout == 1);
    const auto sizes = q.sizes();
    const int batch_size = sizes[0];
    int num_heads = use_bshd_layout ? sizes[2]: sizes[1];
    int seqlen_q = use_bshd_layout ? sizes[1]: sizes[2];
    const int head_size_og = sizes[3];
    const int head_size_og_value = v.size(3);
    const int num_heads_k = use_bshd_layout ? k.size(2): k.size(1);
    const int seqlen_k = use_bshd_layout ? k.size(1): k.size(2);
    TORCH_CHECK(seqlen_q == seqlen_k || is_causal == false, "FlashAttention forward do not support 'seqlen_k != seqlen_q && is_causal == true' for now")
    TORCH_CHECK(batch_size > 0, "batch size must be postive");
    TORCH_CHECK(head_size_og <= 512, "FlashAttention forward only supports head dimension at most 512");
    TORCH_CHECK(head_size_og_value <= 512, "FlashAttention forward only supports head dimension at most 512");
    TORCH_CHECK(num_heads % num_heads_k == 0, "Number of heads in key/value must divide number of heads in query");
    TORCH_CHECK(head_size_og >= head_size_og_value, "Head dimension of query/key must greater or equal to head dimension in query");

    if (softcap > 0.f) { TORCH_CHECK(p_dropout == 0.f, "Softcapping does not support dropout for now"); }

    if (window_size_left >= seqlen_k) { window_size_left = -1; }
    if (window_size_right >= seqlen_k) { window_size_right = -1; }

    TORCH_CHECK(int64_t(batch_size * num_heads * seqlen_q * head_size_og) < /*2^31*/int64_t(2147483648), "The data amount of q must be smaller than the representation range of int");
    TORCH_CHECK(int64_t(batch_size * num_heads_k * seqlen_k * head_size_og) < /*2^31*/int64_t(2147483648), "The data amount of k/v must be smaller than the representation range of int");

    if (seqlen_q == 1 && !alibi_slopes_.has_value()) { is_causal = false; }  // causal=true is the same as causal=false in this case
    if (is_causal) { window_size_right = 0; }

    // Faster to transpose q from (b, 1, (nheads_kv ngroups), d) to (b, ngroups, nheads_kv, d) in this case
    // H/t Daniel Haziza
    const int seqlenq_ngroups_swapped = seqlen_q == 1 && layout == 0 && num_heads > num_heads_k && window_size_left < 0 && window_size_right < 0 && p_dropout == 0.f && head_size_og % 8 == 0;
    if (seqlenq_ngroups_swapped) {
        const int ngroups = num_heads / num_heads_k;
        if (layout == 0) q = q.reshape({batch_size, num_heads_k, ngroups, head_size_og});
        else if (layout == 1) q = q.transpose(1, 2).reshape({batch_size, ngroups, num_heads_k, head_size_og});
        seqlen_q = ngroups;
        num_heads = num_heads_k;
    }
zhangshao's avatar
zhangshao committed
510

hly's avatar
hly committed
511
512
513
514
515
516
517
518
519
    if (layout == 0) {
        CHECK_SHAPE(q, batch_size, num_heads, seqlen_q, head_size_og);
        CHECK_SHAPE(k, batch_size, num_heads_k, seqlen_k, head_size_og);
        CHECK_SHAPE(v, batch_size, num_heads_k, seqlen_k, head_size_og_value);
    } else if (layout == 1) {
        CHECK_SHAPE(q, batch_size, seqlen_q, num_heads, head_size_og);
        CHECK_SHAPE(k, batch_size, seqlen_k, num_heads_k, head_size_og);
        CHECK_SHAPE(v, batch_size, seqlen_k, num_heads_k, head_size_og_value);
    }
zhangshao's avatar
zhangshao committed
520

hly's avatar
hly committed
521
522
523
524
    // For better performance for cases where headdim is not even multiple times of 32, assign head_size granularity
    const char* headdim_granularity_env = std::getenv("FA_HEADDIM_GRANULARITY");
    int headdim_granularity = headdim_granularity_env == nullptr ? 64: std::atoi(headdim_granularity_env);
    if (head_size_og % 32 == 0 or head_size_og_value % 32 == 0) { headdim_granularity = 32; }
zhangshao's avatar
zhangshao committed
525

hly's avatar
hly committed
526
527
528
529
530
531
532
533
    at::Tensor q_padded, k_padded, v_padded;
    if (head_size_og % headdim_granularity != 0) {
        q_padded = at::pad(q, {0, headdim_granularity - head_size_og % headdim_granularity});
        k_padded = at::pad(k, {0, headdim_granularity - head_size_og % headdim_granularity});
    } else {
        q_padded = q;
        k_padded = k;
    }
zhangshao's avatar
zhangshao committed
534

hly's avatar
hly committed
535
536
537
538
539
    if (head_size_og_value % headdim_granularity != 0) {
        v_padded = at::pad(v, {0, headdim_granularity - head_size_og_value % headdim_granularity});
    } else {
        v_padded = v;
    }
zhangshao's avatar
zhangshao committed
540

hly's avatar
hly committed
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
    at::Tensor out;
    auto opts = q.options();
    auto out_opts = fp8_used
        ? (is_bf16_output ? opts.dtype(at::ScalarType::BFloat16) : opts.dtype(at::ScalarType::Half))
        : opts;
    if (out_.has_value()) {
        out = out_.value();
        if (fp8_used) {
            TORCH_CHECK(out.dtype() == at::ScalarType::Half || out.dtype() == at::ScalarType::BFloat16,
                        "FP8 forward output must have fp16 or bf16 dtype");
        } else {
            TORCH_CHECK(out.dtype() == q_dtype, "Output must have the same dtype as inputs");
        }
        CHECK_DEVICE(out);
        TORCH_CHECK(out.stride(-1) == 1, "Output tensor must have contiguous last dimension");
        if (layout == 0) {
            CHECK_SHAPE(out, batch_size, num_heads, seqlen_q, head_size_og_value);
        } else if (layout == 1) {
            CHECK_SHAPE(out, batch_size, seqlen_q, num_heads, head_size_og_value);
        }
    } else {
        if (layout == 0) {
            out = at::empty({batch_size, num_heads, seqlen_q, head_size_og_value}, out_opts);
        } else if (layout == 1) {
            out = at::empty({batch_size, seqlen_q, num_heads, head_size_og_value}, out_opts);
        } else if (layout == 2) {
            out = at::empty({seqlen_q, batch_size, num_heads, head_size_og_value}, out_opts);
        }
    }
zhangshao's avatar
zhangshao committed
570

hly's avatar
hly committed
571
572
573
    if (head_size_og_value % headdim_granularity != 0) {
        out = at::pad(out, {0, headdim_granularity - head_size_og_value % headdim_granularity});
    }
zhangshao's avatar
zhangshao committed
574

hly's avatar
hly committed
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
    auto round_multiple = [](int x, int m) { return (x + m - 1) / m * m; };
    const int head_size = round_multiple(head_size_og, 8);
    const int head_size_rounded = round_multiple(head_size, headdim_granularity);
    const int head_size_v = round_multiple(head_size_og_value, 8);
    const int head_size_v_rounded = round_multiple(head_size_v, headdim_granularity);
    const int seqlen_q_rounded = round_multiple(seqlen_q, headdim_granularity);
    const int seqlen_k_rounded = round_multiple(seqlen_k, headdim_granularity);

    auto softmax_lse = at::empty({batch_size, num_heads, seqlen_q}, opts.dtype(at::kFloat));
    at::Tensor p;
    // Only return softmax if there's dropout to reduce compilation time
    if (return_softmax) {
        TORCH_CHECK(p_dropout > 0.0f, "return_softmax is only supported when p_dropout > 0.0");
        p = at::empty({ batch_size, num_heads, seqlen_q_rounded, seqlen_k_rounded }, opts);
    }
zhangshao's avatar
zhangshao committed
590

hly's avatar
hly committed
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
    Flash_fwd_params params;
    set_params_fprop(params,
                     batch_size,
                     seqlen_q, seqlen_k,
                     seqlen_q_rounded, seqlen_k_rounded,
                     num_heads, num_heads_k,
                     head_size, head_size_rounded,
                     head_size_v, head_size_v_rounded,
                     q_padded, k_padded, v_padded, out,
                     /*cu_seqlens_q_d=*/nullptr,
                     /*cu_seqlens_k_d=*/nullptr,
                     /*seqused_k=*/nullptr,
                     return_softmax ? p.data_ptr() : nullptr,
                     softmax_lse.data_ptr(),
                     p_dropout,
                     softmax_scale,
                     window_size_left,
                     window_size_right,
                     softcap,
                     /*seqlenq_ngroups_swapped*/seqlenq_ngroups_swapped,
                     /*unpadded_lse*/false,
                     /*is_kvcache*/false,
                     /*is_seqlens_k_cumulative*/false,
                     /*layout*/layout
                     );

    if (fp8_used) {
        at::Tensor q_descale = q_descale_.value();
        at::Tensor k_descale = k_descale_.value();
        at::Tensor v_descale = v_descale_.value();
        TORCH_CHECK(q_descale.dtype() == at::ScalarType::Float, "q_descale must have dtype float32");
        TORCH_CHECK(k_descale.dtype() == at::ScalarType::Float, "k_descale must have dtype float32");
        TORCH_CHECK(v_descale.dtype() == at::ScalarType::Float, "v_descale must have dtype float32");
        CHECK_DEVICE(q_descale); CHECK_DEVICE(k_descale); CHECK_DEVICE(v_descale);
        TORCH_CHECK(q_descale.dim() >= 2 && k_descale.dim() >= 2 && v_descale.dim() >= 2,
                    "FP8 descale tensors must have at least [batch, head] dimensions");
        params.is_bf16 = is_bf16_output;
        params.q_descale_ptr = reinterpret_cast<float*>(q_descale.data_ptr());
        params.k_descale_ptr = reinterpret_cast<float*>(k_descale.data_ptr());
        params.v_descale_ptr = reinterpret_cast<float*>(v_descale.data_ptr());
        params.q_descale_batch_stride = q_descale.stride(0);
        params.q_descale_head_stride  = q_descale.stride(1);
        params.k_descale_batch_stride = k_descale.stride(0);
        params.k_descale_head_stride  = k_descale.stride(1);
        params.v_descale_batch_stride = v_descale.stride(0);
        params.v_descale_head_stride  = v_descale.stride(1);
    }
zhangshao's avatar
zhangshao committed
638

hly's avatar
hly committed
639
640
641
642
643
644
    if (head_size_og % headdim_granularity != 0 or head_size_og_value % headdim_granularity != 0) {
        params.d       = head_size_rounded;
        params.d_value = head_size_v_rounded;
        params.qkvheaddim_compute = (int(std::max(head_size_og, head_size_og_value) / 32) + 1) * 32;
        params.qkvheaddim_tail_tile16 = std::max((head_size_og % 32 + 16 - 1) / 16, (head_size_og_value % 32 + 16 - 1) / 16);
    }
zhangshao's avatar
zhangshao committed
645

hly's avatar
hly committed
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
    // This needs to match with run_mha_fwd_splitkv_dispatch
    const int block_n = head_size <= 64 ? 256 : (head_size <= 128 ? 128 : 64);
    const int num_n_blocks = (seqlen_k + block_n - 1) / block_n;
    // Technically kBlockM = 64 only for the splitKV kernels, not the standard kernel.
    // In any case we don't expect seqlen_q to be larger than 64 for inference.
    const int num_m_blocks = (seqlen_q + 64 - 1) / 64;
    params.num_splits = 1;
    if (p_dropout == 0.0f) {  // SplitKV is not implemented for dropout
        params.num_splits = num_splits_heuristic(batch_size * num_heads * num_m_blocks,/*num_SMs*/ 1 /*dprops->multiProcessorCount*/, num_n_blocks, 128);
        if (params.num_splits > 1) {
            at::Tensor softmax_lse_accum = at::empty({params.num_splits, batch_size, num_heads, seqlen_q}, opts.dtype(at::kFloat));
            at::Tensor out_accum = at::empty({params.num_splits, batch_size, num_heads, seqlen_q, head_size_rounded}, opts.dtype(at::kFloat));
            params.softmax_lseaccum_ptr = softmax_lse_accum.data_ptr();
            params.oaccum_ptr = out_accum.data_ptr();
        }
        TORCH_CHECK(params.num_splits <= 128, "num_splits > 128 not supported");
    }
zhangshao's avatar
zhangshao committed
663

hly's avatar
hly committed
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
    // number of times random will be generated per thread, to offset philox counter in thc random
    // state
    // We use a custom RNG that increases the offset by batch_size * nheads * 32.
    at::Tensor rng_state;
    at::Tensor dropout_debug_count;
    int counter_offset = batch_size * num_heads * 64;
    set_params_dropout(params, p_dropout, counter_offset, rng_state, gen_, opts, dropout_debug_count);

    set_params_alibi(params, alibi_slopes_, batch_size, num_heads);

    const char* fa_debug = std::getenv("FA_DEBUG");
    if (fa_debug != nullptr) {
        if (std::strcmp(fa_debug, "1") == 0) { PRINT_PARAMS }
        else if (std::strcmp(fa_debug, "2") == 0) { PRINT_PARAMS_ONELINE }
        PRINT_QKV_INFO(q, k, v)
    }
zhangshao's avatar
zhangshao committed
680

hly's avatar
hly committed
681
682
    const hipStream_t stream = at::hip::getCurrentHIPStreamMasqueradingAsCUDA();
    run_mha_fwd(params, stream);
zhangshao's avatar
zhangshao committed
683

hly's avatar
hly committed
684
685
686
687
688
    #ifdef FA_DEBUG
    if (p_dropout > 0) {
        HIP_CHECK(hipDeviceSynchronize());
        std::cout << "rng_state: " << rng_state[0].item() << ", " << rng_state[1].item() << std::endl;
        std::cout << "dropout_debug_count: " << dropout_debug_count[0].item() << std::endl;
zhangshao's avatar
zhangshao committed
689
    }
hly's avatar
hly committed
690
691
692
693
694
695
    #endif

    at::Tensor out_padded = out;
    if (head_size_og_value % headdim_granularity != 0) {
        out = out.index({"...", at::indexing::Slice(at::indexing::None, head_size_og_value)}).contiguous();
        // if (out_.has_value()) { out_.value().copy_(out); }
zhangshao's avatar
zhangshao committed
696
697
    }

hly's avatar
hly committed
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
    if (seqlenq_ngroups_swapped) {
        if (layout == 0) {
            out = out.reshape({batch_size, num_heads_k * seqlen_q, 1, head_size_og_value});
            out_padded  = out_padded.reshape({batch_size, num_heads_k * seqlen_q, 1, head_size_og_value});
            q_padded    = q_padded.reshape({batch_size, num_heads_k * seqlen_q, 1, head_size_og_value});
            softmax_lse = softmax_lse.reshape({batch_size, num_heads_k * seqlen_q, 1});
        } else if (layout == 1) {
            out = out.transpose(1, 2).reshape({batch_size, 1, num_heads_k * seqlen_q, head_size_og_value});
            out_padded  = out_padded.transpose(1, 2).reshape({batch_size, 1, num_heads_k * seqlen_q, head_size_og_value});
            q_padded    = q_padded.transpose(1, 2).reshape({batch_size, 1, num_heads_k * seqlen_q, head_size_og_value});
            softmax_lse = softmax_lse.transpose(1, 2).reshape({batch_size, num_heads_k * seqlen_q, 1});
        }
    }
    return {out, q_padded, k_padded, v_padded, out_padded, softmax_lse, p, rng_state};
#else
    return {};
#endif
}
zhangshao's avatar
zhangshao committed
716
717
718



hly's avatar
hly committed
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
std::vector<at::Tensor>
hg_fwd_bhsd(at::Tensor &q,                           // batch_size x num_heads x seqlen_q x head_size
        const at::Tensor &k,                      // batch_size x num_heads x seqlen_q x head_size
        const at::Tensor &v,                      // batch_size x num_heads x seqlen_q x head_size
        c10::optional<at::Tensor> &out_,          // batch_size x num_heads x seqlen_q x head_size
        c10::optional<at::Tensor> &alibi_slopes_, // num_heads or batch_size x num_heads
        const float p_dropout,
        const float softmax_scale,
        bool is_causal,
        int window_size_left,
        int window_size_right,
        const float softcap,
        const bool return_softmax,
        c10::optional<at::Generator> gen_,
        c10::optional<at::Tensor> q_descale_,
        c10::optional<at::Tensor> k_descale_,
        c10::optional<at::Tensor> v_descale_,
        const bool is_bf16_output) {
    return fwd_base(q, k, v, out_, alibi_slopes_, p_dropout, softmax_scale, is_causal, window_size_left, window_size_right, softcap, return_softmax, gen_, 0/*bhsd*/, q_descale_, k_descale_, v_descale_, is_bf16_output);
}
zhangshao's avatar
zhangshao committed
739

hly's avatar
hly committed
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
std::vector<at::Tensor>
hg_fwd_bshd(at::Tensor &q,                           // batch_size x seqlen_q x num_heads x head_size
        const at::Tensor &k,                      // batch_size x seqlen_q x num_heads x head_size
        const at::Tensor &v,                      // batch_size x seqlen_q x num_heads x head_size
        c10::optional<at::Tensor> &out_,          // batch_size x seqlen_q x num_heads x head_size
        c10::optional<at::Tensor> &alibi_slopes_, // num_heads or batch_size x num_heads
        const float p_dropout,
        const float softmax_scale,
        bool is_causal,
        int window_size_left,
        int window_size_right,
        const float softcap,
        const bool return_softmax,
        c10::optional<at::Generator> gen_,
        c10::optional<at::Tensor> q_descale_,
        c10::optional<at::Tensor> k_descale_,
        c10::optional<at::Tensor> v_descale_,
        const bool is_bf16_output) {
    return fwd_base(q, k, v, out_, alibi_slopes_, p_dropout, softmax_scale, is_causal, window_size_left, window_size_right, softcap, return_softmax, gen_, 1/*bshd*/, q_descale_, k_descale_, v_descale_, is_bf16_output);
}
zhangshao's avatar
zhangshao committed
760

hly's avatar
hly committed
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
std::vector<at::Tensor>
fwd_padding_mask(at::Tensor &q,
        const at::Tensor &k,
        const at::Tensor &v,
        const at::Tensor &padding_mask,
        c10::optional<at::Tensor> &out_,
        c10::optional<at::Tensor> &alibi_slopes_,
        const float p_dropout,
        const float softmax_scale,
        bool is_causal,
        int window_size_left,
        int window_size_right,
        const float softcap,
        const bool return_softmax,
        c10::optional<at::Generator> gen_,
        int layout) {
#if defined(BUILD_FA_FWD)
    const at::cuda::HIPGuardMasqueradingAsCUDA device_guard(q.device().index());
    auto q_dtype = q.dtype();
    TORCH_CHECK(q_dtype == at::ScalarType::Half || q_dtype == at::ScalarType::BFloat16,
                "FlashAttention only support fp16 and bf16 data type");
    TORCH_CHECK(k.dtype() == q_dtype, "query and key must have the same dtype");
    TORCH_CHECK(v.dtype() == q_dtype, "query and value must have the same dtype");

    CHECK_DEVICE(q); CHECK_DEVICE(k); CHECK_DEVICE(v);

    TORCH_CHECK(q.stride(-1) == 1, "Input tensor must have contiguous last dimension");
    TORCH_CHECK(k.stride(-1) == 1, "Input tensor must have contiguous last dimension");
    TORCH_CHECK(v.stride(-1) == 1, "Input tensor must have contiguous last dimension");

    const bool use_bshd_layout = bool(layout == 1);
    const auto sizes = q.sizes();
    const int batch_size = sizes[0];
    int num_heads = use_bshd_layout ? sizes[2]: sizes[1];
    int seqlen_q = use_bshd_layout ? sizes[1]: sizes[2];
    const int head_size_og = sizes[3];
    const int head_size_og_value = v.size(3);
    const int num_heads_k = use_bshd_layout ? k.size(2): k.size(1);
    const int seqlen_k = use_bshd_layout ? k.size(1): k.size(2);
    TORCH_CHECK(batch_size > 0, "batch size must be postive");
    TORCH_CHECK(head_size_og <= 256, "FlashAttention forward only supports head dimension at most 256");
    TORCH_CHECK(head_size_og_value <= 256, "FlashAttention forward only supports head dimension at most 256");
    TORCH_CHECK(num_heads % num_heads_k == 0, "Number of heads in key/value must divide number of heads in query");
    TORCH_CHECK(head_size_og >= head_size_og_value, "Head dimension of query/key must greater or equal to head dimension in query");
    if ((head_size_og != 64 and head_size_og != 128) or (head_size_og_value != 64 and head_size_og_value != 128)) {
        printf("\x1b[31mOnly headdim 64/128 is supported for padding mask yet!\033[0m\n");
        return {};
    }
zhangshao's avatar
zhangshao committed
809

hly's avatar
hly committed
810
    if (softcap > 0.f) { TORCH_CHECK(p_dropout == 0.f, "Softcapping does not support dropout for now"); }
zhangshao's avatar
zhangshao committed
811

hly's avatar
hly committed
812
813
814
815
816
817
818
819
820
821
822
    if (window_size_left >= seqlen_k) { window_size_left = -1; }
    if (window_size_right >= seqlen_k) { window_size_right = -1; }

    TORCH_CHECK(int64_t(batch_size * num_heads * seqlen_q * head_size_og) < /*2^31*/int64_t(2147483648), "The data amount of q must be smaller than the representation range of int");
    TORCH_CHECK(int64_t(batch_size * num_heads_k * seqlen_k * head_size_og) < /*2^31*/int64_t(2147483648), "The data amount of k/v must be smaller than the representation range of int");

    if (seqlen_q == 1 && !alibi_slopes_.has_value()) { is_causal = false; }  // causal=true is the same as causal=false in this case
    if (is_causal) {
        window_size_right = 0;
        printf("\x1b[31mCausal mask is not supported for padding mask yet!\033[0m\n");
        return {};
zhangshao's avatar
zhangshao committed
823
824
    }

hly's avatar
hly committed
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
    // Faster to transpose q from (b, 1, (nheads_kv ngroups), d) to (b, ngroups, nheads_kv, d) in this case
    // H/t Daniel Haziza
    const int seqlenq_ngroups_swapped = seqlen_q == 1 && num_heads > num_heads_k && window_size_left < 0 && window_size_right < 0 && p_dropout == 0.f && head_size_og % 8 == 0;
    if (seqlenq_ngroups_swapped) {
        const int ngroups = num_heads / num_heads_k;
        q = q.reshape({batch_size, num_heads_k, ngroups, head_size_og});
        seqlen_q = ngroups;
        num_heads = num_heads_k;
    }
    // CHECK_SHAPE(q, batch_size, num_heads, seqlen_q, head_size_og);
    // CHECK_SHAPE(k, batch_size, num_heads_k, seqlen_k, head_size_og);
    // CHECK_SHAPE(v, batch_size, num_heads_k, seqlen_k, head_size_og_value);

    at::Tensor q_padded, k_padded, v_padded;
    if (head_size_og % 32 != 0) {
        q_padded = at::pad(q, {0, 32 - head_size_og % 32});
        k_padded = at::pad(k, {0, 32 - head_size_og % 32});
    } else {
        q_padded = q;
        k_padded = k;
    }
zhangshao's avatar
zhangshao committed
846

hly's avatar
hly committed
847
848
849
850
851
    if (head_size_og_value % 32 != 0) {
        v_padded = at::pad(v, {0, 32 - head_size_og_value % 32});
    } else {
        v_padded = v;
    }
zhangshao's avatar
zhangshao committed
852

hly's avatar
hly committed
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
    at::Tensor out;
    auto opts = q.options();
    if (out_.has_value()) {
        out = out_.value();
        TORCH_CHECK(out.dtype() == q_dtype, "Output must have the same dtype as inputs");
        CHECK_DEVICE(out);
        TORCH_CHECK(out.stride(-1) == 1, "Output tensor must have contiguous last dimension");
        // CHECK_SHAPE(out, batch_size, seqlen_q, num_heads, head_size_og_value);
    } else {
        if (layout == 0) {
            out = at::zeros({batch_size, num_heads, seqlen_q, head_size_og_value}, opts);
        } else if (layout == 1) {
            out = at::zeros({batch_size, seqlen_q, num_heads, head_size_og_value}, opts);
        } else if (layout == 2) {
            out = at::zeros({seqlen_q, batch_size, num_heads, head_size_og_value}, opts);
        }
    }
zhangshao's avatar
zhangshao committed
870

hly's avatar
hly committed
871
872
    if (head_size_og_value % 32 != 0) {
        out = at::pad(out, {0, 32 - head_size_og_value % 32});
zhangshao's avatar
zhangshao committed
873
    }
hly's avatar
hly committed
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936

    auto round_multiple = [](int x, int m) { return (x + m - 1) / m * m; };
    const int head_size = round_multiple(head_size_og, 8);
    const int head_size_rounded = round_multiple(head_size, 32);
    const int head_size_v = round_multiple(head_size_og_value, 8);
    const int head_size_v_rounded = round_multiple(head_size_v, 32);
    const int seqlen_q_rounded = round_multiple(seqlen_q, 32);
    const int seqlen_k_rounded = round_multiple(seqlen_k, 32);

    auto softmax_lse = at::empty({batch_size, num_heads, seqlen_q}, opts.dtype(at::kFloat));
    at::Tensor p, rng_state;

    Flash_fwd_params params;
    set_params_fprop(params,
                     batch_size,
                     seqlen_q, seqlen_k,
                     seqlen_q_rounded, seqlen_k_rounded,
                     num_heads, num_heads_k,
                     head_size, head_size_rounded,
                     head_size_v, head_size_v_rounded,
                     q_padded, k_padded, v_padded, out,
                     /*cu_seqlens_q_d=*/nullptr,
                     /*cu_seqlens_k_d=*/nullptr,
                     /*seqused_k=*/nullptr,
                     return_softmax ? p.data_ptr() : nullptr,
                     softmax_lse.data_ptr(),
                     p_dropout,
                     softmax_scale,
                     window_size_left,
                     window_size_right,
                     softcap,
                     /*seqlenq_ngroups_swapped*/false,
                     /*unpadded_lse*/false,
                     /*is_kvcache*/false,
                     /*is_seqlens_k_cumulative*/false,
                     /*layout*/layout
                     );
    params.padding_mask = padding_mask.data_ptr<int32_t>();

    set_params_alibi(params, alibi_slopes_, batch_size, num_heads);

    const char* fa_debug = std::getenv("FA_DEBUG");
    if (fa_debug != nullptr) {
        if (std::strcmp(fa_debug, "1") == 0) { PRINT_PARAMS }
        else if (std::strcmp(fa_debug, "2") == 0) { PRINT_PARAMS_ONELINE }
        PRINT_QKV_INFO(q, k, v)
    }

    const hipStream_t stream = at::hip::getCurrentHIPStreamMasqueradingAsCUDA();
    run_mha_fwd(params, stream);

    at::Tensor out_padded = out;
    if (head_size_og_value % 32 != 0) {
        out = out.index({"...", at::indexing::Slice(at::indexing::None, head_size_og_value)}).contiguous();
    }

    if (seqlenq_ngroups_swapped) {
        out = out.reshape({batch_size, num_heads_k * seqlen_q, 1, head_size_og_value});
        out_padded = out_padded.reshape({batch_size, num_heads_k * seqlen_q, 1, head_size_og_value});
        q_padded = q_padded.reshape({batch_size, num_heads_k * seqlen_q, 1, head_size_og_value});
        softmax_lse = softmax_lse.reshape({batch_size, num_heads_k * seqlen_q, 1});
    }
    return {out, q_padded, k_padded, v_padded, out_padded, softmax_lse, p, rng_state};
zhangshao's avatar
zhangshao committed
937
#else
hly's avatar
hly committed
938
    return {};
zhangshao's avatar
zhangshao committed
939
940
941
#endif
}

hly's avatar
hly committed
942

zhangshao's avatar
zhangshao committed
943
std::vector<at::Tensor>
hly's avatar
hly committed
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
fwd_attn_mask(at::Tensor &q,
        const at::Tensor &k,
        const at::Tensor &v,
        const at::Tensor &attn_mask,
        c10::optional<at::Tensor> &out_,
        c10::optional<at::Tensor> &alibi_slopes_,
        const float p_dropout,
        const float softmax_scale,
        bool is_causal,
        int window_size_left,
        int window_size_right,
        const float softcap,
        const bool return_softmax,
        c10::optional<at::Generator> gen_,
        int layout) {
#if defined(BUILD_FA_FWD)
    const at::cuda::HIPGuardMasqueradingAsCUDA device_guard(q.device().index());
    auto q_dtype = q.dtype();
    TORCH_CHECK(q_dtype == at::ScalarType::Half || q_dtype == at::ScalarType::BFloat16,
                "FlashAttention only support fp16 and bf16 data type");
    TORCH_CHECK(k.dtype() == q_dtype, "query and key must have the same dtype");
    TORCH_CHECK(v.dtype() == q_dtype, "query and value must have the same dtype");

    CHECK_DEVICE(q); CHECK_DEVICE(k); CHECK_DEVICE(v);

    TORCH_CHECK(q.stride(-1) == 1, "Input tensor must have contiguous last dimension");
    TORCH_CHECK(k.stride(-1) == 1, "Input tensor must have contiguous last dimension");
    TORCH_CHECK(v.stride(-1) == 1, "Input tensor must have contiguous last dimension");

    const bool use_bshd_layout = bool(layout == 1);
    const auto sizes = q.sizes();
    const int batch_size = sizes[0];
    int num_heads = use_bshd_layout ? sizes[2]: sizes[1];
    int seqlen_q = use_bshd_layout ? sizes[1]: sizes[2];
    const int head_size_og = sizes[3];
    const int head_size_og_value = v.size(3);
    const int num_heads_k = use_bshd_layout ? k.size(2): k.size(1);
    const int seqlen_k = use_bshd_layout ? k.size(1): k.size(2);
    TORCH_CHECK(batch_size > 0, "batch size must be postive");
    TORCH_CHECK(head_size_og <= 256, "FlashAttention forward only supports head dimension at most 256");
    TORCH_CHECK(head_size_og_value <= 256, "FlashAttention forward only supports head dimension at most 256");
    TORCH_CHECK(num_heads % num_heads_k == 0, "Number of heads in key/value must divide number of heads in query");
    TORCH_CHECK(head_size_og >= head_size_og_value, "Head dimension of query/key must greater or equal to head dimension in query");
    if (head_size_og != 128 or head_size_og_value != 128) {
        printf("\x1b[31mOnly headdim 128 is supported for attn mask yet!\033[0m\n");
        return {};
    }
zhangshao's avatar
zhangshao committed
991

hly's avatar
hly committed
992
    if (softcap > 0.f) { TORCH_CHECK(p_dropout == 0.f, "Softcapping does not support dropout for now"); }
zhangshao's avatar
zhangshao committed
993

hly's avatar
hly committed
994
995
    if (window_size_left >= seqlen_k) { window_size_left = -1; }
    if (window_size_right >= seqlen_k) { window_size_right = -1; }
zhangshao's avatar
zhangshao committed
996

hly's avatar
hly committed
997
998
    TORCH_CHECK(int64_t(batch_size * num_heads * seqlen_q * head_size_og) < /*2^31*/int64_t(2147483648), "The data amount of q must be smaller than the representation range of int");
    TORCH_CHECK(int64_t(batch_size * num_heads_k * seqlen_k * head_size_og) < /*2^31*/int64_t(2147483648), "The data amount of k/v must be smaller than the representation range of int");
zhangshao's avatar
zhangshao committed
999

hly's avatar
hly committed
1000
1001
1002
1003
1004
1005
    if (seqlen_q == 1 && !alibi_slopes_.has_value()) { is_causal = false; }  // causal=true is the same as causal=false in this case
    if (is_causal) {
        window_size_right = 0;
        printf("\x1b[31mCausal mask is not supported for attn mask yet!\033[0m\n");
        return {};
    }
zhangshao's avatar
zhangshao committed
1006

hly's avatar
hly committed
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
    // Faster to transpose q from (b, 1, (nheads_kv ngroups), d) to (b, ngroups, nheads_kv, d) in this case
    // H/t Daniel Haziza
    const int seqlenq_ngroups_swapped = seqlen_q == 1 && num_heads > num_heads_k && window_size_left < 0 && window_size_right < 0 && p_dropout == 0.f && head_size_og % 8 == 0;
    if (seqlenq_ngroups_swapped) {
        const int ngroups = num_heads / num_heads_k;
        q = q.reshape({batch_size, num_heads_k, ngroups, head_size_og});
        seqlen_q = ngroups;
        num_heads = num_heads_k;
    }

    if (layout == 0) {
        CHECK_SHAPE(q, batch_size, num_heads, seqlen_q, head_size_og);
        CHECK_SHAPE(k, batch_size, num_heads_k, seqlen_k, head_size_og);
        CHECK_SHAPE(v, batch_size, num_heads_k, seqlen_k, head_size_og_value);
    } else {
        CHECK_SHAPE(q, batch_size, seqlen_q, num_heads, head_size_og);
        CHECK_SHAPE(k, batch_size, seqlen_k, num_heads_k, head_size_og);
        CHECK_SHAPE(v, batch_size, seqlen_k, num_heads_k, head_size_og_value);
    }

    at::Tensor q_padded, k_padded, v_padded;
    if (head_size_og % 32 != 0) {
        q_padded = at::pad(q, {0, 32 - head_size_og % 32});
        k_padded = at::pad(k, {0, 32 - head_size_og % 32});
    } else {
        q_padded = q;
        k_padded = k;
    }

    if (head_size_og_value % 32 != 0) {
        v_padded = at::pad(v, {0, 32 - head_size_og_value % 32});
    } else {
        v_padded = v;
    }

    at::Tensor out;
    auto opts = q.options();
    if (out_.has_value()) {
        out = out_.value();
        TORCH_CHECK(out.dtype() == q_dtype, "Output must have the same dtype as inputs");
        CHECK_DEVICE(out);
        TORCH_CHECK(out.stride(-1) == 1, "Output tensor must have contiguous last dimension");
        if (layout == 0) {
            CHECK_SHAPE(out, batch_size, num_heads, seqlen_q, head_size_og_value);
        } else if (layout == 1) {
            CHECK_SHAPE(out, batch_size, seqlen_q, num_heads, head_size_og_value);
        }
    } else {
        if (layout == 0) {
            out = at::zeros({batch_size, num_heads, seqlen_q, head_size_og_value}, opts);
        } else if (layout == 1) {
            out = at::zeros({batch_size, seqlen_q, num_heads, head_size_og_value}, opts);
        } else if (layout == 2) {
            out = at::zeros({seqlen_q, batch_size, num_heads, head_size_og_value}, opts);
        }
    }

    if (head_size_og_value % 32 != 0) {
        out = at::pad(out, {0, 32 - head_size_og_value % 32});
    }

    auto round_multiple = [](int x, int m) { return (x + m - 1) / m * m; };
    const int head_size = round_multiple(head_size_og, 8);
    const int head_size_rounded = round_multiple(head_size, 32);
    const int head_size_v = round_multiple(head_size_og_value, 8);
    const int head_size_v_rounded = round_multiple(head_size_v, 32);
    const int seqlen_q_rounded = round_multiple(seqlen_q, 32);
    const int seqlen_k_rounded = round_multiple(seqlen_k, 32);

    auto softmax_lse = at::empty({batch_size, num_heads, seqlen_q}, opts.dtype(at::kFloat));
    at::Tensor p, rng_state;

    Flash_fwd_params params;
    set_params_fprop(params,
                     batch_size,
                     seqlen_q, seqlen_k,
                     seqlen_q_rounded, seqlen_k_rounded,
                     num_heads, num_heads_k,
                     head_size, head_size_rounded,
                     head_size_v, head_size_v_rounded,
                     q_padded, k_padded, v_padded, out,
                     /*cu_seqlens_q_d=*/nullptr,
                     /*cu_seqlens_k_d=*/nullptr,
                     /*seqused_k=*/nullptr,
                     return_softmax ? p.data_ptr() : nullptr,
                     softmax_lse.data_ptr(),
                     p_dropout,
                     softmax_scale,
                     window_size_left,
                     window_size_right,
                     softcap,
                     /*seqlenq_ngroups_swapped*/false,
                     /*unpadded_lse*/false,
                     /*is_kvcache*/false,
                     /*is_seqlens_k_cumulative*/false,
                     /*layout*/layout
                     );
    params.attn_mask = attn_mask.data_ptr<int32_t>();

    set_params_alibi(params, alibi_slopes_, batch_size, num_heads);

    const char* fa_debug = std::getenv("FA_DEBUG");
    if (fa_debug != nullptr) {
        if (std::strcmp(fa_debug, "1") == 0) { PRINT_PARAMS }
        else if (std::strcmp(fa_debug, "2") == 0) { PRINT_PARAMS_ONELINE }
        PRINT_QKV_INFO(q, k, v)
    }

    const hipStream_t stream = at::hip::getCurrentHIPStreamMasqueradingAsCUDA();
    run_mha_fwd(params, stream);

    at::Tensor out_padded = out;
    if (head_size_og_value % 32 != 0) {
        out = out.index({"...", at::indexing::Slice(at::indexing::None, head_size_og_value)}).contiguous();
    }

    if (seqlenq_ngroups_swapped) {
        out = out.reshape({batch_size, num_heads_k * seqlen_q, 1, head_size_og_value});
        out_padded = out_padded.reshape({batch_size, num_heads_k * seqlen_q, 1, head_size_og_value});
        q_padded = q_padded.reshape({batch_size, num_heads_k * seqlen_q, 1, head_size_og_value});
        softmax_lse = softmax_lse.reshape({batch_size, num_heads_k * seqlen_q, 1});
    }
    return {out, q_padded, k_padded, v_padded, out_padded, softmax_lse, p, rng_state};
#else
zhangshao's avatar
zhangshao committed
1131
    return {};
hly's avatar
hly committed
1132
1133
#endif
}
zhangshao's avatar
zhangshao committed
1134
1135


hly's avatar
hly committed
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
std::vector<at::Tensor> varlen_fwd(
        const at::Tensor &q,
        const at::Tensor &k,
        const at::Tensor &v,
        const int num_heads,
        const int num_heads_k,
        c10::optional<at::Tensor> &out_,
        const at::Tensor &cu_seqlens_q,
        const at::Tensor &cu_seqlens_k,
        c10::optional<at::Tensor> &seqused_k,
        c10::optional<at::Tensor> &alibi_slopes_,
        const int max_seqlen_q,
        const int max_seqlen_k,
        const float p_dropout,
        const float softmax_scale,
        const bool zero_tensors,
        const bool is_causal,
        int window_size_left,
        int window_size_right,
        const float softcap,
        const bool return_softmax,
        c10::optional<at::Generator> gen_,
        const int layout,
        c10::optional<at::Tensor> q_descale_,
        c10::optional<at::Tensor> k_descale_,
        c10::optional<at::Tensor> v_descale_,
        const bool is_bf16_output
) {
#if defined(BUILD_FA_FWD)
    const at::cuda::HIPGuardMasqueradingAsCUDA device_guard(q.device().index());
    if (is_causal) { window_size_right = 0; }

    auto q_dtype = q.dtype();
    const bool fp8_used = q_dtype == at::ScalarType::Float8_e4m3fn;
    TORCH_CHECK(q_dtype == at::ScalarType::Half || q_dtype == at::ScalarType::BFloat16 || fp8_used,
                "FlashAttention only supports fp16, bf16, and fp8_e4m3 data type");
    TORCH_CHECK(k.dtype() == q_dtype, "query and key must have the same dtype");
    TORCH_CHECK(v.dtype() == q_dtype, "query and value must have the same dtype");
    if (fp8_used) {
        TORCH_CHECK(q_descale_.has_value() && k_descale_.has_value() && v_descale_.has_value(),
                    "FP8 varlen forward requires q_descale, k_descale, and v_descale");
    }
    TORCH_CHECK(cu_seqlens_q.dtype() == at::ScalarType::Int, "cu_seqlens_q must have dtype int32");
    TORCH_CHECK(cu_seqlens_k.dtype() == at::ScalarType::Int, "cu_seqlens_k must have dtype int32");

    CHECK_DEVICE(q); CHECK_DEVICE(k); CHECK_DEVICE(v);
    CHECK_DEVICE(cu_seqlens_q);
    CHECK_DEVICE(cu_seqlens_k);

    TORCH_CHECK(q.stride(-1) == 1, "Input tensor must have contiguous last dimension");
    TORCH_CHECK(k.stride(-1) == 1, "Input tensor must have contiguous last dimension");
    TORCH_CHECK(v.stride(-1) == 1, "Input tensor must have contiguous last dimension");
    CHECK_CONTIGUOUS(cu_seqlens_q);
    CHECK_CONTIGUOUS(cu_seqlens_k);

    const bool use_bshd_layout = bool(layout == 1);
    const auto query_size   = q.sizes();
    const auto k_size       = k.sizes();
    const auto v_size       = v.sizes();
    const int head_size_og  = use_bshd_layout ? query_size[2]: query_size[1];
    const int head_size_value = use_bshd_layout ? v_size[2]: v_size[1]; //TODO:FBH
    const int total_q       = use_bshd_layout ? query_size[0] * query_size[1] / num_heads: query_size[0] / num_heads; // cu_seqlens_q[-1].item<int>();
    const int total_k       = use_bshd_layout ? k_size[0]:  k_size[0] / num_heads_k; // cu_seqlens_k[-1].item<int>();
    const int batch_size    = cu_seqlens_q.numel() - 1;
    TORCH_CHECK(batch_size > 0, "batch size must be positive");
    TORCH_CHECK(head_size_og <= 256, "FlashAttention forward only supports head dimension at most 256");
    TORCH_CHECK(head_size_value <= 256, "FlashAttention forward only supports head dimension at most 256");
    TORCH_CHECK(num_heads % num_heads_k == 0, "Number of heads in key/value must divide number of heads in query");
    TORCH_CHECK(int64_t(query_size[0] * head_size_og) < /*2^31*/int64_t(2147483648), "The data amount of q must be smaller than the representation range of int");
    TORCH_CHECK(int64_t(k_size[0] * head_size_value) < /*2^31*/int64_t(2147483648), "The data amount of k/v must be smaller than the representation range of int");
    CHECK_SHAPE(cu_seqlens_q, batch_size + 1);
    CHECK_SHAPE(cu_seqlens_k, batch_size + 1);

    if (softcap > 0.f) { TORCH_CHECK(p_dropout == 0.f, "Softcapping does not support dropout for now"); }

    if (seqused_k.has_value()) {
        auto seqused_k_ = seqused_k.value();
        TORCH_CHECK(seqused_k_.dtype() == at::ScalarType::Int, "seqused_k must have dtype int32");
        TORCH_CHECK(seqused_k_.is_cuda(), "seqused_k must be on CUDA device");
        TORCH_CHECK(seqused_k_.is_contiguous(), "seqused_k must be contiguous");
        CHECK_SHAPE(seqused_k_, batch_size);
    }
zhangshao's avatar
zhangshao committed
1218

hly's avatar
hly committed
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
    // For better performance for cases where headdim is not even multiple times of 32, assign head_size granularity
    const char* headdim_granularity_env = std::getenv("FA_HEADDIM_GRANULARITY");
    int headdim_granularity = headdim_granularity_env == nullptr ? 64: std::atoi(headdim_granularity_env);
    if (head_size_og % 32 == 0 or head_size_value % 32 == 0) { headdim_granularity = 32; }

    auto round_multiple = [](int x, int m) { return (x + m - 1) / m * m; };
    const int head_size = round_multiple(head_size_og, 8);
    const int head_size_rounded = round_multiple(head_size, headdim_granularity);
    const int head_size_v = round_multiple(head_size_value, 8);
    const int head_size_v_rounded = round_multiple(head_size_v, headdim_granularity);
    const int seqlen_q_rounded = round_multiple(max_seqlen_q, headdim_granularity);
    const int seqlen_k_rounded = round_multiple(max_seqlen_k, headdim_granularity);

    at::Tensor q_padded, k_padded, v_padded;
    if (head_size_og % headdim_granularity != 0) {
        q_padded = at::pad(q, {0, headdim_granularity - head_size_og % headdim_granularity});
        k_padded = at::pad(k, {0, headdim_granularity - head_size_og % headdim_granularity});
    } else {
        q_padded = q;
        k_padded = k;
    }
zhangshao's avatar
zhangshao committed
1240

hly's avatar
hly committed
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
    if (head_size_value % headdim_granularity != 0) {
        v_padded = at::pad(v, {0, headdim_granularity - head_size_value % headdim_granularity});
    } else {
        v_padded = v;
    }

    auto opts = q.options();
    auto out_opts = fp8_used
        ? (is_bf16_output ? opts.dtype(at::ScalarType::BFloat16) : opts.dtype(at::ScalarType::Half))
        : opts;
    at::Tensor out;
    if (out_.has_value()) {
        out = out_.value();
        if (fp8_used) {
            TORCH_CHECK(out.dtype() == at::ScalarType::Half || out.dtype() == at::ScalarType::BFloat16,
                        "FP8 varlen forward output must have fp16 or bf16 dtype");
        } else {
            TORCH_CHECK(out.dtype() == q_dtype, "Output must have the same dtype as inputs");
        }
        CHECK_DEVICE(out);
        TORCH_CHECK(out.stride(-1) == 1, "Output tensor must have contiguous last dimension");
        if (head_size_value % headdim_granularity != 0) {
            out = at::pad(out, {0, headdim_granularity - head_size_value % headdim_granularity});
        }
    } else {
        if (layout == 0) {out = at::empty({query_size[0], head_size_v_rounded}, out_opts);}
        else if (layout == 1) {out = at::empty({query_size[0], query_size[1], head_size_v_rounded}, out_opts);}
    }

    auto softmax_lse = at::empty({num_heads, total_q}, opts.dtype(at::kFloat));
    at::Tensor p;
    // Only return softmax if there's dropout to reduce compilation time
    if (return_softmax) {
        TORCH_CHECK(p_dropout > 0.0f, "return_softmax is only supported when p_dropout > 0.0");
        p = at::empty({ batch_size, num_heads, seqlen_q_rounded, seqlen_k_rounded }, opts);
    }

    if (zero_tensors) {
        out.zero_();
        softmax_lse.fill_(-std::numeric_limits<float>::infinity());
        if (return_softmax) {p.zero_();}
    }
    Flash_fwd_params params;
    set_params_fprop(params,
                     batch_size,
                     max_seqlen_q, max_seqlen_k,
                     seqlen_q_rounded, seqlen_k_rounded,
                     num_heads, num_heads_k,
                     head_size, head_size_rounded,
                     head_size_v, head_size_v_rounded,
                     q_padded, k_padded, v_padded, out,
                     cu_seqlens_q.data_ptr(),
                     cu_seqlens_k.data_ptr(),
                     return_softmax ? p.data_ptr() : nullptr,
                     seqused_k.has_value() ? seqused_k.value().data_ptr() : nullptr,
                     softmax_lse.data_ptr(),
                     p_dropout,
                     softmax_scale,
                     window_size_left,
                     window_size_right,
                     softcap,
                     false,
                     /*unpadded_lse*/false,
                     /*is_kvcache*/false,
                     /*is_seqlens_k_cumulative*/cu_seqlens_k.size(0) == (batch_size + 1),
                     layout
                    );
    params.total_q = total_q;
    params.total_k = total_k;
    if (fp8_used) {
        at::Tensor q_descale = q_descale_.value();
        at::Tensor k_descale = k_descale_.value();
        at::Tensor v_descale = v_descale_.value();
        TORCH_CHECK(q_descale.dtype() == at::ScalarType::Float, "q_descale must have dtype float32");
        TORCH_CHECK(k_descale.dtype() == at::ScalarType::Float, "k_descale must have dtype float32");
        TORCH_CHECK(v_descale.dtype() == at::ScalarType::Float, "v_descale must have dtype float32");
        CHECK_DEVICE(q_descale); CHECK_DEVICE(k_descale); CHECK_DEVICE(v_descale);
        TORCH_CHECK(q_descale.dim() >= 2 && k_descale.dim() >= 2 && v_descale.dim() >= 2,
                    "FP8 descale tensors must have at least [batch, head] dimensions");
        params.is_bf16 = is_bf16_output;
        params.q_descale_ptr = reinterpret_cast<float*>(q_descale.data_ptr());
        params.k_descale_ptr = reinterpret_cast<float*>(k_descale.data_ptr());
        params.v_descale_ptr = reinterpret_cast<float*>(v_descale.data_ptr());
        params.q_descale_batch_stride = q_descale.stride(0);
        params.q_descale_head_stride  = q_descale.stride(1);
        params.k_descale_batch_stride = k_descale.stride(0);
        params.k_descale_head_stride  = k_descale.stride(1);
        params.v_descale_batch_stride = v_descale.stride(0);
        params.v_descale_head_stride  = v_descale.stride(1);
    }
    if (head_size_og % headdim_granularity != 0 or head_size_value % headdim_granularity != 0) {
        params.d       = head_size_rounded;
        params.d_value = head_size_v_rounded;
        params.qkvheaddim_compute = (int(std::max(head_size_og, head_size_value) / 32) + 1) * 32/*mls32x32粒度是32*/;
        params.qkvheaddim_tail_tile16 = std::max((head_size_og % 32 + 16 - 1) / 16, (head_size_value % 32 + 16 - 1) / 16);
    }

    at::Tensor rng_state;
    at::Tensor dropout_debug_count;
    int counter_offset = batch_size * num_heads * 64;
    set_params_dropout(params, p_dropout, counter_offset, rng_state, gen_, opts, dropout_debug_count);

    set_params_alibi(params, alibi_slopes_, batch_size, num_heads);

    const char* fa_debug = std::getenv("FA_DEBUG");
    if (fa_debug != nullptr) {
        if (std::strcmp(fa_debug, "1") == 0) { PRINT_PARAMS }
        else if (std::strcmp(fa_debug, "2") == 0) {
            PRINT_PARAMS_ONELINE
            auto temp_tensor = cu_seqlens_k.to(at::DeviceType::CPU).contiguous();
            std::vector<int32_t> temp_vector(temp_tensor.data_ptr<int32_t>(), temp_tensor.data_ptr<int32_t>() + temp_tensor.numel());
            printf("cu_seqlens_k: ["); for (const auto val: temp_vector) { printf("%d ", val); } printf("]\n");
        }
        PRINT_QKV_INFO(q, k, v)
    }

    const hipStream_t stream = at::hip::getCurrentHIPStreamMasqueradingAsCUDA();
    run_mha_fwd(params, stream);

    #ifdef FA_DEBUG
    if (p_dropout > 0) {
        HIP_CHECK(hipDeviceSynchronize());
        std::cout << "rng_state: " << rng_state[0].item() << ", " << rng_state[1].item() << std::endl;
        std::cout << "dropout_debug_count: " << dropout_debug_count[0].item() << std::endl;
    }
    #endif

    at::Tensor out_padded = out;
    if (head_size_value % headdim_granularity != 0) {
        out = out.index({"...", at::indexing::Slice(at::indexing::None, head_size_value)});
        if (out_.has_value()) { out_.value().copy_(out); }
    }

    return {out, q_padded, k_padded, v_padded, out_padded, softmax_lse, p, rng_state};
#else
zhangshao's avatar
zhangshao committed
1376
    return {};
hly's avatar
hly committed
1377
1378
#endif
}
zhangshao's avatar
zhangshao committed
1379
1380
1381



hly's avatar
hly committed
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
std::vector<at::Tensor> hg_varlen_fwd_bshd(
        at::Tensor &q,
        at::Tensor &k,
        at::Tensor &v,
        c10::optional<at::Tensor> &out_,
        const at::Tensor &cu_seqlens_q,
        const at::Tensor &cu_seqlens_k,
        c10::optional<at::Tensor> &seqused_k,
        c10::optional<at::Tensor> &alibi_slopes_,
        const int max_seqlen_q,
        const int max_seqlen_k,
        const float p_dropout,
        const float softmax_scale,
        const bool zero_tensors,
        const bool is_causal,
        int window_size_left,
        int window_size_right,
        const float softcap,
        const bool return_softmax,
        c10::optional<at::Generator> gen_,
        c10::optional<at::Tensor> q_descale_,
        c10::optional<at::Tensor> k_descale_,
        c10::optional<at::Tensor> v_descale_,
        const bool is_bf16_output) {
    const at::cuda::HIPGuardMasqueradingAsCUDA device_guard(q.device().index());
    // [batch x seqlen, num_head, headdim] ----> [batch x num_head x seqlen, headdim]
    const auto query_size = q.sizes();
    const bool tensor_is_4dim = query_size.size() == 4;
    const int num_heads = tensor_is_4dim ? query_size[2]: query_size[1];
    const int num_heads_kv = tensor_is_4dim ? k.size(2): k.size(1);
    // FA kernel
    return varlen_fwd(
        q,
        k,
        v,
        num_heads,
        num_heads_kv,
        out_,
        cu_seqlens_q,
        cu_seqlens_k,
        seqused_k,
        alibi_slopes_,
        max_seqlen_q,
        max_seqlen_k,
        p_dropout,
        softmax_scale,
        zero_tensors,
        is_causal,
        window_size_left,
        window_size_right,
        softcap,
        return_softmax,
        gen_,
        1/*bshd*/,
        q_descale_,
        k_descale_,
        v_descale_,
        is_bf16_output);
}
zhangshao's avatar
zhangshao committed
1441

hly's avatar
hly committed
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
// Preserved for original inference interface
at::Tensor varlen_fwd_bshd_infer(
        at::Tensor &q,
        at::Tensor &k,
        at::Tensor &v,
        c10::optional<at::Tensor> &out_,
        const at::Tensor &cu_seqlens_q,
        const at::Tensor &cu_seqlens_k,
        c10::optional<at::Tensor> &seqused_k,
        c10::optional<at::Tensor> &alibi_slopes_,
        const int max_seqlen_q,
        const int max_seqlen_k,
        const float p_dropout,
        const float softmax_scale,
        const bool zero_tensors,
        const bool is_causal,
        int window_size_left,
        int window_size_right,
        const float softcap,
        const bool return_softmax,
        c10::optional<at::Generator> gen_,
        c10::optional<at::Tensor> q_descale_,
        c10::optional<at::Tensor> k_descale_,
        c10::optional<at::Tensor> v_descale_,
        const bool is_bf16_output) {
    return hg_varlen_fwd_bshd(q, k, v, out_, cu_seqlens_q, cu_seqlens_k, seqused_k, alibi_slopes_, max_seqlen_q, max_seqlen_k, p_dropout, softmax_scale, zero_tensors, is_causal, window_size_left, window_size_right, softcap, return_softmax, gen_, q_descale_, k_descale_, v_descale_, is_bf16_output)[0];
}




std::vector<at::Tensor> varlen_fwd_bhsd(
        const at::Tensor &q,
        const at::Tensor &k,
        const at::Tensor &v,
        c10::optional<at::Tensor> &out_,
        const at::Tensor &cu_seqlens_q,
        const at::Tensor &cu_seqlens_k,
        c10::optional<at::Tensor> &seqused_k,
        c10::optional<at::Tensor> &alibi_slopes_,
        const int max_seqlen_q,
        const int max_seqlen_k,
        const float p_dropout,
        const float softmax_scale,
        const bool zero_tensors,
        const bool is_causal,
        int window_size_left,
        int window_size_right,
        const float softcap,
        const bool return_softmax,
        c10::optional<at::Generator> gen_
){
#if defined(BUILD_FA_FWD)
    const at::cuda::HIPGuardMasqueradingAsCUDA device_guard(q.device().index());
    if (is_causal) { window_size_right = 0; }

    auto q_dtype = q.dtype();
    TORCH_CHECK(q_dtype == at::ScalarType::Half || q_dtype == at::ScalarType::BFloat16,
                "FlashAttention only support fp16 and bf16 data type");
    TORCH_CHECK(k.dtype() == q_dtype, "query and key must have the same dtype");
    TORCH_CHECK(v.dtype() == q_dtype, "query and value must have the same dtype");
    TORCH_CHECK(cu_seqlens_q.dtype() == at::ScalarType::Int, "cu_seqlens_q must have dtype int32");
    TORCH_CHECK(cu_seqlens_k.dtype() == at::ScalarType::Int, "cu_seqlens_k must have dtype int32");

    CHECK_DEVICE(q); CHECK_DEVICE(k); CHECK_DEVICE(v);
    CHECK_DEVICE(cu_seqlens_q);
    CHECK_DEVICE(cu_seqlens_k);

    TORCH_CHECK(q.stride(-1) == 1, "Input tensor must have contiguous last dimension");
    TORCH_CHECK(k.stride(-1) == 1, "Input tensor must have contiguous last dimension");
    TORCH_CHECK(v.stride(-1) == 1, "Input tensor must have contiguous last dimension");
    CHECK_CONTIGUOUS(cu_seqlens_q);
    CHECK_CONTIGUOUS(cu_seqlens_k);

    const auto sizes = q.sizes();
    const int total_q_heads = q.numel() / sizes[1];
    const int total_q       = cu_seqlens_q[-1].item<int>();
    const int batch_size    = cu_seqlens_q.numel() - 1;
    const int num_heads     = total_q_heads / total_q;
    const int head_size_og  = sizes[1];
    const int head_size_value = v.size(1);
    const int total_k_heads = k.numel() / k.size(1);
    const int total_k       = cu_seqlens_k[-1].item<int>();
    const int num_heads_k   = total_k_heads / total_k;
    TORCH_CHECK(batch_size > 0, "batch size must be positive");
    TORCH_CHECK(head_size_og <= 256, "FlashAttention forward only supports head dimension at most 256");
    TORCH_CHECK(head_size_value <= 256, "FlashAttention forward only supports head dimension at most 256 for V");
    TORCH_CHECK(num_heads % num_heads_k == 0, "Number of heads in key/value must divide number of heads in query");
    TORCH_CHECK(int64_t(total_q_heads * head_size_og) < /*2^31*/int64_t(2147483648), "The data amount of q must be smaller than the representation range of int");
    TORCH_CHECK(int64_t(total_k_heads * head_size_og) < /*2^31*/int64_t(2147483648), "The data amount of k/v must be smaller than the representation range of int");

    CHECK_SHAPE(q, total_q_heads, head_size_og);
    CHECK_SHAPE(k, total_k_heads, head_size_og);
    CHECK_SHAPE(v, total_k_heads, head_size_og);
    CHECK_SHAPE(cu_seqlens_q, batch_size + 1);
    CHECK_SHAPE(cu_seqlens_k, batch_size + 1);

    if (softcap > 0.f) { TORCH_CHECK(p_dropout == 0.f, "Softcapping does not support dropout for now"); }

    if (seqused_k.has_value()) {
        auto seqused_k_ = seqused_k.value();
        TORCH_CHECK(seqused_k_.dtype() == at::ScalarType::Int, "seqused_k must have dtype int32");
        TORCH_CHECK(seqused_k_.is_cuda(), "seqused_k must be on CUDA device");
        TORCH_CHECK(seqused_k_.is_contiguous(), "seqused_k must be contiguous");
        CHECK_SHAPE(seqused_k_, batch_size);
zhangshao's avatar
zhangshao committed
1547
1548
    }

hly's avatar
hly committed
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
    auto round_multiple = [](int x, int m) { return (x + m - 1) / m * m; };
    const int head_size = round_multiple(head_size_og, 8);
    const int head_size_rounded = round_multiple(head_size, 32);
    const int head_size_v = round_multiple(head_size_value, 8);
    const int head_size_v_rounded = round_multiple(head_size_v, 32);
    const int seqlen_q_rounded = round_multiple(max_seqlen_q, 32);
    const int seqlen_k_rounded = round_multiple(max_seqlen_k, 32);

    at::Tensor q_padded, k_padded, v_padded;
    if (head_size_og % 32 != 0) {
        q_padded = at::pad(q, {0, 32 - head_size_og % 32});
        k_padded = at::pad(k, {0, 32 - head_size_og % 32});
    } else {
        q_padded = q;
        k_padded = k;
    }
    if (head_size_value % 32 != 0) {
        v_padded = at::pad(v, {0, 32 - head_size_value % 32});
    } else {
        v_padded = v;
    }
zhangshao's avatar
zhangshao committed
1570

hly's avatar
hly committed
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
    auto opts = q.options();
    at::Tensor out;
    if (out_.has_value()) {
        out = out_.value();
        TORCH_CHECK(out.dtype() == q_dtype, "Output must have the same dtype as inputs");
        CHECK_DEVICE(out);
        TORCH_CHECK(out.stride(-1) == 1, "Output tensor must have contiguous last dimension");
        // CHECK_SHAPE(out, total_q, num_heads, head_size_value);
        if (head_size_value % 32 != 0) {
            out = at::pad(out, {0, 32 - head_size_value % 32});
        }
    } else {
        out = at::empty({total_q_heads, head_size_v_rounded}, opts);
    }
zhangshao's avatar
zhangshao committed
1585

hly's avatar
hly committed
1586
1587
1588
1589
1590
1591
1592
    auto softmax_lse = at::empty({num_heads, total_q}, opts.dtype(at::kFloat));
    at::Tensor p;
    // Only return softmax if there's dropout to reduce compilation time
    if (return_softmax) {
        TORCH_CHECK(p_dropout > 0.0f, "return_softmax is only supported when p_dropout > 0.0");
        p = at::empty({ batch_size, num_heads, seqlen_q_rounded, seqlen_k_rounded }, opts);
    }
zhangshao's avatar
zhangshao committed
1593

hly's avatar
hly committed
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
    if (zero_tensors) {
        out.zero_();
        softmax_lse.fill_(-std::numeric_limits<float>::infinity());
        if (return_softmax) {p.zero_();}
    }
    Flash_fwd_params params;
    set_params_fprop(params,
                     batch_size,
                     max_seqlen_q, max_seqlen_k,
                     seqlen_q_rounded, seqlen_k_rounded,
                     num_heads, num_heads_k,
                     head_size, head_size_rounded,
                     head_size_v, head_size_v_rounded,
                     q_padded, k_padded, v_padded, out,
                     cu_seqlens_q.data_ptr(),
                     cu_seqlens_k.data_ptr(),
                     return_softmax ? p.data_ptr() : nullptr,
                     seqused_k.has_value() ? seqused_k.value().data_ptr() : nullptr,
                     softmax_lse.data_ptr(),
                     p_dropout,
                     softmax_scale,
                     window_size_left,
                     window_size_right,
                     softcap,
                     false,
                     /*unpadded_lse*/false,
                     /*is_kvcache*/false,
                     /*is_seqlens_k_cumulative*/cu_seqlens_k.size(0) == (batch_size + 1),
                     /*layout*/0
                    );
    params.total_q = total_q;
    params.total_k = total_k;

    at::Tensor rng_state;
    if (p_dropout > 0) {
        auto options = at::TensorOptions().dtype(at::ScalarType::Float).device(at::DeviceType::CUDA);
        rng_state = at::empty({2}, options.dtype(at::ScalarType::Long));
        // Forward kernel will populate memory with the seed and offset.
        params.rng_state = reinterpret_cast<uint64_t*>(rng_state.data_ptr());
    } else {
        params.rng_state = nullptr;
    }
zhangshao's avatar
zhangshao committed
1636

hly's avatar
hly committed
1637
    set_params_alibi(params, alibi_slopes_, batch_size, num_heads);
zhangshao's avatar
zhangshao committed
1638

hly's avatar
hly committed
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
    const char* fa_debug = std::getenv("FA_DEBUG");
    if (fa_debug != nullptr) {
        if (std::strcmp(fa_debug, "1") == 0) { PRINT_PARAMS }
        else if (std::strcmp(fa_debug, "2") == 0) {
            PRINT_PARAMS_ONELINE
            auto temp_tensor = cu_seqlens_k.to(at::DeviceType::CPU).contiguous();
            std::vector<int32_t> temp_vector(temp_tensor.data_ptr<int32_t>(), temp_tensor.data_ptr<int32_t>() + temp_tensor.numel());
            printf("cu_seqlens_k: ["); for (const auto val: temp_vector) { printf("%d ", val); } printf("]\n");
        }
        PRINT_QKV_INFO(q, k, v)
zhangshao's avatar
zhangshao committed
1649
1650
    }

hly's avatar
hly committed
1651
1652
    const hipStream_t stream = at::hip::getCurrentHIPStreamMasqueradingAsCUDA();
    run_mha_fwd(params, stream);
zhangshao's avatar
zhangshao committed
1653

hly's avatar
hly committed
1654
1655
1656
1657
1658
    at::Tensor out_padded = out;
    if (head_size_value % 32 != 0) {
        out = out.index({"...", at::indexing::Slice(at::indexing::None, head_size_value)});
        if (out_.has_value()) { out_.value().copy_(out); }
    }
zhangshao's avatar
zhangshao committed
1659

hly's avatar
hly committed
1660
    return {out, q_padded, k_padded, v_padded, out_padded, softmax_lse, p, rng_state};
zhangshao's avatar
zhangshao committed
1661
#else
hly's avatar
hly committed
1662
    return {};
zhangshao's avatar
zhangshao committed
1663
1664
1665
#endif
}

hly's avatar
hly committed
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
int get_attention_sink_type(at::ScalarType dtype) {
  if (dtype == at::ScalarType::Float) {
    return 1;
  }
  if (dtype == at::ScalarType::Half) {
    return 2;
  }
  if (dtype == at::ScalarType::BFloat16) {
    return 3;
  }
  TORCH_CHECK(false, "Attention sink only supports fp32/fp16/bf16 dtype");
  return 0;
}

std::vector<at::Tensor> hg_prefix_prefill_varlen_fwd(
    const at::Tensor &q, const at::Tensor &k, const at::Tensor &v,
    c10::optional<at::Tensor> &out_, const at::Tensor &cu_seqlens_q,
    c10::optional<at::Tensor> &cu_seqlens_k, at::Tensor &seqused_k,
    c10::optional<at::Tensor> &alibi_slopes_, at::Tensor &block_table,
    const int max_seqlen_q, const int max_seqlen_k, const float p_dropout,
    const float softmax_scale, const bool zero_tensors, const bool is_causal,
    int window_size_left, int window_size_right, const float softcap,
    const bool return_softmax, const int layout,
    c10::optional<at::Tensor> scales_q_ = c10::nullopt,
    c10::optional<at::Tensor> scales_k_ = c10::nullopt,
    c10::optional<at::Tensor> scales_v_ = c10::nullopt,
    c10::optional<at::Tensor> s_aux_ = c10::nullopt,
    const bool is_bf16_output = false) {
zhangshao's avatar
zhangshao committed
1694
1695
#if defined(BUILD_FA_FWD)
  const at::cuda::HIPGuardMasqueradingAsCUDA device_guard(q.device().index());
hly's avatar
hly committed
1696
1697
1698
1699
1700
1701
  // TORCH_CHECK(is_causal == true, "for prefix prefill, only causal mask = True
  // is supported!");
  if (is_causal) {
    window_size_right = 0;
  }

zhangshao's avatar
zhangshao committed
1702
  auto q_dtype = q.dtype();
hly's avatar
hly committed
1703
1704
  const bool int8_used = q_dtype == at::ScalarType::Char;
  const bool fp8_used = q_dtype == at::ScalarType::Float8_e4m3fn;
zhangshao's avatar
zhangshao committed
1705
  TORCH_CHECK(q_dtype == at::ScalarType::Half ||
hly's avatar
hly committed
1706
1707
1708
1709
                  q_dtype == at::ScalarType::BFloat16 ||
                  q_dtype == at::ScalarType::Char ||
                  q_dtype == at::ScalarType::Float8_e4m3fn,
              "FlashAttention only support fp16 and bf16 and int8 and fp8 data type");
zhangshao's avatar
zhangshao committed
1710
1711
  TORCH_CHECK(k.dtype() == q_dtype, "query and key must have the same dtype");
  TORCH_CHECK(v.dtype() == q_dtype, "query and value must have the same dtype");
hly's avatar
hly committed
1712
1713
1714
1715
  TORCH_CHECK(cu_seqlens_q.dtype() == at::ScalarType::Int,
              "cu_seqlens_q must have dtype int32");
  TORCH_CHECK(seqused_k.dtype() == at::ScalarType::Int,
              "seqused_k must have dtype int32");
zhangshao's avatar
zhangshao committed
1716
1717
1718
1719

  CHECK_DEVICE(q);
  CHECK_DEVICE(k);
  CHECK_DEVICE(v);
hly's avatar
hly committed
1720
1721
  CHECK_DEVICE(cu_seqlens_q);
  CHECK_DEVICE(seqused_k);
zhangshao's avatar
zhangshao committed
1722
1723
1724
1725
1726
1727
1728

  TORCH_CHECK(q.stride(-1) == 1,
              "Input tensor must have contiguous last dimension");
  TORCH_CHECK(k.stride(-1) == 1,
              "Input tensor must have contiguous last dimension");
  TORCH_CHECK(v.stride(-1) == 1,
              "Input tensor must have contiguous last dimension");
hly's avatar
hly committed
1729
1730
  CHECK_CONTIGUOUS(cu_seqlens_q);
  CHECK_CONTIGUOUS(seqused_k);
zhangshao's avatar
zhangshao committed
1731

hly's avatar
hly committed
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
  const bool use_bshd_layout = layout == 1;
  const auto query_size = q.sizes();
  const auto k_size = k.sizes();
  const auto v_size = v.sizes();
  const int num_heads = query_size[1];
  const int num_heads_k = k_size[2];
  const int head_size_og = use_bshd_layout ? query_size[2] : query_size[1];
  const int head_size_value = use_bshd_layout ? v_size[3] : v_size[2];
  const int total_q =
      use_bshd_layout ? query_size[0] : query_size[0] / num_heads;
  const int batch_size = cu_seqlens_q.numel() - 1;
  const int page_block_size = use_bshd_layout ? k_size[1] : k_size[2];
  TORCH_CHECK(batch_size > 0, "batch size must be positive");
  TORCH_CHECK(page_block_size == 128 || (!int8_used && page_block_size == 64),
              "Prefix prefill only supports page block_size 128, plus b16/fp8 page block_size 64");
  TORCH_CHECK((head_size_og == 128 and head_size_value == 128) or
                  (head_size_og == 192 and head_size_value == 128) or
                  (head_size_og == 192 and head_size_value == 192) or
                  (head_size_og == 256 and head_size_value == 256),
              "Prefix prefill only supports head dimension "
              "128+128/192+128/192+192/256+256");
  if (fp8_used) {
    TORCH_CHECK((head_size_og == 128 and head_size_value == 128) or
                    (head_size_og == 192 and head_size_value == 128) or
                    (head_size_og == 256 and head_size_value == 256),
                "FP8 prefix prefill only supports head dimension 128+128/192+128/256+256 on gfx938");
    TORCH_CHECK(scales_q_.has_value() && scales_k_.has_value() &&
                    scales_v_.has_value(),
                "FP8 prefix prefill requires q/k/v descale tensors");
  }
zhangshao's avatar
zhangshao committed
1762
1763
1764
  TORCH_CHECK(
      num_heads % num_heads_k == 0,
      "Number of heads in key/value must divide number of heads in query");
hly's avatar
hly committed
1765
  TORCH_CHECK(int64_t(query_size[0] * head_size_og) <
zhangshao's avatar
zhangshao committed
1766
1767
1768
                  /*2^31*/ int64_t(2147483648),
              "The data amount of q must be smaller than the representation "
              "range of int");
hly's avatar
hly committed
1769
  TORCH_CHECK(int64_t(k_size[0] * head_size_value) <
zhangshao's avatar
zhangshao committed
1770
1771
1772
1773
                  /*2^31*/ int64_t(2147483648),
              "The data amount of k/v must be smaller than the representation "
              "range of int");
  CHECK_SHAPE(cu_seqlens_q, batch_size + 1);
hly's avatar
hly committed
1774
  CHECK_SHAPE(seqused_k, batch_size);
zhangshao's avatar
zhangshao committed
1775
1776
1777
1778
1779
1780
1781
1782

  if (softcap > 0.f) {
    TORCH_CHECK(p_dropout == 0.f,
                "Softcapping does not support dropout for now");
  }

  auto round_multiple = [](int x, int m) { return (x + m - 1) / m * m; };
  const int head_size = round_multiple(head_size_og, 8);
hly's avatar
hly committed
1783
  const int head_size_rounded = round_multiple(head_size, 32);
zhangshao's avatar
zhangshao committed
1784
  const int head_size_v = round_multiple(head_size_value, 8);
hly's avatar
hly committed
1785
1786
1787
  const int head_size_v_rounded = round_multiple(head_size_v, 32);
  const int seqlen_q_rounded = round_multiple(max_seqlen_q, 32);
  const int seqlen_k_rounded = round_multiple(max_seqlen_k, 32);
zhangshao's avatar
zhangshao committed
1788
1789

  at::Tensor q_padded, k_padded, v_padded;
hly's avatar
hly committed
1790
1791
1792
  if (head_size_og % 32 != 0) {
    q_padded = at::pad(q, {0, 32 - head_size_og % 32});
    k_padded = at::pad(k, {0, 32 - head_size_og % 32});
zhangshao's avatar
zhangshao committed
1793
1794
1795
1796
1797
  } else {
    q_padded = q;
    k_padded = k;
  }

hly's avatar
hly committed
1798
1799
  if (head_size_value % 32 != 0) {
    v_padded = at::pad(v, {0, 32 - head_size_value % 32});
zhangshao's avatar
zhangshao committed
1800
1801
1802
1803
1804
1805
1806
1807
  } else {
    v_padded = v;
  }

  auto opts = q.options();
  at::Tensor out;
  if (out_.has_value()) {
    out = out_.value();
hly's avatar
hly committed
1808
1809
1810
1811
1812
1813
1814
1815
    if (!int8_used && !fp8_used) {
      TORCH_CHECK(out.dtype() == q_dtype,
                  "Output must have the same dtype as inputs");
    } else if (fp8_used) {
      TORCH_CHECK(out.dtype() == at::ScalarType::Half ||
                      out.dtype() == at::ScalarType::BFloat16,
                  "FP8 prefix prefill output must be fp16 or bf16");
    }
zhangshao's avatar
zhangshao committed
1816
1817
1818
    CHECK_DEVICE(out);
    TORCH_CHECK(out.stride(-1) == 1,
                "Output tensor must have contiguous last dimension");
hly's avatar
hly committed
1819
1820
    if (head_size_value % 32 != 0) {
      out = at::pad(out, {0, 32 - head_size_value % 32});
zhangshao's avatar
zhangshao committed
1821
1822
    }
  } else {
hly's avatar
hly committed
1823
1824
1825
1826
1827
1828
1829
    // for (bs)hd layout
    if (int8_used || fp8_used) {
      auto int8_opts = is_bf16_output ? opts.dtype(at::ScalarType::BFloat16)
                                      : opts.dtype(at::ScalarType::Half);
      out = at::empty({query_size[0], query_size[1], head_size_v_rounded},
                      int8_opts);
    } else {
zhangshao's avatar
zhangshao committed
1830
1831
1832
1833
1834
1835
1836
1837
      out =
          at::empty({query_size[0], query_size[1], head_size_v_rounded}, opts);
    }
  }

  auto softmax_lse = at::empty({num_heads, total_q}, opts.dtype(at::kFloat));
  at::Tensor p;
  // Only return softmax if there's dropout to reduce compilation time
hly's avatar
hly committed
1838
  if (false /*return_softmax*/) {
zhangshao's avatar
zhangshao committed
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
    TORCH_CHECK(p_dropout > 0.0f,
                "return_softmax is only supported when p_dropout > 0.0");
    p = at::empty({batch_size, num_heads, seqlen_q_rounded, seqlen_k_rounded},
                  opts);
  }

  if (zero_tensors) {
    out.zero_();
    softmax_lse.fill_(-std::numeric_limits<float>::infinity());
    if (return_softmax) {
      p.zero_();
    }
  }
  Flash_fwd_params params;
  set_params_fprop(
      params, batch_size, max_seqlen_q, max_seqlen_k, seqlen_q_rounded,
      seqlen_k_rounded, num_heads, num_heads_k, head_size, head_size_rounded,
      head_size_v, head_size_v_rounded, q_padded, k_padded, v_padded, out,
hly's avatar
hly committed
1857
1858
      cu_seqlens_q.data_ptr(), seqused_k.data_ptr(),
      return_softmax ? nullptr /*p.data_ptr()*/ : nullptr, seqused_k.data_ptr(),
zhangshao's avatar
zhangshao committed
1859
1860
1861
1862
      softmax_lse.data_ptr(), p_dropout, softmax_scale, window_size_left,
      window_size_right, softcap, false,
      /*unpadded_lse*/ false,
      /*is_kvcache*/ false,
hly's avatar
hly committed
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
      /*is_seqlens_k_cumulative*/ seqused_k.size(0) == (batch_size + 1),
      layout /*layout*/, false /*is_flashmla*/, true /*is_prefix*/
  );
  params.s_aux_ptr = nullptr;
  params.s_aux_type = 0;
  if (s_aux_.has_value()) {
    auto s_aux = s_aux_.value();
    const auto expected_sink_dtype =
        fp8_used ? out.scalar_type() : at::ScalarType::Float;
    TORCH_CHECK(s_aux.scalar_type() == expected_sink_dtype,
                "Attention sink dtype must match prefix output dtype. Got ",
                s_aux.dtype(), ", expected ", expected_sink_dtype);
    CHECK_DEVICE(s_aux);
    CHECK_CONTIGUOUS(s_aux);
    CHECK_SHAPE(s_aux, num_heads);
    params.s_aux_ptr = s_aux.data_ptr();
    params.s_aux_type = get_attention_sink_type(s_aux.scalar_type());
  }
zhangshao's avatar
zhangshao committed
1881
  params.total_q = total_q;
hly's avatar
hly committed
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
  params.block_table = block_table.data_ptr<int>();
  params.block_table_batch_stride = block_table.stride(0);
  params.k_batch_stride = k_padded.stride(0);
  params.v_batch_stride = v_padded.stride(0);
  params.page_block_size = page_block_size;
  params.seqused_k = reinterpret_cast<int *>(seqused_k.data_ptr());
  params.layout = 1;

  params.is_int8 = int8_used;
  if (int8_used) {
    params.is_bf16 = is_bf16_output;
    at::Tensor scales_k;
    scales_k = scales_k_.value();
    params.scales_k_ptr = scales_k.data_ptr();
    at::Tensor scales_v;
    scales_v = scales_v_.value();
    params.scales_v_ptr = scales_v.data_ptr();
    at::Tensor scales_q;
    scales_q = scales_q_.value();
    params.scales_q_ptr = scales_q.data_ptr();
    params.total_scale_q = scales_q.numel();
  }
  if (fp8_used) {
    params.is_bf16 = out.dtype() == at::ScalarType::BFloat16;
    params.is_e4m3 = true;
    auto set_fp8_descale = [](const at::Tensor &descale, const char *name) {
      CHECK_DEVICE(descale);
      TORCH_CHECK(descale.dtype() == at::ScalarType::Float,
                  name, " must have dtype float32");
      TORCH_CHECK(descale.numel() >= 1,
                  name, " must contain at least one element");
      return reinterpret_cast<float*>(descale.data_ptr());
    };
    at::Tensor scales_q = scales_q_.value();
    params.q_descale_ptr = set_fp8_descale(scales_q, "q_descale");
    params.q_descale_batch_stride = 0;
    params.q_descale_head_stride = 0;
    at::Tensor scales_k = scales_k_.value();
    params.k_descale_ptr = set_fp8_descale(scales_k, "k_descale");
    params.k_descale_batch_stride = 0;
    params.k_descale_head_stride = 0;
    at::Tensor scales_v = scales_v_.value();
    params.v_descale_ptr = set_fp8_descale(scales_v, "v_descale");
    params.v_descale_batch_stride = 0;
    params.v_descale_head_stride = 0;
zhangshao's avatar
zhangshao committed
1927
1928
1929
  }

  at::Tensor rng_state;
hly's avatar
hly committed
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
  if (p_dropout > 0) {
    auto options = at::TensorOptions()
                       .dtype(at::ScalarType::Float)
                       .device(at::DeviceType::CUDA);
    rng_state = at::empty({2}, options.dtype(at::ScalarType::Long));
    // Forward kernel will populate memory with the seed and offset.
    params.rng_state = reinterpret_cast<uint64_t *>(rng_state.data_ptr());
  } else {
    params.rng_state = nullptr;
  }
zhangshao's avatar
zhangshao committed
1940
1941
1942
1943
1944
1945
1946
1947
1948

  set_params_alibi(params, alibi_slopes_, batch_size, num_heads);

  const char *fa_debug = std::getenv("FA_DEBUG");
  if (fa_debug != nullptr) {
    if (std::strcmp(fa_debug, "1") == 0) {
      PRINT_PARAMS
    } else if (std::strcmp(fa_debug, "2") == 0) {
      PRINT_PARAMS_ONELINE
hly's avatar
hly committed
1949
      auto temp_tensor = seqused_k.to(at::DeviceType::CPU).contiguous();
zhangshao's avatar
zhangshao committed
1950
1951
1952
      std::vector<int32_t> temp_vector(temp_tensor.data_ptr<int32_t>(),
                                       temp_tensor.data_ptr<int32_t>() +
                                           temp_tensor.numel());
hly's avatar
hly committed
1953
      printf("seqused_k: [");
zhangshao's avatar
zhangshao committed
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
      for (const auto val : temp_vector) {
        printf("%d ", val);
      }
      printf("]\n");
    }
    PRINT_QKV_INFO(q, k, v)
  }

  const hipStream_t stream = at::hip::getCurrentHIPStreamMasqueradingAsCUDA();
  run_mha_fwd(params, stream);

  at::Tensor out_padded = out;
hly's avatar
hly committed
1966
  if (head_size_value % 32 != 0) {
zhangshao's avatar
zhangshao committed
1967
1968
1969
1970
1971
1972
1973
    out = out.index(
        {"...", at::indexing::Slice(at::indexing::None, head_size_value)});
    if (out_.has_value()) {
      out_.value().copy_(out);
    }
  }

hly's avatar
hly committed
1974
1975
1976
  // return {out, q_padded, k_padded, v_padded, out_padded, softmax_lse, p, rng_state};
  if (return_softmax) return {out, softmax_lse};
  else return {out};
zhangshao's avatar
zhangshao committed
1977
1978
1979
1980
1981
1982
#else
  return {};
#endif
}


hly's avatar
hly committed
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
std::vector<at::Tensor> prefix_prefill_varlen_fwd_mla(
    at::Tensor &q,
    at::Tensor &kcache,
    at::Tensor &vcache,
    at::Tensor &qv,
    at::Tensor &page_table,
    at::Tensor &cache_seqlens,
    at::Tensor &cu_seqlens_q,
    at::Tensor &cu_seqlens_k_new,
    const int max_seqlen_q,
    const float softmax_scale,
    const bool causal,
    const float softcap,
    c10::optional<const at::Tensor> &k_descale,
    c10::optional<const at::Tensor> &v_descale,
    const bool return_softmax_lse,
    const bool is_mtp
) {
zhangshao's avatar
zhangshao committed
2001
#if defined(BUILD_FA_FWD)
hly's avatar
hly committed
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
    const at::cuda::HIPGuardMasqueradingAsCUDA device_guard(q.device().index());
    // 类型检查
    TORCH_CHECK(q.dtype() == at::ScalarType::Half || q.dtype() == at::ScalarType::BFloat16, "Prefix prefill forward mla only support fp16 and bf16 data type for q");
    TORCH_CHECK(kcache.dtype() == at::ScalarType::Half || kcache.dtype() == at::ScalarType::BFloat16, "Prefix prefill forward mla only support fp16 and bf16 data type for kcache");
    TORCH_CHECK(vcache.dtype() == at::ScalarType::Half || vcache.dtype() == at::ScalarType::BFloat16, "Prefix prefill forward mla only support fp16 and bf16 data type for vcache");
    TORCH_CHECK(qv.dtype() == at::ScalarType::Half || qv.dtype() == at::ScalarType::BFloat16, "Prefix prefill forward mla only support fp16 and bf16 data type for qv");
    TORCH_CHECK(page_table.dtype() == at::ScalarType::Int, "Prefix prefill forward mla only support int32_t data type for page_table");
    TORCH_CHECK(cache_seqlens.dtype() == at::ScalarType::Int, "Prefix prefill forward mla only support int32_t data type for cache_seqlens");
    TORCH_CHECK(cu_seqlens_q.dtype() == at::ScalarType::Int, "Prefix prefill forward mla only support int32_t data type for cu_seqlens_q");
    TORCH_CHECK(cu_seqlens_k_new.dtype() == at::ScalarType::Int, "Prefix prefill forward mla only support int32_t data type for cu_seqlens_k_new");
    // device 检查
    CHECK_DEVICE(q); CHECK_DEVICE(kcache); CHECK_DEVICE(vcache); CHECK_DEVICE(qv); CHECK_DEVICE(page_table); CHECK_DEVICE(cache_seqlens); CHECK_DEVICE(cu_seqlens_q); CHECK_DEVICE(cu_seqlens_k_new);
    // 连续性检查
    CHECK_CONTIGUOUS(page_table); CHECK_CONTIGUOUS(cache_seqlens); CHECK_CONTIGUOUS(cu_seqlens_q); CHECK_CONTIGUOUS(cu_seqlens_k_new);
    // 张量 shape 检查, 是否是 3/4 维这种
    TORCH_CHECK(q.dim() == 3, "In prefix prefill forward mla, q must be 3-dimension tensor");
    TORCH_CHECK(kcache.dim() == 4, "In prefix prefill forward mla, kcache must be 4-dimension tensor");
    TORCH_CHECK(vcache.dim() == 4, "In prefix prefill forward mla, vcache must be 4-dimension tensor");
    TORCH_CHECK(qv.dim() == 3, "In prefix prefill forward mla, qv must be 3-dimension tensor");
    TORCH_CHECK(page_table.dim() == 2, "In prefix prefill forward mla, page_table must be 2-dimension tensor");
    // 获取基本信息
    const auto q_size = q.sizes();
    const auto qv_size = qv.sizes();
    const auto kcache_size = kcache.sizes();
    const auto vcache_size = vcache.sizes();
    const int batch_size = page_table.size(0);
    const int qheads = q_size[1];
    const int kvheads = kcache_size[2];
    const int headdim_v = vcache_size[3];
    const int headdim_rope = q_size[2];
    const int headdim_qk = headdim_v + headdim_rope;
    const int page_block_size = kcache_size[1];
    // 检查 size 是否符合要求
    TORCH_CHECK(qheads % kvheads == 0, "In prefix prefill forward mla, qheads must be multiple of kvheads");
    TORCH_CHECK(headdim_v == 512, "In prefix prefill forward mla, headdim_v must be 512");
    TORCH_CHECK(headdim_rope == 64, "In prefix prefill forward mla, headdim_rope must be 64");
    TORCH_CHECK(headdim_qk == 576, "In prefix prefill forward mla, headdim_qk must be 576");
    TORCH_CHECK(page_block_size == 128, "In prefix prefill forward mla, page_block_size must be 128")
    // 检查 size 是否匹配
    TORCH_CHECK(q_size[2] == kcache_size[3], "In prefix prefill forward mla, headdim must match between q and kcache");
    TORCH_CHECK(qv_size[2] == vcache_size[3], "In prefix prefill forward mla, headdim must match between qv and vcache");
    // 检查平台
    hipDeviceProp_t props;
    auto hipResult = hipGetDeviceProperties(&props, 0);
    std::string gcn_arch_name(props.gcnArchName);
    const int gcn_arch = runtime_gfx_arch_id(gcn_arch_name);
    TORCH_CHECK(is_supported_hg_mla_arch(gcn_arch_name, gcn_arch), "In prefix prefill forward mla, only gfx92a or arch id >= gfx936 is supported!");
    // 准备输出变量
    auto opts = q.options();
    at::Tensor out, softmax_lse, scores_max, scores_sum;
    out = at::empty({q_size[0], q_size[1], headdim_v}, opts);
    if (true/*return_softmax_lse*/) {
        auto scores_memory = at::empty({3, qheads, q_size[0]}, opts.dtype(at::kFloat));
        scores_max = scores_memory.index({0});
        scores_sum = scores_memory.index({1});
        softmax_lse = scores_memory.index({2});
    }
    // 准备 kernel 需要的参数列表
    Flash_fwd_mla_params params;
    memset(&params, 0, sizeof(params));
    params.layout           = 1;
    params.b                = batch_size;
    params.h                = qheads;
    params.h_k              = kvheads;
    params.h_h_k_ratio      = int(qheads / kvheads);
    params.total_q          = q_size[0];
    params.scale_softmax    = softmax_scale;
    params.scale_softmax_log2 = softmax_scale * M_LOG2E;
    params.cu_seqlens_q     = reinterpret_cast<int32_t*>(cu_seqlens_q.data_ptr());
    params.cu_seqlens_k_new = reinterpret_cast<int32_t*>(cu_seqlens_k_new.data_ptr());
    params.q_ptr            = q.data_ptr();
    params.qv_ptr           = qv.data_ptr();
    params.k_ptr            = kcache.data_ptr();
    params.v_ptr            = vcache.data_ptr();
    params.o_ptr            = out.data_ptr();
    params.softmax_lse_ptr  = softmax_lse.data_ptr<float>();
    params.scores_max_ptr   = scores_max.data_ptr<float>();
    params.scores_sum_ptr   = scores_sum.data_ptr<float>();
    params.block_table      = reinterpret_cast<int32_t*>(page_table.data_ptr());
    params.block_table_batch_stride = page_table.stride(0);
    params.page_block_size  = page_block_size;
    params.is_causal        = causal;
    params.q_row_stride     = q.stride(0);
    params.q_head_stride    = q.stride(1);
    params.qv_row_stride    = qv.stride(0);
    params.qv_head_stride   = qv.stride(1);
    params.k_batch_stride   = kcache.stride(0);
    params.k_row_stride     = kcache.stride(1);
    params.k_head_stride    = kcache.stride(2);
    params.v_batch_stride   = vcache.stride(0);
    params.v_row_stride     = vcache.stride(1);
    params.v_head_stride    = vcache.stride(2);
    params.o_row_stride     = out.stride(0);
    params.o_head_stride    = out.stride(1);
    params.seqlen_q         = max_seqlen_q;
    params.is_bf16          = q.dtype() == at::ScalarType::BFloat16;
    params.cu_count         = props.multiProcessorCount;
    params.mtp              = is_mtp;                   // A flag to ensure whether prefill or decode

    // 准备启动 kernel
    const hipStream_t stream = at::hip::getCurrentHIPStreamMasqueradingAsCUDA();
    const char* fa_debug = std::getenv("FA_DEBUG");
    if (fa_debug != nullptr) {
        PRINT_MLA_PARAMS
        if (strcmp(fa_debug, "2") == 0) { // print operations listed below may interrupt cudagraph, and thus only print tensors util FA_DEBUG=2
            PRINT_TENSOR(cache_seqlens, "cache_seqlens")
            PRINT_TENSOR(cu_seqlens_q, "cu_seqlens_q")
            PRINT_TENSOR(cu_seqlens_k_new, "cu_seqlens_k_new")
        }
        PRINT_TENSOR_INFO(q, "q")
        PRINT_TENSOR_INFO(kcache, "kcache")
        PRINT_TENSOR_INFO(vcache, "vcache")
        PRINT_TENSOR_INFO(qv, "qv")
    }
zhangshao's avatar
zhangshao committed
2116

hly's avatar
hly committed
2117
2118
2119
2120
2121
    if (max_seqlen_q > 0 and std::getenv("MLA_PREFILL_EMPTY") == nullptr) {
        run_fwd_prefix_prefill_mla(params, stream);
    } else {
        out.zero_();
    }
zhangshao's avatar
zhangshao committed
2122

hly's avatar
hly committed
2123
2124
2125
2126
2127
    return {out, softmax_lse, scores_max, scores_sum};
#else
    return {};
#endif
}
zhangshao's avatar
zhangshao committed
2128

hly's avatar
hly committed
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
#if defined(BUILD_FA_BWD)
#include "flash_sumout_api.h"
namespace inner {
    void sum_out(at::Tensor &output, at::Tensor input, int dim) {
     auto dtype = input.dtype();
     const int stride0       = input.stride(dim);
     const int stride1       = input.stride(dim-1);
     const int num_elem      = output.numel();
     const int num_thread    = 256;
     const int num_grid      = num_elem / num_thread;
     if(dtype == at::ScalarType::Half)
         flash_sum_out<Float16><<<num_grid, num_thread>>>(reinterpret_cast<Float16 *>(output.data_ptr()), reinterpret_cast<Float16 *>(input.data_ptr()), stride0, stride1);
     else if (dtype == at::ScalarType::BFloat16)
         flash_sum_out<BFloat16><<<num_grid, num_thread>>>(reinterpret_cast<BFloat16 *>(output.data_ptr()), reinterpret_cast<BFloat16 *>(input.data_ptr()), stride0, stride1);
 }
 }
#endif
zhangshao's avatar
zhangshao committed
2146

hly's avatar
hly committed
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
std::vector<at::Tensor>
bwd_base(const at::Tensor &dout,  // batch_size x num_heads x seqlen_q x head_size_og
        const at::Tensor &q,   // batch_size x num_heads x seqlen_q x head_size
        const at::Tensor &k,   // batch_size x num_heads x seqlen_q x head_size
        const at::Tensor &v,   // batch_size x num_heads x seqlen_q x head_size
        const at::Tensor &out,   // batch_size x num_heads x seqlen_q x head_size
        const at::Tensor &softmax_lse,     // b x h x seqlen_q
        c10::optional<at::Tensor> &dq_,   // batch_size x num_heads x seqlen_q x head_size
        c10::optional<at::Tensor> &dk_,   // batch_size x num_heads x seqlen_q x head_size
        c10::optional<at::Tensor> &dv_,   // batch_size x num_heads x seqlen_q x head_size
        c10::optional<at::Tensor> &alibi_slopes_, // num_heads or batch_size x num_heads
        const float p_dropout,         // probability to drop
        const float softmax_scale,
        const bool is_causal,
        int window_size_left,
        int window_size_right,
        const float softcap,
        const bool deterministic,
        c10::optional<at::Generator> gen_,
        c10::optional<at::Tensor> &rng_state,
        const int layout
    ) {
zhangshao's avatar
zhangshao committed
2169
#if defined(BUILD_FA_BWD)
hly's avatar
hly committed
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
    const at::cuda::HIPGuardMasqueradingAsCUDA device_guard(q.device().index());
    if (is_causal) { window_size_right = 0; }

    bool is_dropout = p_dropout > 0.0;
    auto q_dtype = q.dtype();
    TORCH_CHECK(q_dtype == at::ScalarType::Half || q_dtype == at::ScalarType::BFloat16 || q_dtype == at::ScalarType::Float8_e4m3fn,
            "FlashAttention only support fp16,bf16,e4m3 data type");
    TORCH_CHECK(k.dtype() == q_dtype, "query and key must have the same dtype");
    TORCH_CHECK(v.dtype() == q_dtype, "query and value must have the same dtype");
    TORCH_CHECK(out.dtype() == q_dtype, "query and out must have the same dtype");
    TORCH_CHECK(dout.dtype() == q_dtype, "query and dout must have the same dtype");

    CHECK_DEVICE(q); CHECK_DEVICE(k); CHECK_DEVICE(v);
    CHECK_DEVICE(out); CHECK_DEVICE(dout); CHECK_DEVICE(softmax_lse);

    TORCH_CHECK(q.stride(-1) == 1, "Input tensor must have contiguous last dimension");
    TORCH_CHECK(k.stride(-1) == 1, "Input tensor must have contiguous last dimension");
    TORCH_CHECK(v.stride(-1) == 1, "Input tensor must have contiguous last dimension");
    TORCH_CHECK(out.stride(-1) == 1, "out tensor must have contiguous last dimension");
    TORCH_CHECK(dout.stride(-1) == 1, "dout tensor must have contiguous last dimension");
    TORCH_CHECK(layout == 0 || layout == 1, "layout only supports 0 or 1");
    const bool use_bshd_layout = bool(layout == 1);
    const auto sizes = q.sizes();

    const int batch_size = sizes[0];
    const int num_heads = use_bshd_layout ? sizes[2]: sizes[1];
    const int seqlen_q = use_bshd_layout ? sizes[1]: sizes[2];
    const int head_size_value = v.size(3);
    const int head_size = sizes[3];
    const int num_heads_k = use_bshd_layout ? k.size(2): k.size(1);
    const int seqlen_k = use_bshd_layout ? k.size(1): k.size(2);
    TORCH_CHECK(batch_size > 0, "batch size must be positive");
    TORCH_CHECK(head_size <= 256, "FlashAttention backward only supports head dimension at most 256");
    TORCH_CHECK(head_size_value <= 256, "FlashAttention backward only supports head dimension at most 256");


    TORCH_CHECK(num_heads % num_heads_k == 0, "Number of heads in key/value must divide number of heads in query");
    TORCH_CHECK(int64_t(batch_size * num_heads * seqlen_q * head_size) < /*2^31*/int64_t(2147483648), "The data amount of q must be smaller than the representation range of int");
    TORCH_CHECK(int64_t(batch_size * num_heads_k * seqlen_k * head_size) < /*2^31*/int64_t(2147483648), "The data amount of k/v must be smaller than the representation range of int");
    auto round_multiple = [](int x, int m) { return (x + m - 1) / m * m; };
    const int head_size_rounded = round_multiple(head_size, 32);
    const int head_size_value_rounded = round_multiple(head_size_value, 32);
    const int seqlen_q_rounded = round_multiple(seqlen_q, 128);
    const int seqlen_k_rounded = round_multiple(seqlen_k, 128);
    if (softcap > 0.f) { TORCH_CHECK(p_dropout == 0.f, "Softcapping does not support dropout for now"); }

    if (window_size_left >= seqlen_k) { window_size_left = -1; }
    if (window_size_right >= seqlen_k) { window_size_right = -1; }
zhangshao's avatar
zhangshao committed
2218
2219

    if (layout == 0) {
hly's avatar
hly committed
2220
2221
2222
2223
2224
        CHECK_SHAPE(q, batch_size, num_heads, seqlen_q, head_size);
        CHECK_SHAPE(k, batch_size, num_heads_k, seqlen_k, head_size);
        CHECK_SHAPE(v, batch_size, num_heads_k, seqlen_k, head_size_value);
        CHECK_SHAPE(out, batch_size, num_heads, seqlen_q, head_size_value);
        CHECK_SHAPE(dout, batch_size, num_heads, seqlen_q, dout.size(-1));
zhangshao's avatar
zhangshao committed
2225
    } else {
hly's avatar
hly committed
2226
2227
2228
2229
2230
        CHECK_SHAPE(q, batch_size, seqlen_q, num_heads, head_size);
        CHECK_SHAPE(k, batch_size, seqlen_k, num_heads_k, head_size);
        CHECK_SHAPE(v, batch_size, seqlen_k, num_heads_k, head_size_value);
        CHECK_SHAPE(out, batch_size, seqlen_q, num_heads, head_size_value);
        CHECK_SHAPE(dout, batch_size, seqlen_q, num_heads, dout.size(-1));
zhangshao's avatar
zhangshao committed
2231
2232
    }

hly's avatar
hly committed
2233
2234
    auto opts = q.options();
    at::Tensor q_padded, k_padded, v_padded, out_padded, dq_padded, dk_padded, dv_padded, dout_padded;
zhangshao's avatar
zhangshao committed
2235
    if (head_size % 32 != 0) {
hly's avatar
hly committed
2236
2237
        q_padded = at::pad(q, {0, 32 - head_size % 32});
        k_padded = at::pad(k, {0, 32 - head_size % 32});
zhangshao's avatar
zhangshao committed
2238
    } else {
hly's avatar
hly committed
2239
2240
        q_padded = q;
        k_padded = k;
zhangshao's avatar
zhangshao committed
2241
2242
2243
    }

    if (head_size_value % 32 != 0) {
hly's avatar
hly committed
2244
2245
        v_padded = at::pad(v, {0, 32 - head_size_value % 32});
        out_padded = at::pad(out, {0, 32 - head_size_value % 32});
zhangshao's avatar
zhangshao committed
2246
    } else {
hly's avatar
hly committed
2247
2248
        v_padded = v;
        out_padded = out;
zhangshao's avatar
zhangshao committed
2249
2250
    }

hly's avatar
hly committed
2251
2252
    if (dout.size(-1) % 32 != 0) {
        dout_padded = at::pad(dout, {0, 32 - dout.size(-1) % 32});
zhangshao's avatar
zhangshao committed
2253
    } else {
hly's avatar
hly committed
2254
        dout_padded = dout;
zhangshao's avatar
zhangshao committed
2255
2256
    }

hly's avatar
hly committed
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
    if(dq_.has_value()){
        if(layout == 0) {
            CHECK_SHAPE(dq_.value(), batch_size, num_heads, seqlen_q, head_size);
        } else {
            CHECK_SHAPE(dq_.value(), batch_size, seqlen_q, num_heads, head_size);
        }
        if (head_size % 32 != 0) {
            dq_padded = at::pad(dq_.value(), {0, 32 - head_size % 32});
        } else {
            dq_padded = dq_.value();
        }
zhangshao's avatar
zhangshao committed
2268
    } else {
hly's avatar
hly committed
2269
2270
2271
2272
2273
        if (layout == 0) {
            dq_padded = at::empty({batch_size, num_heads, seqlen_q, head_size_rounded}, opts);
        } else {
            dq_padded = at::empty({batch_size, seqlen_q, num_heads, head_size_rounded}, opts);
        }
zhangshao's avatar
zhangshao committed
2274
2275
    }

hly's avatar
hly committed
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
    if(dk_.has_value()){
        if(layout == 0) {
            CHECK_SHAPE(dk_.value(), batch_size, num_heads_k, seqlen_k, head_size);
        } else {
            CHECK_SHAPE(dk_.value(), batch_size, seqlen_k, num_heads_k, head_size);
        }
        if (head_size % 32 != 0) {
            dk_padded = at::pad(dk_.value(), {0, 32 - head_size % 32});
        } else {
            dk_padded = dk_.value();
        }
zhangshao's avatar
zhangshao committed
2287
    } else {
hly's avatar
hly committed
2288
2289
2290
2291
2292
        if (layout == 0) {
            dk_padded = at::empty({batch_size, num_heads_k, seqlen_k, head_size_rounded}, opts);
        } else {
            dk_padded = at::empty({batch_size, seqlen_k, num_heads_k, head_size_rounded}, opts);
        }
zhangshao's avatar
zhangshao committed
2293
2294
    }

hly's avatar
hly committed
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
    if(dv_.has_value()){
        if(layout == 0) {
            CHECK_SHAPE(dv_.value(), batch_size, num_heads_k, seqlen_k, head_size_value);
        } else {
            CHECK_SHAPE(dv_.value(), batch_size, seqlen_k, num_heads_k, head_size_value);
        }
        if (head_size_value % 32 != 0) {
            dv_padded = at::pad(dv_.value(), {0, 32 - head_size_value % 32});
        } else {
            dv_padded = dv_.value();
        }
zhangshao's avatar
zhangshao committed
2306
    } else {
hly's avatar
hly committed
2307
2308
2309
2310
2311
        if (layout == 0) {
            dv_padded = at::empty({batch_size, num_heads_k, seqlen_k, head_size_value_rounded}, opts);
        } else {
            dv_padded = at::empty({batch_size, seqlen_k, num_heads_k, head_size_value_rounded}, opts);
        }
zhangshao's avatar
zhangshao committed
2312
2313
    }

hly's avatar
hly committed
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
    // // Otherwise the kernel will be launched from cuda:0 device
    // // Cast to char to avoid compiler warning about narrowing
    // at::cuda::CUDAGuard device_guard{(char)q.get_device()};

    auto softmax_d = at::empty({batch_size, num_heads, seqlen_q_rounded}, opts.dtype(at::kFloat));
    at::Tensor dk_accum, dv_accum;
    at::Tensor dk_expanded, dv_expanded;
    if (num_heads_k != num_heads) {  // MQA / GQA
        if(layout == 0){
            dk_expanded = at::empty({batch_size, num_heads, seqlen_k, head_size_rounded}, opts);
            dv_expanded = at::empty({batch_size, num_heads, seqlen_k, head_size_value_rounded}, opts);
        } else{
            dk_expanded = at::empty({batch_size, seqlen_k, num_heads, head_size_rounded}, opts);
            dv_expanded = at::empty({batch_size, seqlen_k, num_heads, head_size_value_rounded}, opts);
        }

zhangshao's avatar
zhangshao committed
2330
    } else {
hly's avatar
hly committed
2331
2332
        dk_expanded = dk_padded;
        dv_expanded = dv_padded;
zhangshao's avatar
zhangshao committed
2333
2334
    }

hly's avatar
hly committed
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
#ifdef DEBUGING
        at::Tensor dev_kq, dev_s, dev_dp, dev_ds;
        if(layout == 0){
            dev_kq = at::empty({batch_size, num_heads, seqlen_q, seqlen_k}, opts.dtype(at::kFloat));
            dev_kq.fill_(float('-inf'));
            dev_s  = at::zeros({batch_size, num_heads, seqlen_q, seqlen_k}, opts.dtype(at::kFloat));
            dev_dp = at::zeros({batch_size, num_heads, seqlen_q, seqlen_k}, opts.dtype(at::kFloat));
            dev_ds = at::zeros({batch_size, num_heads, seqlen_q, seqlen_k}, opts.dtype(at::kFloat));
        } else {
            dev_kq = at::zeros({batch_size, seqlen_q, num_heads, seqlen_k}, opts.dtype(at::kFloat));
            dev_kq.fill_(float('-inf'));
            dev_s  = at::zeros({batch_size, seqlen_q, num_heads, seqlen_k}, opts.dtype(at::kFloat));
            dev_dp = at::zeros({batch_size, seqlen_q, num_heads, seqlen_k}, opts.dtype(at::kFloat));
            dev_ds = at::zeros({batch_size, seqlen_q, num_heads, seqlen_k}, opts.dtype(at::kFloat));
        }
#endif
zhangshao's avatar
zhangshao committed
2351

hly's avatar
hly committed
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
    // std::cout << "q_padded:\n" << q_padded << std::endl;
    // std::cout << "k_padded:\n" << k_padded << std::endl;
    // std::cout << "v_padded:\n" << v_padded << std::endl;
    // std::cout << "out_padded:\n" << out_padded << std::endl;
    // std::cout << "dout_padded:\n" << dout_padded << std::endl;

    Flash_bwd_params params;
    set_params_dgrad(params,
                     batch_size,
                     seqlen_q, seqlen_k,
                     seqlen_q_rounded, seqlen_k_rounded,
                     num_heads, num_heads_k,
                     head_size, head_size_rounded,
                     head_size_value, head_size_value_rounded,
                     q_padded, k_padded, v_padded, out_padded,
                     dout_padded, dq_padded, dk_expanded, dv_expanded,
                     nullptr,
                     nullptr,
                     nullptr/*p_d.data_ptr()*/,
zhangshao's avatar
zhangshao committed
2371
#ifdef DEBUGING
hly's avatar
hly committed
2372
2373
2374
2375
                     dev_kq.data_ptr(),
                     dev_s.data_ptr(),
                     dev_dp.data_ptr(),
                     dev_ds.data_ptr(),
zhangshao's avatar
zhangshao committed
2376
#endif
hly's avatar
hly committed
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
                     nullptr,
                     nullptr,
                     nullptr,
                     softmax_lse.data_ptr(),
                     softmax_d.data_ptr(),
                     p_dropout,
                     softmax_scale,
                     window_size_left,
                     window_size_right,
                     softcap,
                     deterministic,
                     /*unpadded_lse*/false,
                     layout
                    );
    // std::cout<<"params.q_row_stride = "<< params.q_row_stride<<std::endl;
    // std::cout<<"params.k_row_stride = "<<params.k_row_stride<<std::endl;
    // std::cout<<"params.v_row_stride = "<<params.v_row_stride<<std::endl;
    // std::cout<<"params.o_row_stride = "<<params.o_row_stride<<std::endl;
    // std::cout<<"params.q_head_stride = "<<params.q_head_stride<<std::endl;
    // std::cout<<"params.k_head_stride = "<<params.k_head_stride<<std::endl;
    // std::cout<<"params.v_head_stride = "<<params.v_head_stride<<std::endl;
    // std::cout<<"params.o_head_stride = "<<params.o_head_stride<<std::endl;
    // std::cout<<"params.dq_row_stride = "<< params.dq_row_stride<<std::endl;
    // std::cout<<"params.dk_row_stride = "<<params.dk_row_stride<<std::endl;
    // std::cout<<"params.dv_row_stride = "<<params.dv_row_stride<<std::endl;
    // std::cout<<"params.do_row_stride = "<<params.do_row_stride<<std::endl;
    // std::cout<<"params.dq_head_stride = "<<params.dq_head_stride<<std::endl;
    // std::cout<<"params.dk_head_stride = "<<params.dk_head_stride<<std::endl;
    // std::cout<<\"params.dv_head_stride = \"<<params.dv_head_stride<<std::endl;
    // std::cout<<\"params.do_head_stride = \"<<params.do_head_stride<<std::endl;

    auto launch = &run_mha_bwd;
    // launch(params, stream, /*configure=*/true);

    // auto gen = at::get_generator_or_default<at::CUDAGeneratorImpl>(
    //     gen_, at::cuda::detail::getDefaultCUDAGenerator());

    // We use a custom RNG that increases the offset by batch_size * nheads * 32.
    int64_t counter_offset = params.b * params.h * 32;
    at::Tensor rng_state_tensor;
    if ( rng_state.has_value() ) {
        params.rng_state = reinterpret_cast<uint64_t*>(rng_state.value().data_ptr());
        std::cout<<"params.rng_state[0] = "<<params.rng_state[0]<<std::endl;
        std::cout<<"params.rng_state[1] = "<<params.rng_state[1]<<std::endl;
    }
    else if( is_dropout ) {
        // See Note [Acquire lock when using random generators]
        rng_state_tensor = at::empty({2}, opts.dtype(at::ScalarType::Long));
        params.rng_state = reinterpret_cast<uint64_t*>(rng_state_tensor.data_ptr());
        auto gen = at::get_generator_or_default<at::CUDAGeneratorImpl>(
            gen_, at::cuda::detail::getDefaultCUDAGenerator());
        std::lock_guard<std::mutex> lock(gen->mutex_);
        at::PhiloxCudaState philox_args = gen->philox_cuda_state(counter_offset);
        // at::cuda::philox::unpack(philox_args) not supported on ROCm
        params.rng_state[0] = philox_args.seed_.val;
        params.rng_state[1] = philox_args.offset_.val;
    }
    if (is_dropout) {
        params.rand_seed = params.rng_state[0];
        params.rand_offset = params.rng_state[1];
    }
zhangshao's avatar
zhangshao committed
2438

hly's avatar
hly committed
2439
    set_params_alibi(params, alibi_slopes_, batch_size, num_heads);
zhangshao's avatar
zhangshao committed
2440

hly's avatar
hly committed
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
    const hipStream_t stream = nullptr;//at::hip::getCurrentHIPStreamMasqueradingAsCUDA();
    launch(params, stream, /*configure=*/false);
    // For MQA/GQA we need to sum dK and dV across the groups
    if (num_heads_k != num_heads) {
        if(layout == 0){
            sum_out(dk_padded, at::reshape(dk_expanded, {batch_size, num_heads_k, num_heads / num_heads_k, seqlen_k, head_size_rounded}), 2);
            sum_out(dv_padded, at::reshape(dv_expanded, {batch_size, num_heads_k, num_heads / num_heads_k, seqlen_k, head_size_value_rounded}), 2);
        } else {
            sum_out(dk_padded, at::reshape(dk_expanded, {batch_size, seqlen_k, num_heads_k, num_heads / num_heads_k, head_size_rounded}), 3);
            sum_out(dv_padded, at::reshape(dv_expanded, {batch_size, seqlen_k, num_heads_k, num_heads / num_heads_k, head_size_value_rounded}), 3);
        }
zhangshao's avatar
zhangshao committed
2452

hly's avatar
hly committed
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
    }
    at::Tensor dq, dk, dv;
    if (head_size % 32 != 0) {
        dq = dq_padded.index({"...", at::indexing::Slice(at::indexing::None, head_size)});
        dk = dk_padded.index({"...", at::indexing::Slice(at::indexing::None, head_size)});
    } else {
        dq = dq_padded;
        dk = dk_padded;
    }
    if (head_size_value % 32 != 0) {
        dv = dv_padded.index({"...", at::indexing::Slice(at::indexing::None, head_size_value)});
    } else {
        dv = dv_padded;
    }
zhangshao's avatar
zhangshao committed
2467

hly's avatar
hly committed
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
    // std::cout<<"q.sizes() = "<<q.sizes()<<std::endl;
    // std::cout<<"k.sizes() = "<<k.sizes()<<std::endl;
    // std::cout<<"out.sizes() = "<<out.sizes()<<std::endl;
    // std::cout<<"num_heads = "<<num_heads<<std::endl;
    // std::cout<<"dk.sizes() = "<<dk.sizes()<<std::endl;
    // std::cout<<"layout="<<layout<<std::endl;
    // std::cout<<"dq.sizes() = "<<dq.sizes()<<std::endl;
    // std::cout<<"dq.stride() = "<<dq.stride(0)<<" "<<dq.stride(1)<<" "<<dq.stride(2)<<" "<<dq.stride(3)<<std::endl;
    // std::cout<<"q.stride() = "<<q.stride(0)<<" "<<q.stride(1)<<" "<<q.stride(2)<<" "<<q.stride(3)<<std::endl;
    // std::cout<<"dk.sizes() = "<<dk.sizes()<<std::endl;
    // std::cout<<"dv.sizes() = "<<dv.sizes()<<std::endl;
    // std::cout<<"num_heads_k = "<<num_heads_k<<std::endl;
    // std::cout<<"num_heads = "<<num_heads<<std::endl;
    // std::cout<<"dq.sizes() = "<<dq.sizes()<<std::endl;
    // std::cout<<"dk.sizes() = "<<dk.sizes()<<std::endl;
    // std::cout<<"dv.sizes() = "<<dv.sizes()<<std::endl;

    #ifdef DEBUGING
        return { dq, dk, dv, softmax_d, dev_kq.clone(), dev_s.clone(), dev_dp.clone(), dev_ds.clone()};
    #else
        return { dq, dk, dv, softmax_d };
    #endif
zhangshao's avatar
zhangshao committed
2490
#else
hly's avatar
hly committed
2491
    return {};
zhangshao's avatar
zhangshao committed
2492
2493
2494
#endif
}

hly's avatar
hly committed
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
std::vector<at::Tensor>
hg_bwd_bhsd(const at::Tensor &dout,  // batch_size x num_heads x seqlen_q x head_size_og
    const at::Tensor &q,   // batch_size x num_heads x seqlen_q x head_size
    const at::Tensor &k,   // batch_size x num_heads x seqlen_q x head_size
    const at::Tensor &v,   // batch_size x num_heads x seqlen_q x head_size
    const at::Tensor &out,   // batch_size x num_heads x seqlen_q x head_size
    const at::Tensor &softmax_lse,     // b x h x seqlen_q
    c10::optional<at::Tensor> &dq_,   // batch_size x num_heads x seqlen_q x head_size
    c10::optional<at::Tensor> &dk_,   // batch_size x num_heads x seqlen_q x head_size
    c10::optional<at::Tensor> &dv_,   // batch_size x num_heads x seqlen_q x head_size
    c10::optional<at::Tensor> &alibi_slopes_, // num_heads or batch_size x num_heads
    const float p_dropout,         // probability to drop
    const float softmax_scale,
    const bool is_causal,
    int window_size_left,
    int window_size_right,
    const float softcap,
    const bool deterministic,
    c10::optional<at::Generator> gen_,
zhangshao's avatar
zhangshao committed
2514
2515
    c10::optional<at::Tensor> &rng_state
) {
hly's avatar
hly committed
2516
2517
    return bwd_base(dout, q, k, v, out, softmax_lse, dq_, dk_, dv_, alibi_slopes_, p_dropout, softmax_scale, is_causal, window_size_left, window_size_right, softcap, deterministic, gen_, rng_state, 0);
}
zhangshao's avatar
zhangshao committed
2518

hly's avatar
hly committed
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
std::vector<at::Tensor>
hg_bwd_bshd(const at::Tensor &dout,  // batch_size x num_heads x seqlen_q x head_size_og
    const at::Tensor &q,   // batch_size x num_heads x seqlen_q x head_size
    const at::Tensor &k,   // batch_size x num_heads x seqlen_q x head_size
    const at::Tensor &v,   // batch_size x num_heads x seqlen_q x head_size
    const at::Tensor &out,   // batch_size x num_heads x seqlen_q x head_size
    const at::Tensor &softmax_lse,     // b x h x seqlen_q
    c10::optional<at::Tensor> &dq_,   // batch_size x num_heads x seqlen_q x head_size
    c10::optional<at::Tensor> &dk_,   // batch_size x num_heads x seqlen_q x head_size
    c10::optional<at::Tensor> &dv_,   // batch_size x num_heads x seqlen_q x head_size
    c10::optional<at::Tensor> &alibi_slopes_, // num_heads or batch_size x num_heads
    const float p_dropout,         // probability to drop
    const float softmax_scale,
    const bool is_causal,
    int window_size_left,
    int window_size_right,
    const float softcap,
    const bool deterministic,
    c10::optional<at::Generator> gen_,
    c10::optional<at::Tensor> &rng_state
) {
    return bwd_base(dout, q, k, v, out, softmax_lse, dq_, dk_, dv_, alibi_slopes_, p_dropout, softmax_scale, is_causal, window_size_left, window_size_right, softcap, deterministic, gen_, rng_state, 1);
}
zhangshao's avatar
zhangshao committed
2542

hly's avatar
hly committed
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
std::vector<at::Tensor>
hg_varlen_bwd_bshd(const at::Tensor &dout,  // total_q_heads x head_size, total_q_heads := \sum_{i=0}^{b} s_i x num_heads
                    const at::Tensor &q,  // total_q_heads x head_size, total_q_heads := \sum_{i=0}^{b} s_i x num_heads
                    const at::Tensor &k,  // total_k_heads x head_size, total_k_heads := \sum_{i=0}^{b} s_i x num_heads_k
                    const at::Tensor &v,  // total_k_heads x head_size, total_k_heads := \sum_{i=0}^{b} s_i x num_heads_k
                    const at::Tensor &out, // total_q_heads x head_size, total_q_heads := \sum_{i=0}^{b} s_i x num_heads
                    const at::Tensor &softmax_lse,     // b x h x s   softmax logsumexp
                    c10::optional<at::Tensor> &dq_,   // total_q x num_heads x head_size, total_q := \sum_{i=0}^{b} s_i
                    c10::optional<at::Tensor> &dk_,   // total_k x num_heads_k x head_size, total_k := \sum_{i=0}^{b} s_i
                    c10::optional<at::Tensor> &dv_,   // total_k x num_heads_k x head_size, total_k := \sum_{i=0}^{b} s_i
                    const at::Tensor &cu_seqlens_q,  // b+1
                    const at::Tensor &cu_seqlens_k,  // b+1
                    c10::optional<at::Tensor> &alibi_slopes_, // num_heads or b x num_heads
                    const int max_seqlen_q,
                    const int max_seqlen_k,          // max sequence length to choose the kernel
                    const float p_dropout,         // probability to drop
                    const float softmax_scale,
                    const bool zero_tensors,
                    const bool is_causal,
                    int window_size_left,
                    int window_size_right,
                    const float softcap,
                    const bool deterministic,
                    c10::optional<at::Generator> gen_,
                    c10::optional<at::Tensor> &rng_state
        #ifdef DEBUGING
                        ,
                        const at::Tensor &dev_kq,
                        const at::Tensor &dev_s,
                        const at::Tensor &dev_dp,
                        const at::Tensor &dev_ds
        #endif
                    ) {
#if defined(BUILD_FA_BWD)
    const at::cuda::HIPGuardMasqueradingAsCUDA device_guard(q.device().index());
    const int layout = 1;
    if (is_causal) { window_size_right = 0; }

    bool is_dropout = p_dropout > 0.0;
    auto q_dtype = q.dtype();
    TORCH_CHECK(q_dtype == at::ScalarType::Half || q_dtype == at::ScalarType::BFloat16 || q_dtype == at::ScalarType::Float8_e4m3fn,
            "FlashAttention only support fp16,bf16,e4m3 data type");
    TORCH_CHECK(k.dtype() == q_dtype, "query and key must have the same dtype");
    TORCH_CHECK(v.dtype() == q_dtype, "query and value must have the same dtype");
    TORCH_CHECK(out.dtype() == q_dtype, "query and out must have the same dtype");
    TORCH_CHECK(dout.dtype() == q_dtype, "query and dout must have the same dtype");
    TORCH_CHECK(cu_seqlens_q.dtype() == torch::kInt32, "cu_seqlens_q must have dtype int32");
    TORCH_CHECK(cu_seqlens_k.dtype() == torch::kInt32, "cu_seqlens_k must have dtype int32");

    CHECK_DEVICE(q); CHECK_DEVICE(k); CHECK_DEVICE(v);
    CHECK_DEVICE(out); CHECK_DEVICE(dout); CHECK_DEVICE(softmax_lse);
    CHECK_DEVICE(cu_seqlens_q); CHECK_DEVICE(cu_seqlens_k);

    TORCH_CHECK(q.stride(-1) == 1, "Input tensor must have contiguous last dimension");
    TORCH_CHECK(k.stride(-1) == 1, "Input tensor must have contiguous last dimension");
    TORCH_CHECK(v.stride(-1) == 1, "Input tensor must have contiguous last dimension");
    TORCH_CHECK(out.stride(-1) == 1, "out tensor must have contiguous last dimension");
    TORCH_CHECK(dout.stride(-1) == 1, "dout tensor must have contiguous last dimension");
    CHECK_CONTIGUOUS(cu_seqlens_q);
    CHECK_CONTIGUOUS(cu_seqlens_k);

    const auto sizes = q.sizes();

    //support MLA
    const int total_q = sizes[0];
    const int batch_size = cu_seqlens_q.numel() - 1;
    const int num_heads = sizes[1];
    const int head_size_value = v.size(2);
    const int head_size = sizes[2];
    const int total_k = k.size(0);
    const int num_heads_k = k.size(1);

    TORCH_CHECK(batch_size > 0, "batch size must be positive");
    TORCH_CHECK(head_size <= 256, "FlashAttention backward only supports head dimension at most 256");
    TORCH_CHECK(head_size_value <= 256, "FlashAttention backward only supports head dimension at most 256");


    TORCH_CHECK(num_heads % num_heads_k == 0, "Number of heads in key/value must divide number of heads in query");
    TORCH_CHECK(int64_t(total_q * num_heads * head_size) < /*2^31*/int64_t(2147483648), "The data amount of q must be smaller than the representation range of int");
    TORCH_CHECK(int64_t(total_k * num_heads_k * head_size) < /*2^31*/int64_t(2147483648), "The data amount of k/v must be smaller than the representation range of int");
    auto round_multiple = [](int x, int m) { return (x + m - 1) / m * m; };
    const int head_size_rounded = round_multiple(head_size, 32);
    const int head_size_value_rounded = round_multiple(head_size_value, 32);
    const int seqlen_q_rounded = round_multiple(max_seqlen_q, 128);
    const int seqlen_k_rounded = round_multiple(max_seqlen_k, 128);
    if (softcap > 0.f) { TORCH_CHECK(p_dropout == 0.f, "Softcapping does not support dropout for now"); }

    if (window_size_left >= max_seqlen_k) { window_size_left = -1; }
    if (window_size_right >= max_seqlen_k) { window_size_right = -1; }

    CHECK_SHAPE(dout, total_q, num_heads, dout.size(-1));
    CHECK_SHAPE(cu_seqlens_q, batch_size + 1);
    CHECK_SHAPE(cu_seqlens_k, batch_size + 1);

    auto opts = q.options();
    at::Tensor q_padded, k_padded, v_padded, out_padded, dq_padded, dk_padded, dv_padded, dout_padded;
zhangshao's avatar
zhangshao committed
2639
    if (head_size % 32 != 0) {
hly's avatar
hly committed
2640
2641
        q_padded = at::pad(q, {0, 32 - head_size % 32});
        k_padded = at::pad(k, {0, 32 - head_size % 32});
zhangshao's avatar
zhangshao committed
2642
    } else {
hly's avatar
hly committed
2643
2644
        q_padded = q;
        k_padded = k;
zhangshao's avatar
zhangshao committed
2645
2646
    }

hly's avatar
hly committed
2647
2648
2649
    if (head_size_value % 32 != 0) {
        v_padded = at::pad(v, {0, 32 - head_size_value % 32});
        out_padded = at::pad(out, {0, 32 - head_size_value % 32});
zhangshao's avatar
zhangshao committed
2650
    } else {
hly's avatar
hly committed
2651
2652
        v_padded = v;
        out_padded = out;
zhangshao's avatar
zhangshao committed
2653
2654
    }

hly's avatar
hly committed
2655
2656
    if (dout.size(-1) % 32 != 0) {
        dout_padded = at::pad(dout, {0, 32 - dout.size(-1) % 32});
zhangshao's avatar
zhangshao committed
2657
    } else {
hly's avatar
hly committed
2658
        dout_padded = dout;
zhangshao's avatar
zhangshao committed
2659
2660
    }

hly's avatar
hly committed
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
    if(dq_.has_value()){
        CHECK_SHAPE(dq_.value(), total_q, num_heads, head_size);
        if (head_size % 32 != 0) {
            dq_padded = at::pad(dq_.value(), {0, 32 - head_size % 32});
        } else {
            dq_padded = dq_.value();
        }
    } else {
        dq_padded = at::empty({total_q, num_heads, head_size_rounded}, opts);
    }
zhangshao's avatar
zhangshao committed
2671

hly's avatar
hly committed
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
    if(dk_.has_value()){
        CHECK_SHAPE(dk_.value(), total_k, num_heads_k, head_size);
        if (head_size % 32 != 0) {
            dk_padded = at::pad(dk_.value(), {0, 32 - head_size % 32});
        } else {
            dk_padded = dk_.value();
        }
    } else {
        dk_padded = at::empty({total_k, num_heads_k, head_size_rounded}, opts);
    }
zhangshao's avatar
zhangshao committed
2682

hly's avatar
hly committed
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
    if(dv_.has_value()){
        CHECK_SHAPE(dv_.value(), total_k, num_heads_k, head_size_value);
        if (head_size_value % 32 != 0) {
            dv_padded = at::pad(dv_.value(), {0, 32 - head_size_value % 32});
        } else {
            dv_padded = dv_.value();
        }
    } else {
        dv_padded = at::empty({total_k, num_heads_k, head_size_value_rounded}, opts);
    }
zhangshao's avatar
zhangshao committed
2693

hly's avatar
hly committed
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
    auto softmax_d = at::empty({batch_size, num_heads, seqlen_q_rounded}, opts.dtype(at::kFloat));
    at::Tensor dk_accum, dv_accum;
    at::Tensor dk_expanded, dv_expanded;
    if (num_heads_k != num_heads) {  // MQA / GQA
        dk_expanded = at::empty({total_k, num_heads, head_size_rounded}, opts);
        dv_expanded = at::empty({total_k, num_heads, head_size_value_rounded}, opts);
    } else {
        dk_expanded = dk_padded;
        dv_expanded = dv_padded;
    }
zhangshao's avatar
zhangshao committed
2704

hly's avatar
hly committed
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
    #ifdef DEBUGING
        at::Tensor dev_kq, dev_s, dev_dp, dev_ds;
        if(layout == 0){
            dev_kq = at::empty({batch_size, num_heads, seqlen_q, seqlen_k}, opts.dtype(at::kFloat));
            dev_kq.fill_(float('-inf'));
            dev_s  = at::zeros({batch_size, num_heads, seqlen_q, seqlen_k}, opts.dtype(at::kFloat));
            dev_dp = at::zeros({batch_size, num_heads, seqlen_q, seqlen_k}, opts.dtype(at::kFloat));
            dev_ds = at::zeros({batch_size, num_heads, seqlen_q, seqlen_k}, opts.dtype(at::kFloat));
        } else {
            dev_kq = at::zeros({batch_size, seqlen_q, num_heads, seqlen_k}, opts.dtype(at::kFloat));
            dev_kq.fill_(float('-inf'));
            dev_s  = at::zeros({batch_size, seqlen_q, num_heads, seqlen_k}, opts.dtype(at::kFloat));
            dev_dp = at::zeros({batch_size, seqlen_q, num_heads, seqlen_k}, opts.dtype(at::kFloat));
            dev_ds = at::zeros({batch_size, seqlen_q, num_heads, seqlen_k}, opts.dtype(at::kFloat));
        }
    #endif

    // std::cout << "q_padded:\n" << q_padded << std::endl;
    // std::cout << "k_padded:\n" << k_padded << std::endl;
    // std::cout << "v_padded:\n" << v_padded << std::endl;
    // std::cout << "out_padded:\n" << out_padded << std::endl;
    // std::cout << "dout_padded:\n" << dout_padded << std::endl;

    Flash_bwd_params params;
    set_params_dgrad(params,
                    batch_size,
                    max_seqlen_q, max_seqlen_k,
                    seqlen_q_rounded, seqlen_k_rounded,
                    num_heads, num_heads_k,
                    head_size, head_size_rounded,
                    head_size_value, head_size_value_rounded,
                    q_padded, k_padded, v_padded, out_padded,
                    dout_padded, dq_padded, dk_expanded, dv_expanded,
                    cu_seqlens_q.data_ptr(),
                    cu_seqlens_k.data_ptr(),
                    nullptr/*p_d.data_ptr()*/,
    #ifdef DEBUGING
                    dev_kq.data_ptr(),
                    dev_s.data_ptr(),
                    dev_dp.data_ptr(),
                    dev_ds.data_ptr(),
    #endif
                    nullptr,
                    nullptr,
                    nullptr,
                    softmax_lse.data_ptr(),
                    softmax_d.data_ptr(),
                    p_dropout,
                    softmax_scale,
                    window_size_left,
                    window_size_right,
                    softcap,
                    deterministic,
                    /*unpadded_lse*/false,
                    layout
                    );
    params.total_q = total_q;
    params.total_k = total_k;
    auto launch = &run_mha_bwd;
    // launch(params, stream, /*configure=*/true);

    // auto gen = at::get_generator_or_default<at::CUDAGeneratorImpl>(
    //     gen_, at::cuda::detail::getDefaultCUDAGenerator());

    // We use a custom RNG that increases the offset by batch_size * nheads * 32.
    int64_t counter_offset = params.b * params.h * 32;

    at::Tensor rng_state_tensor;
    if ( rng_state.has_value() ) {
        params.rng_state = reinterpret_cast<uint64_t*>(rng_state.value().data_ptr());
    }
    else if( is_dropout ) {
        // See Note [Acquire lock when using random generators]
        rng_state_tensor = at::empty({2}, opts.dtype(at::ScalarType::Long));
        params.rng_state = reinterpret_cast<uint64_t*>(rng_state_tensor.data_ptr());
        auto gen = at::get_generator_or_default<at::CUDAGeneratorImpl>(
            gen_, at::cuda::detail::getDefaultCUDAGenerator());
        std::lock_guard<std::mutex> lock(gen->mutex_);
        at::PhiloxCudaState philox_args = gen->philox_cuda_state(counter_offset);
        // at::cuda::philox::unpack(philox_args) not supported on ROCm
        params.rng_state[0] = philox_args.seed_.val;
        params.rng_state[1] = philox_args.offset_.val;
    }
    if (is_dropout) {
        params.rand_seed = params.rng_state[0];
        params.rand_offset = params.rng_state[1];
zhangshao's avatar
zhangshao committed
2791
2792
    }

hly's avatar
hly committed
2793
    set_params_alibi(params, alibi_slopes_, batch_size, num_heads);
zhangshao's avatar
zhangshao committed
2794

hly's avatar
hly committed
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
    const hipStream_t stream = nullptr;//at::hip::getCurrentHIPStreamMasqueradingAsCUDA();
    launch(params, stream, /*configure=*/false);
    // For MQA/GQA we need to sum dK and dV across the groups
    if (num_heads_k != num_heads) {
        // inner::sum_out(dk_padded, at::reshape(dk_expanded, {total_k, num_heads_k, num_heads / num_heads_k, head_size_rounded}), 2);
        // inner::sum_out(dv_padded, at::reshape(dv_expanded, {total_k, num_heads_k, num_heads / num_heads_k, head_size_value_rounded}), 2);
        at::sum_out(dk_padded, at::reshape(dk_expanded, {total_k, num_heads_k, num_heads / num_heads_k, head_size_rounded}), {2});
        at::sum_out(dv_padded, at::reshape(dv_expanded, {total_k, num_heads_k, num_heads / num_heads_k, head_size_value_rounded}), {2});
    }
    at::Tensor dq, dk, dv;
    if (head_size % 32 != 0) {
        dq = dq_padded.index({"...", at::indexing::Slice(at::indexing::None, head_size)});
        dk = dk_padded.index({"...", at::indexing::Slice(at::indexing::None, head_size)});
    } else {
        dq = dq_padded;
        dk = dk_padded;
    }
    if (head_size_value % 32 != 0) {
        dv = dv_padded.index({"...", at::indexing::Slice(at::indexing::None, head_size_value)});
    } else {
        dv = dv_padded;
    }

    // std::cout<<"q.sizes() = "<<q.sizes()<<std::endl;
    // std::cout<<"k.sizes() = "<<k.sizes()<<std::endl;
    // std::cout<<"out.sizes() = "<<out.sizes()<<std::endl;
    // std::cout<<"num_heads = "<<num_heads<<std::endl;
    // std::cout<<"dk.sizes() = "<<dk.sizes()<<std::endl;
    // std::cout<<"layout="<<layout<<std::endl;
    // std::cout<<"dq.sizes() = "<<dq.sizes()<<std::endl;
    // std::cout<<"dq.stride() = "<<dq.stride(0)<<" "<<dq.stride(1)<<" "<<dq.stride(2)<<" "<<dq.stride(3)<<std::endl;
    // std::cout<<"q.stride() = "<<q.stride(0)<<" "<<q.stride(1)<<" "<<q.stride(2)<<" "<<q.stride(3)<<std::endl;
    // std::cout<<"dk.sizes() = "<<dk.sizes()<<std::endl;
    // std::cout<<"dv.sizes() = "<<dv.sizes()<<std::endl;
    // std::cout<<"num_heads_k = "<<num_heads_k<<std::endl;
    // std::cout<<"num_heads = "<<num_heads<<std::endl;
    // std::cout<<"dq.sizes() = "<<dq.sizes()<<std::endl;
    // std::cout<<"dk.sizes() = "<<dk.sizes()<<std::endl;
    // std::cout<<"dv.sizes() = "<<dv.sizes()<<std::endl;

    #ifdef DEBUGING
        return { dq, dk, dv, softmax_d, dev_kq.clone(), dev_s.clone(), dev_dp.clone(), dev_ds.clone()};
    #else
        return { dq, dk, dv, softmax_d };
    #endif
zhangshao's avatar
zhangshao committed
2840
#else
hly's avatar
hly committed
2841
    return {};
zhangshao's avatar
zhangshao committed
2842
2843
2844
#endif
}

hly's avatar
hly committed
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
std::vector<at::Tensor>
mha_varlen_bwd_bhsd(const at::Tensor &dout,  // total_q_heads x head_size, total_q_heads := \sum_{i=0}^{b} s_i x num_heads
                    const at::Tensor &q,  // total_q_heads x head_size, total_q_heads := \sum_{i=0}^{b} s_i x num_heads
                    const at::Tensor &k,  // total_k_heads x head_size, total_k_heads := \sum_{i=0}^{b} s_i x num_heads_k
                    const at::Tensor &v,  // total_k_heads x head_size, total_k_heads := \sum_{i=0}^{b} s_i x num_heads_k
                    const at::Tensor &out, // total_q_heads x head_size, total_q_heads := \sum_{i=0}^{b} s_i x num_heads
                    const at::Tensor &softmax_lse,     // b x h x s   softmax logsumexp
                    c10::optional<at::Tensor> &dq_,   // total_q x num_heads x head_size, total_q := \sum_{i=0}^{b} s_i
                    c10::optional<at::Tensor> &dk_,   // total_k x num_heads_k x head_size, total_k := \sum_{i=0}^{b} s_i
                    c10::optional<at::Tensor> &dv_,   // total_k x num_heads_k x head_size, total_k := \sum_{i=0}^{b} s_i
                    const at::Tensor &cu_seqlens_q,  // b+1
                    const at::Tensor &cu_seqlens_k,  // b+1
                    c10::optional<at::Tensor> &alibi_slopes_, // num_heads or b x num_heads
                    const int max_seqlen_q,
                    const int max_seqlen_k,          // max sequence length to choose the kernel
                    const float p_dropout,         // probability to drop
                    const float softmax_scale,
                    const bool zero_tensors,
                    const bool is_causal,
                    int window_size_left,
                    int window_size_right,
                    const float softcap,
                    const bool deterministic,
                    c10::optional<at::Generator> gen_,
                    c10::optional<at::Tensor> &rng_state
        #ifdef DEBUGING
                        ,
                        const at::Tensor &dev_kq,
                        const at::Tensor &dev_s,
                        const at::Tensor &dev_dp,
                        const at::Tensor &dev_ds
        #endif
                    ) {
#if defined(BUILD_FA_BWD)
    const at::cuda::HIPGuardMasqueradingAsCUDA device_guard(q.device().index());
    const int layout = 0;
    if (is_causal) { window_size_right = 0; }

    bool is_dropout = p_dropout > 0.0;
    auto q_dtype = q.dtype();
    TORCH_CHECK(q_dtype == at::ScalarType::Half || q_dtype == at::ScalarType::BFloat16 || q_dtype == at::ScalarType::Float8_e4m3fn,
            "FlashAttention only support fp16,bf16,e4m3 data type");
    TORCH_CHECK(k.dtype() == q_dtype, "query and key must have the same dtype");
    TORCH_CHECK(v.dtype() == q_dtype, "query and value must have the same dtype");
    TORCH_CHECK(out.dtype() == q_dtype, "query and out must have the same dtype");
    TORCH_CHECK(dout.dtype() == q_dtype, "query and dout must have the same dtype");
    TORCH_CHECK(cu_seqlens_q.dtype() == torch::kInt32, "cu_seqlens_q must have dtype int32");
    TORCH_CHECK(cu_seqlens_k.dtype() == torch::kInt32, "cu_seqlens_k must have dtype int32");

    CHECK_DEVICE(q); CHECK_DEVICE(k); CHECK_DEVICE(v);
    CHECK_DEVICE(out); CHECK_DEVICE(dout); CHECK_DEVICE(softmax_lse);
    CHECK_DEVICE(cu_seqlens_q); CHECK_DEVICE(cu_seqlens_k);

    TORCH_CHECK(q.stride(-1) == 1, "Input tensor must have contiguous last dimension");
    TORCH_CHECK(k.stride(-1) == 1, "Input tensor must have contiguous last dimension");
    TORCH_CHECK(v.stride(-1) == 1, "Input tensor must have contiguous last dimension");
    TORCH_CHECK(out.stride(-1) == 1, "out tensor must have contiguous last dimension");
    TORCH_CHECK(dout.stride(-1) == 1, "dout tensor must have contiguous last dimension");
    CHECK_CONTIGUOUS(cu_seqlens_q);
    CHECK_CONTIGUOUS(cu_seqlens_k);

    const auto sizes = q.sizes();

    const int total_q_heads = sizes[0];
    const int total_q = cu_seqlens_q[-1].item<int>();
    const int batch_size = cu_seqlens_q.numel() - 1;
    const int num_heads = total_q_heads / total_q;
    const int head_size_value = v.size(-1);
    const int head_size = sizes[1];
    const int total_k_heads = k.size(0);
    const int total_k = cu_seqlens_k[-1].item<int>();
    const int num_heads_k = total_k_heads / total_k;

    TORCH_CHECK(batch_size > 0, "batch size must be positive");
    TORCH_CHECK(head_size <= 256, "FlashAttention backward only supports head dimension at most 256");
    TORCH_CHECK(head_size_value <= 256, "FlashAttention backward only supports head dimension at most 256");


    TORCH_CHECK(num_heads % num_heads_k == 0, "Number of heads in key/value must divide number of heads in query");
    TORCH_CHECK(int64_t(total_q_heads * head_size) < /*2^31*/int64_t(2147483648), "The data amount of q must be smaller than the representation range of int");
    TORCH_CHECK(int64_t(total_k_heads * head_size) < /*2^31*/int64_t(2147483648), "The data amount of k/v must be smaller than the representation range of int");
    auto round_multiple = [](int x, int m) { return (x + m - 1) / m * m; };
    const int head_size_rounded = round_multiple(head_size, 32);
    const int head_size_value_rounded = round_multiple(head_size_value, 32);
    const int seqlen_q_rounded = round_multiple(max_seqlen_q, 128);
    const int seqlen_k_rounded = round_multiple(max_seqlen_k, 128);
    if (softcap > 0.f) { TORCH_CHECK(p_dropout == 0.f, "Softcapping does not support dropout for now"); }

    if (window_size_left >= max_seqlen_k) { window_size_left = -1; }
    if (window_size_right >= max_seqlen_k) { window_size_right = -1; }

    CHECK_SHAPE(dout, total_q_heads, dout.size(-1));
    CHECK_SHAPE(cu_seqlens_q, batch_size + 1);
    CHECK_SHAPE(cu_seqlens_k, batch_size + 1);

    auto opts = q.options();
    at::Tensor q_padded, k_padded, v_padded, out_padded, dq_padded, dk_padded, dv_padded, dout_padded;
    if (head_size % 32 != 0) {
        q_padded = at::pad(q, {0, 32 - head_size % 32});
        k_padded = at::pad(k, {0, 32 - head_size % 32});
    } else {
        q_padded = q;
        k_padded = k;
    }
zhangshao's avatar
zhangshao committed
2949

hly's avatar
hly committed
2950
2951
2952
2953
2954
2955
2956
    if (head_size_value % 32 != 0) {
        v_padded = at::pad(v, {0, 32 - head_size_value % 32});
        out_padded = at::pad(out, {0, 32 - head_size_value % 32});
    } else {
        v_padded = v;
        out_padded = out;
    }
zhangshao's avatar
zhangshao committed
2957

hly's avatar
hly committed
2958
2959
2960
2961
2962
    if (dout.size(-1) % 32 != 0) {
        dout_padded = at::pad(dout, {0, 32 - dout.size(-1) % 32});
    } else {
        dout_padded = dout;
    }
zhangshao's avatar
zhangshao committed
2963

hly's avatar
hly committed
2964
2965
2966
2967
    if(dq_.has_value()){
        CHECK_SHAPE(dq_.value(), total_q_heads, head_size);
        if (head_size % 32 != 0) {
            dq_padded = at::pad(dq_.value(), {0, 32 - head_size % 32});
zhangshao's avatar
zhangshao committed
2968
        } else {
hly's avatar
hly committed
2969
            dq_padded = dq_.value();
zhangshao's avatar
zhangshao committed
2970
2971
        }
    } else {
hly's avatar
hly committed
2972
        dq_padded = at::empty({total_q_heads, head_size_rounded}, opts);
zhangshao's avatar
zhangshao committed
2973
2974
    }

hly's avatar
hly committed
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
    if(dk_.has_value()){
        CHECK_SHAPE(dk_.value(), total_k_heads, head_size);
        if (head_size % 32 != 0) {
            dk_padded = at::pad(dk_.value(), {0, 32 - head_size % 32});
        } else {
            dk_padded = dk_.value();
        }
    } else {
        dk_padded = at::empty({total_k_heads, head_size_rounded}, opts);
    }
zhangshao's avatar
zhangshao committed
2985

hly's avatar
hly committed
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
    if(dv_.has_value()){
        CHECK_SHAPE(dv_.value(), total_k_heads, head_size_value);
        if (head_size_value % 32 != 0) {
            dv_padded = at::pad(dv_.value(), {0, 32 - head_size_value % 32});
        } else {
            dv_padded = dv_.value();
        }
    } else {
        dv_padded = at::empty({total_k_heads, head_size_value_rounded}, opts);
    }
zhangshao's avatar
zhangshao committed
2996

hly's avatar
hly committed
2997
    auto softmax_d = at::empty({batch_size, num_heads, seqlen_q_rounded}, opts.dtype(at::kFloat));
zhangshao's avatar
zhangshao committed
2998

hly's avatar
hly committed
2999
3000
3001
3002
3003
3004
3005
3006
3007
    at::Tensor dk_accum, dv_accum;
    at::Tensor dk_expanded, dv_expanded;
    if (num_heads_k != num_heads) {  // MQA / GQA
        dk_expanded = at::empty({total_k_heads * (num_heads / num_heads_k), head_size_rounded}, opts);
        dv_expanded = at::empty({total_k_heads * (num_heads / num_heads_k), head_size_value_rounded}, opts);
    } else {
        dk_expanded = dk_padded;
        dv_expanded = dv_padded;
    }
zhangshao's avatar
zhangshao committed
3008

hly's avatar
hly committed
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
    #ifdef DEBUGING
        at::Tensor dev_kq, dev_s, dev_dp, dev_ds;
        if(layout == 0){
            dev_kq = at::empty({batch_size, num_heads, seqlen_q, seqlen_k}, opts.dtype(at::kFloat));
            dev_kq.fill_(float('-inf'));
            dev_s  = at::zeros({batch_size, num_heads, seqlen_q, seqlen_k}, opts.dtype(at::kFloat));
            dev_dp = at::zeros({batch_size, num_heads, seqlen_q, seqlen_k}, opts.dtype(at::kFloat));
            dev_ds = at::zeros({batch_size, num_heads, seqlen_q, seqlen_k}, opts.dtype(at::kFloat));
        } else {
            dev_kq = at::zeros({batch_size, seqlen_q, num_heads, seqlen_k}, opts.dtype(at::kFloat));
            dev_kq.fill_(float('-inf'));
            dev_s  = at::zeros({batch_size, seqlen_q, num_heads, seqlen_k}, opts.dtype(at::kFloat));
            dev_dp = at::zeros({batch_size, seqlen_q, num_heads, seqlen_k}, opts.dtype(at::kFloat));
            dev_ds = at::zeros({batch_size, seqlen_q, num_heads, seqlen_k}, opts.dtype(at::kFloat));
        }
    #endif

    // std::cout << "q_padded:\n" << q_padded << std::endl;
    // std::cout << "k_padded:\n" << k_padded << std::endl;
    // std::cout << "v_padded:\n" << v_padded << std::endl;
    // std::cout << "out_padded:\n" << out_padded << std::endl;
    // std::cout << "dout_padded:\n" << dout_padded << std::endl;

    Flash_bwd_params params;
    set_params_dgrad(params,
                    batch_size,
                    max_seqlen_q, max_seqlen_k,
                    seqlen_q_rounded, seqlen_k_rounded,
                    num_heads, num_heads_k,
                    head_size, head_size_rounded,
                    head_size_value, head_size_value_rounded,
                    q_padded, k_padded, v_padded, out_padded,
                    dout_padded, dq_padded, dk_expanded, dv_expanded,
                    cu_seqlens_q.data_ptr(),
                    cu_seqlens_k.data_ptr(),
                    nullptr/*p_d.data_ptr()*/,
    #ifdef DEBUGING
                    dev_kq.data_ptr(),
                    dev_s.data_ptr(),
                    dev_dp.data_ptr(),
                    dev_ds.data_ptr(),
    #endif
                    nullptr,
                    nullptr,
                    nullptr,
                    softmax_lse.data_ptr(),
                    softmax_d.data_ptr(),
                    p_dropout,
                    softmax_scale,
                    window_size_left,
                    window_size_right,
                    softcap,
                    deterministic,
                    /*unpadded_lse*/false,
                    layout
                    );
    params.total_q = total_q;
    params.total_k = total_k;
    auto launch = &run_mha_bwd;
    // launch(params, stream, /*configure=*/true);

    // auto gen = at::get_generator_or_default<at::CUDAGeneratorImpl>(
    //     gen_, at::cuda::detail::getDefaultCUDAGenerator());

    // We use a custom RNG that increases the offset by batch_size * nheads * 32.
    int64_t counter_offset = params.b * params.h * 32;

    at::Tensor rng_state_tensor;
    if ( rng_state.has_value() ) {
        params.rng_state = reinterpret_cast<uint64_t*>(rng_state.value().data_ptr());
    }
    else if( is_dropout ) {
        // See Note [Acquire lock when using random generators]
        rng_state_tensor = at::empty({2}, opts.dtype(at::ScalarType::Long));
        params.rng_state = reinterpret_cast<uint64_t*>(rng_state_tensor.data_ptr());
        auto gen = at::get_generator_or_default<at::CUDAGeneratorImpl>(
            gen_, at::cuda::detail::getDefaultCUDAGenerator());
        std::lock_guard<std::mutex> lock(gen->mutex_);
        at::PhiloxCudaState philox_args = gen->philox_cuda_state(counter_offset);
        // at::cuda::philox::unpack(philox_args) not supported on ROCm
        params.rng_state[0] = philox_args.seed_.val;
        params.rng_state[1] = philox_args.offset_.val;
    }
    if (is_dropout) {
        params.rand_seed = params.rng_state[0];
        params.rand_offset = params.rng_state[1];
    }
zhangshao's avatar
zhangshao committed
3096

hly's avatar
hly committed
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
    set_params_alibi(params, alibi_slopes_, batch_size, num_heads);

    const hipStream_t stream = nullptr;//at::hip::getCurrentHIPStreamMasqueradingAsCUDA();
    launch(params, stream, /*configure=*/false);
    // For MQA/GQA we need to sum dK and dV across the groups
    // b * h * s, d
    if (num_heads_k != num_heads) {
        for(int i = 0; i< batch_size; ++i) {
            at::Tensor tmp_dk = at::reshape(at::reshape(dk_expanded.index({at::indexing::Slice(cu_seqlens_k[i].item<int>() * num_heads, cu_seqlens_k[i+1].item<int>() * num_heads)}), {num_heads_k, num_heads / num_heads_k, -1, head_size_rounded}).sum(1), {-1, head_size_rounded});
            dk_padded.index({at::indexing::Slice(cu_seqlens_k[i].item<int>() * num_heads_k, cu_seqlens_k[i+1].item<int>() * num_heads_k)}) = tmp_dk;
            at::Tensor tmp_dv = at::reshape(at::reshape(dv_expanded.index({at::indexing::Slice(cu_seqlens_k[i].item<int>() * num_heads, cu_seqlens_k[i+1].item<int>() * num_heads)}), {num_heads_k, num_heads / num_heads_k, -1, head_size_value_rounded}).sum(1), {-1, head_size_value_rounded});
            dv_padded.index({at::indexing::Slice(cu_seqlens_k[i].item<int>() * num_heads_k, cu_seqlens_k[i+1].item<int>() * num_heads_k)}) = tmp_dv;
        }
zhangshao's avatar
zhangshao committed
3110
    }
hly's avatar
hly committed
3111
3112
3113
3114
3115
3116
3117
    at::Tensor dq, dk, dv;
    if (head_size % 32 != 0) {
        dq = dq_padded.index({"...", at::indexing::Slice(at::indexing::None, head_size)});
        dk = dk_padded.index({"...", at::indexing::Slice(at::indexing::None, head_size)});
    } else {
        dq = dq_padded;
        dk = dk_padded;
zhangshao's avatar
zhangshao committed
3118
    }
hly's avatar
hly committed
3119
3120
    if (head_size_value % 32 != 0) {
        dv = dv_padded.index({"...", at::indexing::Slice(at::indexing::None, head_size_value)});
zhangshao's avatar
zhangshao committed
3121
    } else {
hly's avatar
hly committed
3122
        dv = dv_padded;
zhangshao's avatar
zhangshao committed
3123
3124
    }

hly's avatar
hly committed
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
    // std::cout<<"q.sizes() = "<<q.sizes()<<std::endl;
    // std::cout<<"k.sizes() = "<<k.sizes()<<std::endl;
    // std::cout<<"out.sizes() = "<<out.sizes()<<std::endl;
    // std::cout<<"num_heads = "<<num_heads<<std::endl;
    // std::cout<<"dk.sizes() = "<<dk.sizes()<<std::endl;
    // std::cout<<"layout="<<layout<<std::endl;
    // std::cout<<"dq.sizes() = "<<dq.sizes()<<std::endl;
    // std::cout<<"dq.stride() = "<<dq.stride(0)<<" "<<dq.stride(1)<<" "<<dq.stride(2)<<" "<<dq.stride(3)<<std::endl;
    // std::cout<<"q.stride() = "<<q.stride(0)<<" "<<q.stride(1)<<" "<<q.stride(2)<<" "<<q.stride(3)<<std::endl;
    // std::cout<<"dk.sizes() = "<<dk.sizes()<<std::endl;
    // std::cout<<"dv.sizes() = "<<dv.sizes()<<std::endl;
    // std::cout<<"num_heads_k = "<<num_heads_k<<std::endl;
    // std::cout<<"num_heads = "<<num_heads<<std::endl;
    // std::cout<<"dq.sizes() = "<<dq.sizes()<<std::endl;
    // std::cout<<"dk.sizes() = "<<dk.sizes()<<std::endl;
    // std::cout<<"dv.sizes() = "<<dv.sizes()<<std::endl;

    #ifdef DEBUGING
        return { dq, dk, dv, softmax_d, dev_kq.clone(), dev_s.clone(), dev_dp.clone(), dev_ds.clone()};
    #else
        return { dq, dk, dv, softmax_d };
    #endif
#else
    return {};
#endif
}
zhangshao's avatar
zhangshao committed
3151
3152


hly's avatar
hly committed
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
std::vector<at::Tensor> mha_fwd_kvcache_base(
    at::Tensor &q,
    const at::Tensor &kcache,
    const at::Tensor &vcache,
    c10::optional<const at::Tensor> &k_,
    c10::optional<const at::Tensor> &v_,
    c10::optional<const at::Tensor> &seqlens_q_,
    c10::optional<const at::Tensor> &seqlens_k_,
    int max_seqlen_k,
    c10::optional<const at::Tensor> &rotary_cos_,
    c10::optional<const at::Tensor> &rotary_sin_,
    c10::optional<const at::Tensor> &cache_batch_idx_,
    c10::optional<const at::Tensor> &leftpad_k_,
    c10::optional<at::Tensor> &block_table_,
    c10::optional<at::Tensor> &alibi_slopes_,
    c10::optional<at::Tensor> &out_,
    const float softmax_scale,
    bool is_causal,
    int window_size_left,
    int window_size_right,
    const float softcap,
    bool is_rotary_interleaved,
    int partition_size,
    c10::optional<at::Tensor> &scores_raw,
    c10::optional<at::Tensor> &tmp_output,
    const int layout,
    c10::optional<at::Tensor> scales_q_,
    c10::optional<at::Tensor> scales_k_,
    c10::optional<at::Tensor> scales_v_,
    const bool is_bf16_output
) {
#if defined(BUILD_FA_KVCACHE)
    const at::cuda::HIPGuardMasqueradingAsCUDA device_guard(q.device().index());
    const bool int8_used = scales_k_.has_value();
    auto q_dtype = q.dtype();
    TORCH_CHECK(q_dtype == at::ScalarType::Half || q_dtype == at::ScalarType::BFloat16 || q_dtype == at::ScalarType::Char,
                "FlashAttention only support fp16 and bf16 and int8 data type");
    TORCH_CHECK(kcache.dtype() == q_dtype, "query and key must have the same dtype");
    TORCH_CHECK(vcache.dtype() == q_dtype, "query and value must have the same dtype");

    CHECK_DEVICE(q); CHECK_DEVICE(kcache); CHECK_DEVICE(vcache);

    TORCH_CHECK(q.stride(-1) == 1, "Input tensor must have contiguous last dimension");
    TORCH_CHECK(kcache.stride(-1) == 1, "Input tensor must have contiguous last dimension");
    TORCH_CHECK(vcache.stride(-1) == 1, "Input tensor must have contiguous last dimension");

    at::Tensor block_table;
    const bool paged_KV = block_table_.has_value();
    TORCH_CHECK(paged_KV, "Only PagedAttention KVcache is suppprted yet!");
    if (paged_KV) {
        TORCH_CHECK(!cache_batch_idx_.has_value(), "Paged KVcache does not support cache_batch_idx");
        block_table = block_table_.value();
        CHECK_DEVICE(block_table);
        TORCH_CHECK(block_table.dtype() == at::ScalarType::Int, "block_table must have dtype torch.int32");
        TORCH_CHECK(block_table.stride(-1) == 1, "block_table must have contiguous last dimension");
    }
zhangshao's avatar
zhangshao committed
3209

hly's avatar
hly committed
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
    const auto sizes       = q.sizes();
    const int batch_size   = sizes[0];
    int       num_heads    = (layout == 1) ? sizes[2]: sizes[1];
    int       seqlen_q     = (layout == 1) ? sizes[1]: sizes[2];
    const int head_size_og = sizes[3];
    const int qk_head_size = q.size(3);
    const int v_head_size  = vcache.size(3);
    const int max_num_blocks_per_seq = block_table.size(1);
    const int num_blocks   = kcache.size(0);
    const int page_block_size = (layout == 1) ? kcache.size(1): kcache.size(2);
    const int num_heads_k  = (layout == 1) ? kcache.size(2): kcache.size(1);
    const int batch_size_c = batch_size;
    // multi token prediction
    const int mtp          = (layout == 1) ? sizes[1]: sizes[2];

    TORCH_CHECK(batch_size > 0, "batch size must be positive");
    TORCH_CHECK(qk_head_size <= 256 or qk_head_size == 576, "PagedAttention only supports head dimension at most 256 or MLA-QK-576");
    TORCH_CHECK(v_head_size <= 256 or v_head_size == 512, "PagedAttention only supports head dimension at most 256 or MLA-V-512");
    TORCH_CHECK(num_heads % num_heads_k == 0, "Number of heads in key/value must divide number of heads in query");

    // causal=true is the same as causal=false in this case
    if (seqlen_q == 1 && !alibi_slopes_.has_value()) { is_causal = false; }
    if (is_causal) { window_size_right = 0; }

    // acquire varlen information of Q
    void *cu_seqlens_q = seqlens_q_.has_value() ? seqlens_q_.value().data_ptr(): nullptr;

    // Faster to transpose q from (b, 1, (nheads_kv ngroups), d) to (b, ngroups, nheads_kv, d) in this case
    // H/t Daniel Haziza
    const int ngroups = num_heads / num_heads_k;
    const int seqlenq_ngroups_swapped = (!int8_used or layout == 0) && (v_head_size == 128 or v_head_size == 64) && num_heads > num_heads_k && window_size_left < 0 && window_size_right < 0 && head_size_og % 8 == 0 && !alibi_slopes_.has_value();
    if (seqlenq_ngroups_swapped) {
        // when batch size is small, cu occupancy is likely low, and thus reuse less KV to dispatch more threadgroups
        if (batch_size <= 2) {
            PA_GQA_REGROUP_SWITCH(ngroups, [&] {
                if (layout == 0) {
                    q = q.view({batch_size, num_heads_k * int(ngroups / GQA_REGROUP), GQA_REGROUP * mtp, qk_head_size});
                } else {
                    q = q.view({batch_size, mtp, -1, GQA_REGROUP, qk_head_size}).transpose(2, 3).contiguous().view({batch_size, mtp * GQA_REGROUP, -1, qk_head_size});
                }
                seqlen_q  = GQA_REGROUP * mtp;
                num_heads = num_heads_k * int(ngroups / GQA_REGROUP);
            });
        } else {
            // default reuse strategy
            if (layout == 0) {
                q = q.view({batch_size, num_heads_k * int(ngroups / ngroups), ngroups * mtp, qk_head_size});
            } else {
                q = q.view({batch_size, mtp, -1, ngroups, qk_head_size}).transpose(2, 3).contiguous().view({batch_size, mtp * ngroups, -1, qk_head_size});
            }
            seqlen_q  = ngroups * mtp;
            num_heads = num_heads_k;
        }
    }
zhangshao's avatar
zhangshao committed
3264

hly's avatar
hly committed
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
    if (window_size_left >= max_seqlen_k) { window_size_left = -1; }
    if (window_size_right >= max_seqlen_k) { window_size_right = -1; }

    TORCH_CHECK(int64_t(batch_size * num_heads * seqlen_q * qk_head_size) < /*2^31*/int64_t(2147483648), "The data amount of q must be smaller than the representation range of int");
    // TORCH_CHECK(int64_t(total_k_heads * head_size_og) < /*2^31*/int64_t(2147483648), "The data amount of k/v must be smaller than the representation range of int");
    if (!paged_KV) {
        CHECK_SHAPE(q, batch_size, seqlen_q, num_heads, qk_head_size);
        CHECK_SHAPE(kcache, batch_size_c, seqlen_q, num_heads_k, qk_head_size);
        CHECK_SHAPE(vcache, batch_size_c, seqlen_q, num_heads_k, v_head_size);
    } else {
        // CHECK_SHAPE(block_table, batch_size, max_num_blocks_per_seq);
        // CHECK_SHAPE(q, total_q_heads, qk_head_size);
        // CHECK_SHAPE(kcache, total_k_heads, head_size_og);
        // CHECK_SHAPE(vcache, total_k_heads, head_size_og);
    }

    at::Tensor q_padded, kcache_padded, vcache_padded, accum_output_padded;
    constexpr int HEADDIM_GRANULARITY = 32; // headdim 模板参数化的最小粒度是 32
    const bool QK_IS_NOT_COMMON_HEADDIM  = (qk_head_size % HEADDIM_GRANULARITY != 0);
zhangshao's avatar
zhangshao committed
3284
    if (QK_IS_NOT_COMMON_HEADDIM) {
hly's avatar
hly committed
3285
3286
        q_padded = at::pad(q, {0, HEADDIM_GRANULARITY - qk_head_size % HEADDIM_GRANULARITY});
        kcache_padded = at::pad(kcache, {0, HEADDIM_GRANULARITY - qk_head_size % HEADDIM_GRANULARITY});
zhangshao's avatar
zhangshao committed
3287
    } else {
hly's avatar
hly committed
3288
3289
        q_padded = q;
        kcache_padded = kcache;
zhangshao's avatar
zhangshao committed
3290
3291
    }

hly's avatar
hly committed
3292
3293
    const bool V_IS_NOT_COMMON_HEADDIM  = (v_head_size % HEADDIM_GRANULARITY != 0);

zhangshao's avatar
zhangshao committed
3294
    if (V_IS_NOT_COMMON_HEADDIM) {
hly's avatar
hly committed
3295
3296
        vcache_padded = at::pad(vcache, {0, HEADDIM_GRANULARITY - v_head_size % HEADDIM_GRANULARITY});
        if (tmp_output.has_value()) accum_output_padded = at::pad(tmp_output.value(), {0, HEADDIM_GRANULARITY - v_head_size % HEADDIM_GRANULARITY});
zhangshao's avatar
zhangshao committed
3297
    } else {
hly's avatar
hly committed
3298
3299
        vcache_padded = vcache;
        if (tmp_output.has_value()) accum_output_padded = tmp_output.value();
zhangshao's avatar
zhangshao committed
3300
3301
    }

hly's avatar
hly committed
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
    auto opts = q.options();
    at::Tensor out;
    bool output_allocated_outside = out_.has_value();
    if (output_allocated_outside) {
        out = out_.value();
        if (!int8_used){
            TORCH_CHECK(out.dtype() == q_dtype, "Output must have the same dtype as inputs");
        }
        CHECK_DEVICE(out);
        // TORCH_CHECK(out.stride(-1) == 1, "Output tensor must have contiguous last dimension");
        // CHECK_SHAPE(out, batch_size, seqlen_q, num_heads, v_head_size);
        if (V_IS_NOT_COMMON_HEADDIM) { out = at::empty_like(q_padded); }
        // out = out.view_as(q);
        out = out.view({q.size(0), q.size(1), q.size(2), -1});
    } else {
        if (!int8_used) {
            out = at::empty({{q.size(0), q.size(1), q.size(2), vcache_padded.size(-1)}}, opts);
        } else {
            auto int8_opts = is_bf16_output ? opts.dtype(at::ScalarType::BFloat16) : opts.dtype(at::ScalarType::Half);
            out = at::empty({{q.size(0), q.size(1), q.size(2), vcache_padded.size(-1)}}, int8_opts);
        }
    }
zhangshao's avatar
zhangshao committed
3324

hly's avatar
hly committed
3325
3326
3327
    auto round_multiple = [](int x, int m) { return (x + m - 1) / m * m; };
    const int qk_head_size_rounded = round_multiple(round_multiple(qk_head_size, 8), HEADDIM_GRANULARITY);
    const int v_head_size_rounded = round_multiple(round_multiple(v_head_size, 8), HEADDIM_GRANULARITY);
zhangshao's avatar
zhangshao committed
3328

hly's avatar
hly committed
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
    const int seqlen_q_rounded = round_multiple(seqlen_q, 32);
    const int seqlen_k_rounded = round_multiple(max_seqlen_k, 32);

    // auto softmax_lse = at::empty({batch_size, num_heads, seqlen_q}, opts.dtype(at::kFloat));
    bool seqlens_k_has_value = seqlens_k_.has_value();
    if (seqlens_k_has_value) {
        auto seqlens_k = seqlens_k_.value();
        TORCH_CHECK(seqlens_k.dtype() == at::ScalarType::Int, "seqlens_k must have dtype int32");
        CHECK_DEVICE(seqlens_k);
        CHECK_CONTIGUOUS(seqlens_k);
    }

    Flash_fwd_params params;
    set_params_fprop(params,
                     batch_size,
                     seqlen_q, max_seqlen_k,
                     seqlen_q_rounded, seqlen_k_rounded,
                     num_heads, num_heads_k,
                     qk_head_size, qk_head_size_rounded,
                     v_head_size, v_head_size_rounded,
                     q_padded, kcache_padded, vcache_padded, out,
                     /*cu_seqlens_q_d=*/cu_seqlens_q,
                     /*cu_seqlens_k_d=*/seqlens_k_has_value ? seqlens_k_.value().data_ptr(): nullptr,
                     /*seqused_k=*/nullptr,
                     /*p_ptr=*/nullptr,
                     /*softmax_lse.data_ptr()*/nullptr,
                     /*p_dropout=*/0.f,
                     softmax_scale,
                     window_size_left,
                     window_size_right,
                     softcap,
                     seqlenq_ngroups_swapped,
                     /*unpadded_lse*/true,
                     /*is_kvcache*/true,
                     /*is_seqlens_k_cumulative*/seqlens_k_has_value ? (seqlens_k_.value().size(0) == (batch_size + 1)): false,
                     layout
                    );

    if (int8_used){
        params.is_bf16 = is_bf16_output;
        at::Tensor scales_q;
        scales_q = scales_q_.value();
        params.scales_q_ptr = scales_q.data_ptr();
        params.total_scale_q = scales_q.numel();
        at::Tensor scales_k;
        scales_k = scales_k_.value();
        params.scales_k_ptr = scales_k.data_ptr();
        at::Tensor scales_v;
        scales_v = scales_v_.value();
        params.scales_v_ptr = scales_v.data_ptr();
    }
    if (k_.has_value()) {
        at::Tensor k, v, k_padded, v_padded;
        TORCH_CHECK(v_.has_value(), "If key is supplied, value must also be passed in");
        TORCH_CHECK(seqlens_k_.has_value(), "If key is supplied, seqlens_k must also be passed in");
        TORCH_CHECK(seqlen_q <= max_seqlen_k, "If key is supplied, it must have seqlen <= the seqlen of the KV cache");
        k = k_.value();
        v = v_.value();
        if (!int8_used){
            TORCH_CHECK(k.dtype() == q_dtype, "Key must have the same dtype as query");
            TORCH_CHECK(v.dtype() == q_dtype, "Value must have the same dtype as query");
        }
        CHECK_DEVICE(k); CHECK_DEVICE(v);
        // TORCH_CHECK(k.stride(-1) == 1, "Key tensor must have contiguous last dimension");
        // TORCH_CHECK(v.stride(-1) == 1, "Value tensor must have contiguous last dimension");
        int seqlen_knew = k.size(1);
        // CHECK_SHAPE(k, batch_size, seqlen_knew, num_heads_k, qk_head_size);
        // CHECK_SHAPE(v, batch_size, seqlen_knew, num_heads_k, v_head_size);
        if (QK_IS_NOT_COMMON_HEADDIM) {
            k_padded = at::pad(k, {0, HEADDIM_GRANULARITY - qk_head_size % HEADDIM_GRANULARITY});
        } else {
            k_padded = k;
        }

        if (V_IS_NOT_COMMON_HEADDIM) {
            v_padded = at::pad(v, {0, HEADDIM_GRANULARITY - v_head_size % HEADDIM_GRANULARITY});
        } else {
            v_padded = v;
        }
        params.seqlen_knew = seqlen_knew;
        params.knew_ptr = k_padded.data_ptr();
        params.vnew_ptr = v_padded.data_ptr();
        // All stride are in elements, not bytes.
        params.knew_batch_stride = k_padded.stride(0);
        params.vnew_batch_stride = v_padded.stride(0);
        params.knew_row_stride = k_padded.stride(-3);
        params.vnew_row_stride = v_padded.stride(-3);
        params.knew_head_stride = k_padded.stride(-2);
        params.vnew_head_stride = v_padded.stride(-2);
    }

    // params.is_seqlens_k_cumulative = !(seqlens_k_.has_value());
    if (leftpad_k_.has_value()) {
        TORCH_CHECK(!paged_KV, "We don't support Paged KV and leftpad_k running at the same time yet");
        auto leftpad_k = leftpad_k_.value();
        TORCH_CHECK(leftpad_k.dtype() == at::ScalarType::Int, "leftpad_k must have dtype int32");
        CHECK_DEVICE(leftpad_k);
        CHECK_CONTIGUOUS(leftpad_k);
        CHECK_SHAPE(leftpad_k, batch_size);
        params.leftpad_k = static_cast<int *>(leftpad_k.data_ptr());
    }
zhangshao's avatar
zhangshao committed
3430

hly's avatar
hly committed
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
    if (rotary_cos_.has_value()) {
        TORCH_CHECK(k_.has_value(), "If rotary cos/sin are provided, new key / value to be appended to KV cache must also be provided");
        auto rotary_cos = rotary_cos_.value();
        CHECK_DEVICE(rotary_cos);
        params.rotary_dim = rotary_cos.size(1) * 2;
        TORCH_CHECK(params.rotary_dim <= qk_head_size, "rotary_dim must be <= headdim");
        TORCH_CHECK(params.rotary_dim % 16 == 0, "Only rotary dimensions divisible by 16 are currently supported");
        const int seqlen_ro = rotary_cos.size(0);
        TORCH_CHECK(seqlen_ro >= max_seqlen_k, "cos/sin seqlen must be at least the seqlen of KV cache");
        CHECK_SHAPE(rotary_cos, seqlen_ro, params.rotary_dim / 2);
        CHECK_CONTIGUOUS(rotary_cos);
        TORCH_CHECK(rotary_cos.scalar_type() == q_dtype, "rotary_cos must have the same dtype as query");

        TORCH_CHECK(rotary_sin_.has_value(), "If rotary cos is provided, rotary sin must also be provided");
        auto rotary_sin = rotary_sin_.value();
        CHECK_DEVICE(rotary_sin);
        CHECK_SHAPE(rotary_sin, seqlen_ro, params.rotary_dim / 2);
        CHECK_CONTIGUOUS(rotary_sin);
        TORCH_CHECK(rotary_sin.scalar_type() == q_dtype, "rotary_cos must have the same dtype as query");
        params.rotary_cos_ptr = rotary_cos.data_ptr();
        params.rotary_sin_ptr = rotary_sin.data_ptr();
        params.is_rotary_interleaved = is_rotary_interleaved;
zhangshao's avatar
zhangshao committed
3453
    } else {
hly's avatar
hly committed
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
        params.rotary_dim = 0;
    }

    if (cache_batch_idx_.has_value()) {
        auto cache_batch_idx = cache_batch_idx_.value();
        CHECK_DEVICE(cache_batch_idx);
        CHECK_CONTIGUOUS(cache_batch_idx);
        TORCH_CHECK(cache_batch_idx.scalar_type() == at::ScalarType::Int, "cache_batch_idx must have dtype int32");
        params.cache_batch_idx = reinterpret_cast<int *>(cache_batch_idx.data_ptr());
    }

    // Acquire cu count
    hipDeviceProp_t props;
    auto hipResult = hipGetDeviceProperties(&props, 0);
    params.cu_count = props.multiProcessorCount;

    // check if splitkv is forbidden
    bool allow_splitkv = bool(std::getenv("PA_NO_SPLITKV") == nullptr) and (v_head_size_rounded == 128 or v_head_size_rounded == 512 or v_head_size_rounded == 64);

    // Keep references to these tensors to extend their lifetime
    at::Tensor scores_sum, scores_max, out_accum;
    if (allow_splitkv and partition_size > 0) {
        // compare with official methods, we don't consider the relationship between partition_size and cu_count
        // since we don't support arbitrary partition size yet
        bool partition_size_assigned = scores_raw.has_value() and tmp_output.has_value();
        at::Tensor raw_memory;
        if (partition_size_assigned) {
            params.partition_size = partition_size;
            params.num_splits = std::max<int32_t>(1, std::floor(max_seqlen_k * 1.f / params.partition_size));
            TORCH_CHECK(params.num_splits <= 1024, "num_splits > 128 not supported");
            TORCH_CHECK(params.partition_size >= 128, "partition_size >= 128 is required");
            TORCH_CHECK(params.partition_size % page_block_size == 0, "partition_size must be multiple of page_block_size");
            raw_memory = scores_raw.value().view({2, params.num_splits, batch_size, num_heads, seqlen_q});
        } else {
            // 指定的不是 partition_size 而是 num_splits, 这样 batch_size, num_splits, num_heads 都是固定的, 可以跑 cudagraph
            params.num_splits = partition_size;
            params.partition_size = std::max<int32_t>(128, std::ceil(max_seqlen_k * 1.f / (params.num_splits * page_block_size)) * page_block_size);
            raw_memory = at::empty({2, params.num_splits, batch_size, num_heads, seqlen_q}, opts.dtype(at::kFloat));
            if (layout == 0)      accum_output_padded = at::empty({params.num_splits, batch_size, num_heads, seqlen_q, v_head_size_rounded}, opts.dtype(q_dtype));
            else if (layout == 1) accum_output_padded = at::empty({params.num_splits, batch_size, seqlen_q, num_heads, v_head_size_rounded}, opts.dtype(q_dtype));
zhangshao's avatar
zhangshao committed
3494
3495
3496
        }
        scores_sum = raw_memory.index({0});
        scores_max = raw_memory.index({1});
hly's avatar
hly committed
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
        out_accum  = /*original is tmp_output*/accum_output_padded.view({params.num_splits, batch_size, num_heads, seqlen_q, v_head_size_rounded}); // 看官方的写法, O_accum 用的更高精度去写的, 而不是半精度
        params.scores_sum_ptr = reinterpret_cast<float*>(scores_sum.data_ptr());
        params.scores_max_ptr = reinterpret_cast<float*>(scores_max.data_ptr());
        params.oaccum_ptr     = out_accum.data_ptr();
    }
    // 如果没有指定 partition size, 且 headdim 128, 自主决定切分策略
    if (allow_splitkv and !tmp_output.has_value() and partition_size == 0) {
        const char* partition_size_env = std::getenv("PA_PARTITION_SIZE");
        const int partition_size_assign = partition_size_env ? std::atoi(partition_size_env): 0;
        // 没有指定 splitkv 分块大小, 则启发式
        if (partition_size_assign == 0) {
            // 如果初步能划分的 block 数量对应的利用率不高
            constexpr int device_cu = 128;
            const int threshold     = device_cu;
            // 如果 gqa 组数不是常见的 16/8/4/2/9/7/5/3 的倍数, ngroup 会被全部 re-group 到 seqlen 维度上, 会导致发的 TG 比较少, 因此算最优 partition size 的时候还是要认为 ngroup = 1
            // 原始是 GQA, 但做了最大程度的 regroup
            const bool use_max_regroup  = (ngroups > 1 and ngroups != 29 and ngroups != 16 and ngroups != 8 and ngroups != 4 and ngroups != 2 and ngroups != 9 and ngroups != 7 and ngroups != 5 and ngroups != 3);
            int actual_ngroup = use_max_regroup ? 1: ngroups;
            // 如果目前能发的 TG 数量比较少而且最大的 seqkv 不是很短
            // 或者 seqkv 比较长, 可以做切分
            if ((batch_size * 1/*seq_q_len*/ * actual_ngroup < threshold and max_seqlen_k >= 1024) or (max_seqlen_k >= 8192)) {
                // 根据一个 batch 里最大的 seqKV 长度, 决定相应的划分 size
                if (max_seqlen_k <= 1024)       partition_size = 128;
                else if (max_seqlen_k <= 2048)  partition_size = 256;
                else if (max_seqlen_k <= 32768) partition_size = 512;
                else                            partition_size = 1024;
                // 如果是 MHA, 无法做 GQA ngroup-swapped 优化, 可以发更多的 TG, 不需要划分那么多小块, 可以划分大一点的块
                if (ngroups == 1) partition_size = 1024;
                // 如果按照上述划分之后, 利用率还不是很高, partition size 继续减半
                while (ngroups > 1 and (batch_size * 1/*seq_q_len*/ * actual_ngroup * (max_seqlen_k / partition_size)) < threshold) {
                    // 目前支持的最小 partition size 是 128
                    if (partition_size < 256) break;
                    partition_size = int(partition_size / 2);
                }
            }
        } else if (partition_size_assign >= 128 and partition_size_assign <= 1024) {
            // 指定的 partition_size 满足需求, 可以开始划分
            partition_size = partition_size_assign;
        }
        // 如果划分满足最小粒度 128 的倍数, 且不超过 1024 个划分, 则允许 splitkv 算法
        // 128 的倍数, 对应 kernel: int this_split_seqlen_start = Split ? split_id * params.partition_size: 0; 暂不支持任意长度的 splitkv
        if (partition_size >= 128 and partition_size % page_block_size == 0) {
            // 截断最后一个切分到前一个 block 上去计算
            const int num_splits = std::max<int32_t>(1, std::floor(max_seqlen_k * 1.f / partition_size));
            // 最大支持 1024 个划分
            if (num_splits <= 1024) {
                // 传递给 kernel args
                params.partition_size = partition_size;
                params.num_splits     = num_splits;
                auto raw_memory = at::empty({2, params.num_splits, batch_size, num_heads, seqlen_q}, opts.dtype(at::kFloat));
                scores_sum = raw_memory.index({0});
                scores_max = raw_memory.index({1});
                if (layout == 0)      out_accum  = at::empty({params.num_splits, batch_size, num_heads, seqlen_q, v_head_size_rounded}, opts.dtype(q_dtype));
                else if (layout == 1) out_accum  = at::empty({params.num_splits, batch_size, seqlen_q, num_heads, v_head_size_rounded}, opts.dtype(q_dtype));
                params.scores_sum_ptr = reinterpret_cast<float*>(scores_sum.data_ptr());
                params.scores_max_ptr = reinterpret_cast<float*>(scores_max.data_ptr());
                params.oaccum_ptr     = out_accum.data_ptr();
            }
        }
zhangshao's avatar
zhangshao committed
3556
3557
    }

hly's avatar
hly committed
3558
3559
3560
3561
    // decide accumulation dtype when splitkv
    if (params.partition_size > 0 and params.num_splits > 1) {
        params.splitkv_use_fp32_as_accum = out_accum.dtype() == at::ScalarType::Float;
    }
zhangshao's avatar
zhangshao committed
3562

hly's avatar
hly committed
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
    if (paged_KV) {
        params.block_table = block_table.data_ptr<int>();
        params.block_table_batch_stride = block_table.stride(0);
        params.k_batch_stride = kcache_padded.stride(0);
        params.v_batch_stride = vcache_padded.stride(0);
    }
    params.page_block_size = page_block_size;
    params.mtp = mtp;

    set_params_alibi(params, alibi_slopes_, batch_size, num_heads);

    // print main args
    bool fa_debug = (std::getenv("FA_DEBUG") != nullptr);
    if (fa_debug) {
        PRINT_PARAMS
        auto temp_tensor = seqlens_k_.value().to(at::DeviceType::CPU).contiguous();
        std::vector<int32_t> temp_vector(temp_tensor.data_ptr<int32_t>(), temp_tensor.data_ptr<int32_t>() + temp_tensor.numel());
        printf("seqlens_k: ["); for (const auto val: temp_vector) { printf("%d ", val); } printf("]\n");
        PRINT_QKV_INFO(q, kcache, vcache)
        std::cout << "block_table: " << block_table.sizes() << "\n";
    }
zhangshao's avatar
zhangshao committed
3584

hly's avatar
hly committed
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
    const hipStream_t stream = at::hip::getCurrentHIPStreamMasqueradingAsCUDA();
    // Only split kernel supports appending to KV cache, or indexing to the cache with cache_batch_idx,
    // or paged KV cache
    // run_mha_fwd(params, stream, /*force_split_kernel=*/k_.has_value() || cache_batch_idx_.has_value() || paged_KV);
    if (max_seqlen_k > 0 and std::getenv("PA_EMPTY") == nullptr) {
        if (!int8_used){
            run_mha_fwd_kvcache(params, stream, paged_KV);
        } else{
            run_int8_fwd_kvcache(params, stream, paged_KV);
        }
zhangshao's avatar
zhangshao committed
3595
    } else {
hly's avatar
hly committed
3596
3597
        out.zero_();
        // softmax_lse.fill_(std::numeric_limits<float>::infinity());
zhangshao's avatar
zhangshao committed
3598
3599
    }

hly's avatar
hly committed
3600
3601
3602
3603
3604
3605
3606
    if (seqlenq_ngroups_swapped) {
        if (layout == 0) {
            out = out.view({batch_size, -1, mtp, v_head_size_rounded});
        } else if (layout == 1) {
            out = out.view({batch_size, mtp, -1, num_heads, v_head_size_rounded}).transpose(2, 3).contiguous().view({batch_size, mtp, -1, v_head_size_rounded});
            if (output_allocated_outside and out_.has_value()) { out_.value().copy_(out.clone()); } // strange, without this line, result is wrong
        }
zhangshao's avatar
zhangshao committed
3607
3608
    }

hly's avatar
hly committed
3609
3610
3611
3612
3613
3614
    if (QK_IS_NOT_COMMON_HEADDIM) {
        if (k_.has_value()) {
            // It's expensive to copy the KV cache here for the case where head size not divisible by 8,
            // but we don't expect to get this case in practice. This is just so that the code works for that case.
            kcache.copy_(kcache_padded.index({"...", at::indexing::Slice(at::indexing::None, qk_head_size)}));
        }
zhangshao's avatar
zhangshao committed
3615
3616
    }

hly's avatar
hly committed
3617
3618
3619
3620
3621
3622
3623
3624
    if (V_IS_NOT_COMMON_HEADDIM) {
        out = out.index({"...", at::indexing::Slice(at::indexing::None, v_head_size)});
        if (out_.has_value()) { out_.value().copy_(out); }
        if (v_.has_value()) {
            // It's expensive to copy the KV cache here for the case where head size not divisible by 8,
            // but we don't expect to get this case in practice. This is just so that the code works for that case.
            vcache.copy_(vcache_padded.index({"...", at::indexing::Slice(at::indexing::None, v_head_size)}));
        }
zhangshao's avatar
zhangshao committed
3625
3626
    }

hly's avatar
hly committed
3627
3628
3629
3630
3631
    if (output_allocated_outside) {
        return {out};
    } else {
        return {out, out_accum, scores_max, scores_sum, at::tensor(params.partition_size, at::dtype(at::ScalarType::Int))};
    }
zhangshao's avatar
zhangshao committed
3632
#else
hly's avatar
hly committed
3633
    return {};
zhangshao's avatar
zhangshao committed
3634
3635
3636
#endif
}

hly's avatar
hly committed
3637

zhangshao's avatar
zhangshao committed
3638
std::vector<at::Tensor> mha_fwd_kvcache_bhsd(
hly's avatar
hly committed
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
        at::Tensor &q,
        const at::Tensor &kcache,
        const at::Tensor &vcache,
        c10::optional<const at::Tensor> &k_,
        c10::optional<const at::Tensor> &v_,
        c10::optional<const at::Tensor> &seqlens_q_,
        c10::optional<const at::Tensor> &seqlens_k_,
        int max_seqlen_k,
        c10::optional<const at::Tensor> &rotary_cos_,
        c10::optional<const at::Tensor> &rotary_sin_,
        c10::optional<const at::Tensor> &cache_batch_idx_,
        c10::optional<const at::Tensor> &leftpad_k_,
        c10::optional<at::Tensor> &block_table_,
        c10::optional<at::Tensor> &alibi_slopes_,
        c10::optional<at::Tensor> &out_,
        const float softmax_scale,
        bool is_causal,
        int window_size_left,
        int window_size_right,
        const float softcap,
        bool is_rotary_interleaved,
        int partition_size,
        c10::optional<at::Tensor> &scores_raw,
        c10::optional<at::Tensor> &tmp_output,
        c10::optional<at::Tensor> scales_q_,
        c10::optional<at::Tensor> scales_k_,
        c10::optional<at::Tensor> scales_v_,
        const bool is_bf16_output
    ) {
    return mha_fwd_kvcache_base(q, kcache, vcache,
        k_, v_, seqlens_q_, seqlens_k_, max_seqlen_k, rotary_cos_, rotary_sin_, cache_batch_idx_, leftpad_k_, block_table_, alibi_slopes_, out_, softmax_scale, is_causal, window_size_left, window_size_right, softcap, is_rotary_interleaved, partition_size, scores_raw, tmp_output,
        0/*bhsd*/, scales_q_, scales_k_, scales_v_, is_bf16_output
    );
zhangshao's avatar
zhangshao committed
3672
3673
}

hly's avatar
hly committed
3674

zhangshao's avatar
zhangshao committed
3675
std::vector<at::Tensor> hg_fwd_kvcache_bshd(
hly's avatar
hly committed
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
        at::Tensor &q,
        const at::Tensor &kcache,
        const at::Tensor &vcache,
        c10::optional<const at::Tensor> &k_,
        c10::optional<const at::Tensor> &v_,
        c10::optional<const at::Tensor> &seqlens_q_,
        c10::optional<const at::Tensor> &seqlens_k_,
        int max_seqlen_k,
        c10::optional<const at::Tensor> &rotary_cos_,
        c10::optional<const at::Tensor> &rotary_sin_,
        c10::optional<const at::Tensor> &cache_batch_idx_,
        c10::optional<const at::Tensor> &leftpad_k_,
        c10::optional<at::Tensor> &block_table_,
        c10::optional<at::Tensor> &alibi_slopes_,
        c10::optional<at::Tensor> &out_,
        const float softmax_scale,
        bool is_causal,
        int window_size_left,
        int window_size_right,
        const float softcap,
        bool is_rotary_interleaved,
        int partition_size,
        c10::optional<at::Tensor> &scores_raw,
        c10::optional<at::Tensor> &tmp_output,
        c10::optional<at::Tensor> scales_q_,
        c10::optional<at::Tensor> scales_k_,
        c10::optional<at::Tensor> scales_v_,
        const bool is_bf16_output
    ) {
    return mha_fwd_kvcache_base(q, kcache, vcache,
        k_, v_, seqlens_q_, seqlens_k_, max_seqlen_k, rotary_cos_, rotary_sin_, cache_batch_idx_, leftpad_k_, block_table_, alibi_slopes_, out_, softmax_scale, is_causal, window_size_left, window_size_right, softcap, is_rotary_interleaved, partition_size, scores_raw, tmp_output,
        1/*bshd*/, scales_q_, scales_k_, scales_v_, is_bf16_output
    );
zhangshao's avatar
zhangshao committed
3709
3710
}

hly's avatar
hly committed
3711
3712
3713



zhangshao's avatar
zhangshao committed
3714
3715
3716
3717
3718
3719
3720
3721
std::vector<at::Tensor> hg_prefix_decode_varlen_fwd(
    at::Tensor &q, const at::Tensor &k, const at::Tensor &v,
    c10::optional<at::Tensor> &out_, const at::Tensor &cu_seqlens_q,
    c10::optional<at::Tensor> &cu_seqlens_k, at::Tensor &seqused_k,
    c10::optional<at::Tensor> &alibi_slopes_, at::Tensor &block_table,
    const int max_seqlen_q, const int max_seqlen_k, const float p_dropout,
    const float softmax_scale, const bool zero_tensors, const bool is_causal,
    int window_size_left, int window_size_right, const float softcap,
hly's avatar
hly committed
3722
3723
3724
3725
3726
3727
    const bool return_softmax, const int layout,
    c10::optional<at::Tensor> scales_q_ = c10::nullopt,
    c10::optional<at::Tensor> scales_k_ = c10::nullopt,
    c10::optional<at::Tensor> scales_v_ = c10::nullopt,
    c10::optional<at::Tensor> s_aux_ = c10::nullopt,
    const bool is_bf16_output = false ) {
zhangshao's avatar
zhangshao committed
3728
3729
3730
3731
3732
3733
3734
3735
3736
#if defined(BUILD_FA_KVCACHE)
  const at::cuda::HIPGuardMasqueradingAsCUDA device_guard(q.device().index());
  // TORCH_CHECK(is_causal == true, "For prefix decode, only causal mask = True
  // is supported!");
  if (is_causal) {
    window_size_right = 0;
  }

  auto q_dtype = q.dtype();
hly's avatar
hly committed
3737
  const bool fp8_used = q_dtype == at::ScalarType::Float8_e4m3fn;
zhangshao's avatar
zhangshao committed
3738
  TORCH_CHECK(q_dtype == at::ScalarType::Half ||
hly's avatar
hly committed
3739
3740
3741
              q_dtype == at::ScalarType::BFloat16 ||
              q_dtype == at::ScalarType::Float8_e4m3fn,
              "For prefix decode, only support fp16/bf16/fp8_e4m3 data type");
zhangshao's avatar
zhangshao committed
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
  TORCH_CHECK(k.dtype() == q_dtype,
              "For prefix decode, query and key must have the same dtype");
  TORCH_CHECK(v.dtype() == q_dtype,
              "For prefix decode, query and value must have the same dtype");
  TORCH_CHECK(cu_seqlens_q.dtype() == at::ScalarType::Int,
              "For prefix decode, cu_seqlens_q must have dtype int32");
  TORCH_CHECK(seqused_k.dtype() == at::ScalarType::Int,
              "For prefix decode, seqused_k must have dtype int32");

  CHECK_DEVICE(q);
  CHECK_DEVICE(k);
  CHECK_DEVICE(v);
  CHECK_DEVICE(cu_seqlens_q);
  CHECK_DEVICE(seqused_k);

  TORCH_CHECK(
      q.stride(-1) == 1,
      "For prefix decode, Input tensor must have contiguous last dimension");
  TORCH_CHECK(
      k.stride(-1) == 1,
      "For prefix decode, Input tensor must have contiguous last dimension");
  TORCH_CHECK(
      v.stride(-1) == 1,
      "For prefix decode, Input tensor must have contiguous last dimension");
  CHECK_CONTIGUOUS(cu_seqlens_q);
  CHECK_CONTIGUOUS(seqused_k);

  const bool use_bshd_layout = layout == 1;
  const auto query_size = q.sizes();
  const auto k_size = k.sizes();
  const auto v_size = v.sizes();
  int num_heads = query_size[1];
hly's avatar
hly committed
3774
  const int original_num_heads = num_heads;
zhangshao's avatar
zhangshao committed
3775
3776
3777
3778
3779
3780
3781
3782
  const int num_heads_k = k_size[2];
  const int head_size_og = use_bshd_layout ? query_size[2] : query_size[1];
  const int head_size_value = use_bshd_layout ? v_size[3] : v_size[2];
  const int total_q =
      use_bshd_layout ? query_size[0] : query_size[0] / num_heads;
  const int batch_size = cu_seqlens_q.numel() - 1;
  const int page_block_size = use_bshd_layout ? k_size[1] : k_size[2];
  TORCH_CHECK(batch_size > 0, "For prefix decode, batch size must be positive");
hly's avatar
hly committed
3783
3784
  TORCH_CHECK(page_block_size == 128 || page_block_size == 64,
              "For prefix decode, only supports page block_size 128 or 64");
zhangshao's avatar
zhangshao committed
3785
  TORCH_CHECK((head_size_og == 128 and head_size_value == 128) or
hly's avatar
hly committed
3786
3787
3788
              (head_size_og == 192 and head_size_value == 128) or
              (head_size_og == 192 and head_size_value == 192) or
              (head_size_og == 256 and head_size_value == 256),
zhangshao's avatar
zhangshao committed
3789
3790
              "For prefix decode, only supports head dimension "
              "128+128/192+128/192+192/256+256");
hly's avatar
hly committed
3791
3792
3793
3794
3795
3796
3797
3798
3799
  if (fp8_used) {
    TORCH_CHECK((head_size_og == 128 and head_size_value == 128) or
                (head_size_og == 192 and head_size_value == 128) or
                (head_size_og == 256 and head_size_value == 256),
                "For fp8 prefix decode, only supports head dimension "
                "128+128/192+128/256+256 on gfx938 MLS kernel");
    TORCH_CHECK(scales_q_.has_value() && scales_k_.has_value() && scales_v_.has_value(),
                "For fp8 prefix decode, q/k/v descale tensors must be provided");
  }
zhangshao's avatar
zhangshao committed
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
  TORCH_CHECK(
      num_heads % num_heads_k == 0,
      "Number of heads in key/value must divide number of heads in query");
  TORCH_CHECK(int64_t(query_size[0] * head_size_og) <
                  /*2^31*/ int64_t(2147483648),
              "The data amount of q must be smaller than the representation "
              "range of int");
  TORCH_CHECK(int64_t(k_size[0] * head_size_value) <
                  /*2^31*/ int64_t(2147483648),
              "The data amount of k/v must be smaller than the representation "
              "range of int");
  CHECK_SHAPE(cu_seqlens_q, batch_size + 1);
  CHECK_SHAPE(seqused_k, batch_size);

  if (softcap > 0.f) {
    TORCH_CHECK(
        p_dropout == 0.f,
        "For prefix decode, Softcapping does not support dropout for now");
  }

  int ngroups = num_heads / num_heads_k;
  const int ngroups_limit = std::getenv("PA_USE_TILE32X32") == nullptr
                                ? 32
                                : 16 /*32 is not supported for 32x32tile yet*/;
  while (ngroups > 1) {
    if (ngroups * max_seqlen_q <= ngroups_limit and
        (num_heads % ngroups == 0 and num_heads / ngroups % num_heads_k == 0))
      break;
    --ngroups;
  }
  if (ngroups > 1) {
    num_heads = num_heads / ngroups;
    q = q.view({total_q, num_heads, ngroups, -1})
            .transpose(1, 2)
            .contiguous()
            .view({total_q * ngroups, num_heads, -1});
  }

  auto round_multiple = [](int x, int m) { return (x + m - 1) / m * m; };
  const int head_size = round_multiple(head_size_og, 8);
  const int head_size_rounded = round_multiple(head_size, 32);
  const int head_size_v = round_multiple(head_size_value, 8);
  const int head_size_v_rounded = round_multiple(head_size_v, 32);
  const int seqlen_q_rounded = round_multiple(max_seqlen_q, 32);
  const int seqlen_k_rounded = round_multiple(max_seqlen_k, 32);

  at::Tensor q_padded, k_padded, v_padded;
  if (head_size_og % 32 != 0) {
    q_padded = at::pad(q, {0, 32 - head_size_og % 32});
    k_padded = at::pad(k, {0, 32 - head_size_og % 32});
  } else {
    q_padded = q;
    k_padded = k;
  }

  if (head_size_value % 32 != 0) {
    v_padded = at::pad(v, {0, 32 - head_size_value % 32});
  } else {
    v_padded = v;
  }

  auto opts = q.options();
  at::Tensor out;
  bool output_allocated_outside = out_.has_value();
  if (output_allocated_outside) {
    out = out_.value();
hly's avatar
hly committed
3866
3867
3868
3869
3870
3871
3872
    if (!fp8_used){
      TORCH_CHECK(out.dtype() == q_dtype, "Output must have the same dtype as inputs");
    } else {
      TORCH_CHECK(out.dtype() == at::ScalarType::Half ||
                  out.dtype() == at::ScalarType::BFloat16,
                  "For fp8 prefix decode, output must be fp16 or bf16");
    }
zhangshao's avatar
zhangshao committed
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
    if (out.is_contiguous()) {
      out = out.view({q.size(0), q.size(1), -1});
      CHECK_DEVICE(out);
      TORCH_CHECK(out.stride(-1) == 1, "For prefix decode, output tensor must "
                                       "have contiguous last dimension");
    } else {
      out = at::empty({q.size(0), q.size(1), v_padded.size(-1)}, opts);
    }
  } else {
    // for (bs)hd layout
hly's avatar
hly committed
3883
3884
3885
3886
3887
3888
    if (fp8_used) {
      auto fp8_opts = is_bf16_output ? opts.dtype(at::ScalarType::BFloat16) : opts.dtype(at::ScalarType::Half);
      out = at::empty({q.size(0), q.size(1), head_size_v_rounded}, fp8_opts);
    } else {
      out = at::empty({q.size(0), q.size(1), v_padded.size(-1)}, opts);
    }
zhangshao's avatar
zhangshao committed
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
  }

  auto softmax_lse =
      at::empty({num_heads * ngroups, total_q}, opts.dtype(at::kFloat));
  if (zero_tensors) {
    out.zero_();
    softmax_lse.fill_(-std::numeric_limits<float>::infinity());
  }

  Flash_fwd_params params;
  set_params_fprop(
      params, batch_size, max_seqlen_q, max_seqlen_k, seqlen_q_rounded,
      seqlen_k_rounded, num_heads, num_heads_k, head_size, head_size_rounded,
      head_size_v, head_size_v_rounded, q_padded, k_padded, v_padded, out,
      cu_seqlens_q.data_ptr(), seqused_k.data_ptr(),
      return_softmax ? nullptr /*p.data_ptr()*/ : nullptr, seqused_k.data_ptr(),
      softmax_lse.data_ptr(), p_dropout, softmax_scale, window_size_left,
      window_size_right, softcap, false,
      /*unpadded_lse*/ false,
      /*is_kvcache*/ false,
      /*is_seqlens_k_cumulative*/ seqused_k.size(0) == (batch_size + 1),
      layout /*layout*/, false /*is_flashmla*/, true /*is_prefix*/
  );
hly's avatar
hly committed
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
  params.s_aux_ptr = nullptr;
  params.s_aux_type = 0;
  if (s_aux_.has_value()) {
    auto s_aux = s_aux_.value();
    const auto expected_sink_dtype =
        fp8_used ? out.scalar_type() : at::ScalarType::Float;
    TORCH_CHECK(s_aux.scalar_type() == expected_sink_dtype,
                "Attention sink dtype must match prefix output dtype. Got ",
                s_aux.dtype(), ", expected ", expected_sink_dtype);
    CHECK_DEVICE(s_aux);
    CHECK_CONTIGUOUS(s_aux);
    CHECK_SHAPE(s_aux, original_num_heads);
    params.s_aux_ptr = s_aux.data_ptr();
    params.s_aux_type = get_attention_sink_type(s_aux.scalar_type());
  }
zhangshao's avatar
zhangshao committed
3927
3928
3929
3930
3931
3932
3933
3934
  params.total_q = total_q;
  params.block_table = block_table.data_ptr<int>();
  params.block_table_batch_stride = block_table.stride(0);
  params.k_batch_stride = k_padded.stride(0);
  params.v_batch_stride = v_padded.stride(0);
  params.page_block_size = page_block_size;
  params.seqused_k = reinterpret_cast<int *>(seqused_k.data_ptr());
  params.layout = 1; // only bshd (layout = 1) is supported yet
hly's avatar
hly committed
3935
  params.mtp = max_seqlen_q;
zhangshao's avatar
zhangshao committed
3936
  params.seqlen_q *= ngroups;
hly's avatar
hly committed
3937
3938
  params.ngroups = ngroups;
  params.seqlenq_ngroups_swapped = ngroups > 1;
zhangshao's avatar
zhangshao committed
3939

hly's avatar
hly committed
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
  if (fp8_used) {
    params.is_bf16 = out.dtype() == at::ScalarType::BFloat16;
    params.is_e4m3 = true;
    auto set_fp8_descale = [](const at::Tensor &descale, const char *name) {
      CHECK_DEVICE(descale);
      TORCH_CHECK(descale.dtype() == at::ScalarType::Float,
                  name, " must have dtype float32");
      TORCH_CHECK(descale.numel() >= 1,
                  name, " must contain at least one element");
      return reinterpret_cast<float*>(descale.data_ptr());
    };
    at::Tensor scales_q = scales_q_.value();
    params.q_descale_ptr = set_fp8_descale(scales_q, "q_descale");
    params.q_descale_batch_stride = 0;
    params.q_descale_head_stride = 0;
    at::Tensor scales_k = scales_k_.value();
    params.k_descale_ptr = set_fp8_descale(scales_k, "k_descale");
    params.k_descale_batch_stride = 0;
    params.k_descale_head_stride = 0;
    at::Tensor scales_v = scales_v_.value();
    params.v_descale_ptr = set_fp8_descale(scales_v, "v_descale");
    params.v_descale_batch_stride = 0;
    params.v_descale_head_stride = 0;
  }
  set_params_alibi(params, alibi_slopes_, batch_size, num_heads);
zhangshao's avatar
zhangshao committed
3965

hly's avatar
hly committed
3966
3967
  at::Tensor softmax_lseaccum;
  at::Tensor out_accum;
zhangshao's avatar
zhangshao committed
3968
3969
3970
  hipDeviceProp_t props;
  auto hipResult = hipGetDeviceProperties(&props, 0);
  params.cu_count = props.multiProcessorCount;
hly's avatar
hly committed
3971
3972
3973
3974
3975
3976
3977
  params.num_splits = 1;
  if (getArch() >= 938) {
    if (batch_size * params.h < params.cu_count / 2 and
      (head_size_value == 128 or head_size_value == 64)) {
      params.partition_size = PA_FIX_PARTITION;
      params.num_splits = 8;
      while (batch_size * params.h * params.num_splits < params.cu_count) {
zhangshao's avatar
zhangshao committed
3978
3979
3980
        params.num_splits *= 2;
      }
      params.num_splits = std::min(64, params.num_splits);
hly's avatar
hly committed
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
      const bool has_local_window =
          window_size_left >= 0 || window_size_right >= 0;
      if (has_local_window) {
        const int local_left =
            window_size_left < 0 ? max_seqlen_k : window_size_left;
        const int local_right =
            window_size_right < 0 ? max_seqlen_k : window_size_right;
        const int local_seqlen_k =
            std::min(max_seqlen_k, local_left + max_seqlen_q + local_right);
        if (local_seqlen_k <= 2048) {
          params.num_splits = 1;
        }
      }
      if (params.num_splits > 1) {
        // 申请空间
        softmax_lseaccum =
            at::empty({params.num_splits, num_heads * ngroups, total_q},
                      opts.dtype(at::kFloat));
zhangshao's avatar
zhangshao committed
3999
        out_accum = at::empty(
hly's avatar
hly committed
4000
4001
4002
4003
4004
4005
            {params.num_splits, out.size(0), out.size(1), out.size(2)},
            fp8_used ? out.options() : opts);
        params.softmax_lseaccum_ptr =
            reinterpret_cast<float *>(softmax_lseaccum.data_ptr());
        params.oaccum_ptr = out_accum.data_ptr();
      }
zhangshao's avatar
zhangshao committed
4006
4007
4008
    }
  }

hly's avatar
hly committed
4009
4010
4011
4012
4013
4014
4015
  const char *fa_debug = std::getenv("FA_DEBUG");
  if (fa_debug != nullptr) {
    if (std::strcmp(fa_debug, "1") == 0) {
      PRINT_PARAMS
    } else if (std::strcmp(fa_debug, "2") == 0) {
      PRINT_PARAMS_ONELINE
      auto temp_tensor = seqused_k.to(at::DeviceType::CPU).contiguous();
zhangshao's avatar
zhangshao committed
4016
4017
4018
      std::vector<int32_t> temp_vector(temp_tensor.data_ptr<int32_t>(),
                                       temp_tensor.data_ptr<int32_t>() +
                                           temp_tensor.numel());
hly's avatar
hly committed
4019
      printf("seqused_k: [");
zhangshao's avatar
zhangshao committed
4020
4021
4022
4023
4024
      for (const auto val : temp_vector) {
        printf("%d ", val);
      }
      printf("]\n");
    }
hly's avatar
hly committed
4025
    PRINT_QKV_INFO(q, k, v)
zhangshao's avatar
zhangshao committed
4026
4027
4028
  }

  const hipStream_t stream = at::hip::getCurrentHIPStreamMasqueradingAsCUDA();
hly's avatar
hly committed
4029
4030
  if (std::getenv("PA_EMPTY") == nullptr) {
    run_mha_fwd_kvcache(params, stream);
zhangshao's avatar
zhangshao committed
4031
4032
  }

hly's avatar
hly committed
4033
4034
4035
4036
4037
4038
  at::Tensor out_padded = out;
  if (head_size_value % 32 != 0) {
    out = out.index(
        {"...", at::indexing::Slice(at::indexing::None, head_size_value)});
    if (out_.has_value()) {
      out_.value().copy_(out);
zhangshao's avatar
zhangshao committed
4039
4040
4041
    }
  }

hly's avatar
hly committed
4042
4043
4044
  if (ngroups > 1) {
    out = out.view({total_q, num_heads * ngroups, -1});
    if (output_allocated_outside) { out_.value().copy_(out); }
zhangshao's avatar
zhangshao committed
4045
  }
hly's avatar
hly committed
4046
4047
4048

  if (return_softmax) return {out, softmax_lse};
  else return {out};
zhangshao's avatar
zhangshao committed
4049
#else
hly's avatar
hly committed
4050
    return {};
zhangshao's avatar
zhangshao committed
4051
4052
4053
#endif
}

hly's avatar
hly committed
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064


std::vector<at::Tensor> fwd_kvcache_mla_decoding(
    at::Tensor &q,
    const at::Tensor &kcache,
    c10::optional<const at::Tensor> &vcache,
    const int head_dim_v,
    const at::Tensor &cache_seqlens,
    const at::Tensor &block_table,
    const float softmax_scale,
    bool is_causal,
zhangshao's avatar
zhangshao committed
4065
4066
    const c10::optional<const at::Tensor> &tile_scheduler_metadata,
    const c10::optional<const at::Tensor> &num_splits,
hly's avatar
hly committed
4067
4068
4069
    c10::optional<at::Tensor> &out_,
    int max_seqlen_k
) {
zhangshao's avatar
zhangshao committed
4070
#if defined(BUILD_FLASHMLA)
hly's avatar
hly committed
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
    const at::cuda::HIPGuardMasqueradingAsCUDA device_guard(q.device().index());
    // OptionalHIPStreamGuardMasqueradingAsCUDA ?

    auto q_dtype = q.dtype();
    TORCH_CHECK(q_dtype == at::ScalarType::Half || q_dtype == at::ScalarType::BFloat16, "FlashMLA only support fp16 and bf16 data type");
    TORCH_CHECK(kcache.dtype() == q_dtype, "Query and key must have the same dtype");
    CHECK_DEVICE(q); CHECK_DEVICE(kcache);
    TORCH_CHECK(q.stride(-1) == 1, "Input tensor must have contiguous last dimension");
    TORCH_CHECK(kcache.stride(-1) == 1, "Input tensor must have contiguous last dimension");
    CHECK_DEVICE(block_table);
    TORCH_CHECK(block_table.dtype() == at::ScalarType::Int, "block_table must have dtype torch.int32");
    TORCH_CHECK(block_table.stride(-1) == 1, "block_table must have contiguous last dimension");

    // decide layout ----> 0: bhsd, 1: bshd
    const int layout = (kcache.size(1) % 32 == 0/*page block size*/) and (kcache.size(2) == 1/*kvhead = 1, MQA*/);

    const auto sizes       = q.sizes();
    const int o_batch_size = sizes[0]; // fake batch size, may be padded in sglang, and thus o_batch_size >= batch_size
    int       num_heads    = layout == 1 ? sizes[2]: sizes[1];
    int       seqlen_q     = layout == 1 ? sizes[1]: sizes[2];
    const int head_size_og = sizes[3];
    const int head_dim_qk  = q.size(3);
    const int batch_size   = block_table.size(0); // true batch size
    const int max_num_blocks_per_seq = block_table.size(1);
    const int num_blocks   = kcache.size(0);
    const int page_block_size = layout == 1 ? kcache.size(1): kcache.size(2);
    const int num_heads_k  = layout == 1 ? kcache.size(2): kcache.size(1);
    const int mtp = seqlen_q;
    TORCH_CHECK(batch_size > 0 and o_batch_size > 0, "batch size must be positive");
    TORCH_CHECK(o_batch_size >= batch_size, "batch size of query must be larger than batch_size of query");
    // TORCH_CHECK(block_table.size(0) == batch_size, "For FlashMLA, batch size of block table is not compatible with query! Please check shape!");
    TORCH_CHECK(head_dim_qk == 576, "FlashMLA only supports QK headdim 576");
    TORCH_CHECK(head_dim_v == 512, "FlashMLA only supports V headdim 512");
    TORCH_CHECK(num_heads % num_heads_k == 0, "Number of heads in key/value must divide number of heads in query");
    TORCH_CHECK(mtp <= 128, "FlashMLA only support mtp <= 128 yet");
    TORCH_CHECK(not (num_heads == 128 and mtp > 1), "FlashMLA decoding doesn't support mtp when qheads = 128, not supported yet");

    // causal=true is the same as causal=false in this case
    if (mtp == 1) { is_causal = false; } else { is_causal = true; }

    // for ours flashmla, mtp and regroup are limited
    const bool use_tile_16x32 = std::getenv("MLA_USE_TILE32X32") == nullptr;
    const int MTP_REGROUP_COUNT = use_tile_16x32 ? 4: 8;
    const int MAX_MTP_ALLOWED = use_tile_16x32 ? 16 / MTP_REGROUP_COUNT: 32 / MTP_REGROUP_COUNT;

    // Faster to transpose q from (b, 1, (nheads_kv ngroups), d) to (b, ngroups, nheads_kv, d) in this case
    const int ngroups = num_heads / num_heads_k;
    const char* mla_regroup_control = std::getenv("MLA_REGROUP");
    const int mla_regroup = mla_regroup_control ? std::atoi(mla_regroup_control): 0;
    const int seqlenq_ngroups_swapped = (mtp == 1 or (mtp <= MAX_MTP_ALLOWED and num_heads <= 16)) and num_heads > num_heads_k and (mla_regroup == 0/*默认不指定 regroup*/ or (mla_regroup > 1 and mla_regroup <= num_heads/*指定的 regroup 在合理范围内*/ and (num_heads % mla_regroup == 0/*可以做 regroup*/)));
    if (seqlenq_ngroups_swapped) {
        // default reuse strategy
        if (mla_regroup == 0) {
            // limited seqlen_q_regroup due to 16x576 lds load limit
            int regroup_discount = std::ceil(ngroups * 1.f / 16);
            if (mtp > 1) {
                seqlen_q  = mtp * MTP_REGROUP_COUNT;
                num_heads = int(num_heads / MTP_REGROUP_COUNT);
            } else {
                seqlen_q  = int(ngroups / regroup_discount);
                num_heads = int(num_heads_k * regroup_discount);
            }
            if (layout == 0)      q = q.view({o_batch_size, num_heads, seqlen_q, head_dim_qk});
            else if (layout == 1) q = q.view({o_batch_size, seqlen_q, num_heads, head_dim_qk});
        } else { // use self-assigned regroup strategy
            seqlen_q  = mla_regroup;
            num_heads = num_heads_k * int(ngroups / mla_regroup);
            if (layout == 0)      q = q.view({o_batch_size, num_heads, mla_regroup, head_dim_qk});
            else if (layout == 1) q = q.view({o_batch_size, mla_regroup, num_heads, head_dim_qk});
        }
    }
    TORCH_CHECK(seqlen_q <= 128, "FlashMLA only support seqlen_q * hq / hk <= 128 yet");
    TORCH_CHECK(int64_t(o_batch_size * num_heads * seqlen_q * head_dim_qk) < /*2^31*/int64_t(2147483648), "The data amount of q must be smaller than the representation range of int");
zhangshao's avatar
zhangshao committed
4144

hly's avatar
hly committed
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
    // Allocate and check output
    auto opts = q.options();
    at::Tensor out;
    bool output_allocated_outside = out_.has_value();
    if (output_allocated_outside) {
        out = out_.value();
        TORCH_CHECK(out.dtype() == q_dtype, "Output must have the same dtype as inputs");
        CHECK_DEVICE(out);
        TORCH_CHECK(out.stride(-1) == 1, "Output tensor must have contiguous last dimension");
        // CHECK_SHAPE(out, batch_size, seqlen_q, num_heads, head_dim_v);
        out = out.view({q.size(0), q.size(1), q.size(2), head_dim_v});
    } else {
        out = at::empty({q.size(0), q.size(1), q.size(2), head_dim_v}, opts);
    }
zhangshao's avatar
zhangshao committed
4159

hly's avatar
hly committed
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
    // Acquire and check cache_seqlens length information
    TORCH_CHECK(cache_seqlens.dtype() == at::ScalarType::Int, "seqlens_k must have dtype int32");
    CHECK_DEVICE(cache_seqlens);
    CHECK_CONTIGUOUS(cache_seqlens);
    auto cache_seqlens_ptr = cache_seqlens.data_ptr();

    Flash_fwd_mla_params params;
    // Reset the parameters
    memset(&params, 0, sizeof(params));
    // Set the status.
    params.layout = layout;
    params.mtp = mtp;
    params.is_bf16 = q.dtype() == at::ScalarType::BFloat16;
    params.is_e4m3 = q.dtype() == at::ScalarType::Float8_e4m3fn;
    params.seqlenq_ngroups_swapped = seqlenq_ngroups_swapped;
    params.is_seqlens_k_cumulative = cache_seqlens.size(0) == (batch_size + 1);
    // Set the pointers.
    params.q_ptr = q.data_ptr();
    params.k_ptr = kcache.data_ptr();
    params.v_ptr = kcache.data_ptr();
    params.o_ptr = out.data_ptr();
    params.cu_seqlens_q = static_cast<int *>(cache_seqlens_ptr);
    params.cu_seqlens_k = static_cast<int *>(cache_seqlens_ptr);
    // Set the strides.
    params.q_batch_stride = q.stride(0);
    params.o_batch_stride = out.stride(0);
    params.q_head_stride  = (layout == 1) ? q.stride(2): q.stride(1);
    params.k_head_stride  = (layout == 1) ? kcache.stride(2): kcache.stride(1);
    params.v_head_stride  = params.k_head_stride;
    params.o_head_stride  = (layout == 1) ? out.stride(2): out.stride(1);
    params.q_row_stride   = (layout == 1) ? q.stride(1): q.stride(2);
    params.k_row_stride   = (layout == 1) ? kcache.stride(1): kcache.stride(2);
    params.v_row_stride   = params.k_row_stride;
    params.o_row_stride   = (layout == 1) ? out.stride(1): out.stride(2);
    // Set the dimensions etc.
    params.b   = batch_size;
    params.h   = num_heads;
    params.h_k = num_heads_k;
    params.d   = head_dim_qk;
    params.d_v = head_dim_v;
    params.h_h_k_ratio = num_heads / num_heads_k;
    params.seqlen_q = seqlen_q;
    params.seqlen_k = max_seqlen_k;
    params.scale_softmax = softmax_scale;
    params.scale_softmax_log2 = softmax_scale * M_LOG2E;
    // Set the block table.
    params.block_table     = block_table.data_ptr<int>();
    params.page_block_size = page_block_size;
    params.block_table_batch_stride = block_table.stride(0);
    params.k_batch_stride  = kcache.stride(0);
    params.v_batch_stride  = kcache.stride(0);

    // get cu_count
    hipDeviceProp_t props;
    auto hipResult  = hipGetDeviceProperties(&props, 0);
    params.cu_count = props.multiProcessorCount;

    at::Tensor out_accum, softmax_lse_accum;
    // MTP == 1, 而且没有禁止 splitkv 的情况下, 对 seqkv 进行划分
    bool env_allow_splitkv = bool(std::getenv("MLA_NO_SPLITKV") == nullptr);
    bool allow_splitkv = max_seqlen_k >= 128 and mtp <= 128 and env_allow_splitkv;
    if (allow_splitkv) {
        int partition_size = 0;
        const char* partition_size_env = std::getenv("MLA_PARTITION_SIZE");
        const int partition_size_assign = partition_size_env ? std::atoi(partition_size_env): 0;
        // 如果没有指定 partition size, 启发式决定切分策略
        if (partition_size_assign == 0) {
            // 如果初步能划分的 block 数量对应的利用率不高
            constexpr int device_cu = 100;
            const int threshold     = device_cu * 0.8;
            constexpr int large_seq = 4096;
            // 如果目前能发的 TG 数量比较少而且最大的 seqkv 不是很短, 根据 batch 来决定切多大
            if (batch_size * num_heads * mtp < threshold and max_seqlen_k >= 512 and max_seqlen_k < large_seq) {
                if (batch_size < 8)       partition_size = 128;
                else if (batch_size < 16) partition_size = 256;
                else if (batch_size < 32) partition_size = 512;
                else if (batch_size < 64) partition_size = 1024;
            } else if (max_seqlen_k >= large_seq) { // 或者 seqkv 足够长, 直接根据 seqkv 来决定切多大
                partition_size = 1024;
                // 如果按照上述划分之后, 利用率还不是很高, partition size 继续减半
                int splits = std::ceil(max_seqlen_k / partition_size);
                while (batch_size * num_heads * mtp * splits < threshold) {
                    // 目前支持的最小 partition size 是 128
                    if (partition_size < 256) break;
                    partition_size = int(partition_size / 2);
                    splits *= 2;
                }
            }
        } else if (partition_size_assign >= 128 and partition_size_assign % 128 == 0 and partition_size_assign <= max_seqlen_k) {
            // 指定的 partition_size 满足划分的需求, 目前只支持 128 的倍数, 则可以开始划分
            partition_size = partition_size_assign;
        }
        int num_splits = std::ceil(max_seqlen_k * 1.f / partition_size);
        // 如果划分成功
        if (partition_size > 0 and partition_size >= 128/*partition_size 本身合理*/ and num_splits <= 1024/*最多只能支持 1024 个划分*/) {
            // 传递给 kernel args
            params.partition_size = partition_size;
            params.num_splits     = num_splits;
            // 申请 scores_max/sum 和 out_accum 的空间
            auto raw_memory = at::empty({1, params.num_splits, o_batch_size, num_heads, seqlen_q}, opts.dtype(at::kFloat));
            softmax_lse_accum = raw_memory.index({0});
            if (layout == 0) out_accum  = at::empty({params.num_splits, o_batch_size, num_heads, seqlen_q, head_dim_v}, opts.dtype(q_dtype));
            else if (layout == 1) out_accum  = at::empty({params.num_splits, o_batch_size, seqlen_q, num_heads, head_dim_v}, opts.dtype(q_dtype));
            params.softmax_lse_ptr = reinterpret_cast<float*>(softmax_lse_accum.data_ptr());
            params.oaccum_ptr      = out_accum.data_ptr();
        }
    } else if (env_allow_splitkv) { // 开启 cuda graph 可走这里
        const int num_splits_assigned = 8;
        if (num_splits_assigned > 1 and batch_size <= 32) {
            // 传递给 kernel args
            params.partition_size = MLA_FIX_PARTITION;
            params.num_splits     = num_splits_assigned;
            while (o_batch_size * params.num_splits < 64) {
                params.num_splits *= 2;
            }
            params.num_splits = o_batch_size == 1 ? 32: params.num_splits; // for tiny batch size 1, splitkv reduce 64 may be the bottleneck
            params.num_splits = std::min(64, params.num_splits);
            // 申请 scores_max/sum 和 out_accum 的空间
            auto raw_memory = at::empty({1, params.num_splits, o_batch_size, num_heads, seqlen_q}, opts.dtype(at::kFloat));
            softmax_lse_accum = raw_memory.index({0});
            if (layout == 0) out_accum  = at::empty({params.num_splits, o_batch_size, num_heads, seqlen_q, head_dim_v}, opts.dtype(q_dtype));
            else if (layout == 1) out_accum  = at::empty({params.num_splits, o_batch_size, seqlen_q, num_heads, head_dim_v}, opts.dtype(q_dtype));
            params.softmax_lse_ptr = reinterpret_cast<float*>(softmax_lse_accum.data_ptr());
            params.oaccum_ptr      = out_accum.data_ptr();
        }
    }
zhangshao's avatar
zhangshao committed
4286

hly's avatar
hly committed
4287
4288
4289
4290
    // decide accumulation dtype when splitkv
    if (params.partition_size > 0 and params.num_splits > 1) {
        params.splitkv_use_fp32_as_accum = out_accum.dtype() == at::ScalarType::Float;
    }
zhangshao's avatar
zhangshao committed
4291

hly's avatar
hly committed
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
    const char* env_info = std::getenv("FA_DEBUG");
    if (env_info != nullptr) {
        PRINT_MLA_PARAMS
        PRINT_QKV_INFO(q, kcache, kcache);
        PRINT_TENSOR_INFO(out, "out");
        std::cout << "block_table: " << block_table.sizes() << std::endl;
        if (std::strcmp(env_info, "2") == 0) {
            auto temp_tensor = cache_seqlens.to(at::DeviceType::CPU).contiguous(); // to cpu op may interrupt cudagraph
            std::vector<int32_t> temp_vector(temp_tensor.data_ptr<int32_t>(), temp_tensor.data_ptr<int32_t>() + temp_tensor.numel());
            printf("cache_seqlens: ["); for (const auto val: temp_vector) { printf("%d ", val); } printf("]\n");
        }
    }
zhangshao's avatar
zhangshao committed
4304

hly's avatar
hly committed
4305
4306
4307
4308
4309
4310
4311
4312
    const hipStream_t stream = at::hip::getCurrentHIPStreamMasqueradingAsCUDA();
    if (max_seqlen_k > 0 and std::getenv("MLA_DECODE_EMPTY") == nullptr) {
        FP16_SWITCH(!params.is_bf16, [&] {
            run_mla_fwd_splitkv_dispatch<elem_type, 576, 512>(params, stream);
        });
    } else {
        out.zero_();
    }
zhangshao's avatar
zhangshao committed
4313

hly's avatar
hly committed
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
    if (seqlenq_ngroups_swapped) {
        if (layout == 0) {
            if (mtp > 1) {
                out = out.view({o_batch_size, num_heads * MTP_REGROUP_COUNT, mtp, head_dim_v});
                if (params.partition_size > 0) out_accum = out_accum.view({params.num_splits, o_batch_size, num_heads * MTP_REGROUP_COUNT, mtp, head_dim_v});
            } else {
                out = out.view({o_batch_size, num_heads_k * ngroups, mtp, head_dim_v});
                if (params.partition_size > 0) out_accum = out_accum.view({params.num_splits, o_batch_size, num_heads_k * ngroups, mtp, head_dim_v});
            }
        } else if (layout == 1) {
            if (mtp > 1) {
                out = out.view({o_batch_size, mtp, num_heads * MTP_REGROUP_COUNT, head_dim_v});
                if (params.partition_size > 0) out_accum = out_accum.view({params.num_splits, o_batch_size, mtp, num_heads * MTP_REGROUP_COUNT, head_dim_v});
            } else {
                out = out.view({o_batch_size, mtp, num_heads_k * ngroups, head_dim_v}); // kheads 为 1, 所以不用加一步 contiguous()
                if (params.partition_size > 0) out_accum = out_accum.view({params.num_splits, o_batch_size, mtp, num_heads_k * ngroups, head_dim_v});
            }
        }
    }

    if (output_allocated_outside) {
        return {};
    } else {
        return {out, out_accum, softmax_lse_accum};
    }
zhangshao's avatar
zhangshao committed
4339
#else
hly's avatar
hly committed
4340
    return {};
zhangshao's avatar
zhangshao committed
4341
4342
4343
4344
#endif
}


hly's avatar
hly committed
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354

std::vector<at::Tensor> fwd_kvcache_mla_dataparallel(
    at::Tensor &q_all,
    at::Tensor &kvcache,
    c10::optional<const at::Tensor> &vcache_,
    const int headdim_v,
    const at::Tensor &cache_seqlens,
    const at::Tensor &page_table,
    const float softmax_scale,
    const bool is_causal,
zhangshao's avatar
zhangshao committed
4355
4356
    const c10::optional<const at::Tensor> &tile_scheduler_metadata,
    const c10::optional<const at::Tensor> &num_splits,
hly's avatar
hly committed
4357
4358
4359
    c10::optional<at::Tensor> &out_,
    int max_seqlen_k
) {
zhangshao's avatar
zhangshao committed
4360
#if defined(BUILD_FLASHMLA)
hly's avatar
hly committed
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
    // 类型检查
    TORCH_CHECK(q_all.dtype() == at::ScalarType::Half || q_all.dtype() == at::ScalarType::BFloat16, "Fwd_kvcache_mla only support fp16 and bf16 data type for q");
    TORCH_CHECK(kvcache.dtype() == at::ScalarType::Half || kvcache.dtype() == at::ScalarType::BFloat16, "Fwd_kvcache_mla mla only support fp16 and bf16 data type for kcache");
    TORCH_CHECK(cache_seqlens.dtype() == at::ScalarType::Int, "Fwd_kvcache_mla only support int32_t data type for cache_seqlens");
    TORCH_CHECK(page_table.dtype() == at::ScalarType::Int, "Fwd_kvcache_mla only support int32_t data type for page_table");
    // device 检查
    CHECK_DEVICE(q_all); CHECK_DEVICE(kvcache); CHECK_DEVICE(page_table); CHECK_DEVICE(cache_seqlens);
    // 连续性检查
    CHECK_CONTIGUOUS(page_table); CHECK_CONTIGUOUS(cache_seqlens);
    // 张量 shape 检查, 是否是 3/4 维这种
    TORCH_CHECK(q_all.dim() == 4, "In fwd_kvcache_mla, q must be 4-dimension tensor");
    TORCH_CHECK(kvcache.dim() == 4, "In fwd_kvcache_mla, kvcache must be 4-dimension tensor");
    TORCH_CHECK(page_table.dim() == 2, "In fwd_kvcache_mla, page_table must be 2-dimension tensor");
    // 获取基本信息
    const auto q_size       = q_all.sizes();
    const int o_batch_size  = q_size[0];
    const int headdim_qk    = q_size[3];
    const int headdim_rope  = headdim_qk - headdim_v;
    const int batch_size    = page_table.size(0);
    const int num_heads_ori = q_size[2];
    const int num_heads_k   = kvcache.size(2);
    const int page_block_size = kvcache.size(1);
    TORCH_CHECK(batch_size > 0 and o_batch_size > 0, "batch size must be positive");
    TORCH_CHECK(o_batch_size >= batch_size, "batch size of query must be larger than batch_size of query");
    // TORCH_CHECK(page_table.size(0) == q_size[0], "In fwd_kvcache_mla, batch_size of page_table must be compatible with query! Please check shape!");
    // GQA regroup 优化
    TORCH_CHECK(num_heads_ori % num_heads_k == 0, "In fwd_kvcache_mla, qheads must be multiple of kvheads! Please check layout and shape!");
    const int seqlen_q_ori = q_size[1];
    const int ngroups = num_heads_ori / num_heads_k;
    const int seqlen_q = seqlen_q_ori * ngroups;
    const int num_heads = num_heads_k;
    q_all = q_all.view({o_batch_size, seqlen_q, num_heads_k, headdim_qk});
    // 沿着 headdim 切分 q
    const auto q = q_all.narrow(-1, headdim_v, headdim_rope);
    const auto qv = q_all.narrow(-1, 0, headdim_v);
    // 沿着 headdim 切分 k, v
    const auto kcache = kvcache.narrow(-1, headdim_v, headdim_rope);
    const auto vcache = kvcache.narrow(-1, 0, headdim_v);
    const auto kcache_size = kcache.sizes();
    const auto vcache_size = vcache.sizes();
    // 检查 size 是否符合要求
    TORCH_CHECK(headdim_v == 512, "In fwd_kvcache_mla, headdim_v must be 512");
    TORCH_CHECK(headdim_rope == 64, "In fwd_kvcache_mla, headdim_rope must be 64");
    TORCH_CHECK(headdim_qk == 576, "In fwd_kvcache_mla, headdim_qk must be 576");
    TORCH_CHECK(page_block_size == 128, "In fwd_kvcache_mla, page_block_size must be 128")
    // 检查平台
    hipDeviceProp_t props;
    auto hipResult = hipGetDeviceProperties(&props, 0);
    std::string gcn_arch_name(props.gcnArchName);
    const int gcn_arch = runtime_gfx_arch_id(gcn_arch_name);
    TORCH_CHECK(is_supported_hg_mla_arch(gcn_arch_name, gcn_arch), "In fwd_kvcache_mla, only gfx92a or arch id >= gfx936 is supported!");
    // 准备输出变量
    auto opts = q.options();
    at::Tensor out, softmax_lse, scores_max, scores_sum;
    out = at::empty({q.size(0), q.size(1), q.size(2), headdim_v}, opts);
    if (true/*return_softmax_lse*/) { // extra op for return_softmax_lse may lead to 2.3% performance drop, slightly
        auto scores_memory = at::empty({3, o_batch_size, num_heads, seqlen_q}, opts.dtype(at::kFloat));
        scores_max = scores_memory.index({0});
        scores_sum = scores_memory.index({1});
        softmax_lse = scores_memory.index({2});
    }
zhangshao's avatar
zhangshao committed
4422

hly's avatar
hly committed
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
    // NMZ走MLS FlashMLA
    bool IS_DP_MLA_MLS = false;
    if (gcn_arch >= 938 and std::getenv("MLA_DP_DECODE_NO_MLS") == nullptr and o_batch_size>= 16) IS_DP_MLA_MLS = true;

    // 准备 kernel 需要的参数列表
    Flash_fwd_mla_params params;
    memset(&params, 0, sizeof(params));
    params.layout           = 1;
    params.b                = batch_size;
    params.h                = num_heads;
    params.h_k              = num_heads_k;
    params.h_h_k_ratio      = params.h / params.h_k;
    params.mtp              = seqlen_q_ori;
    params.d                = headdim_qk;
    params.d_v              = headdim_v;
    params.scale_softmax    = softmax_scale;
    params.scale_softmax_log2 = softmax_scale * M_LOG2E;
    params.cu_seqlens_q     = nullptr; // <int32_t*>(cu_seqlens_q.data_ptr());
    params.cu_seqlens_k     = reinterpret_cast<int32_t*>(cache_seqlens.data_ptr());
    params.q_ptr            = IS_DP_MLA_MLS ? q_all.data_ptr() : q.data_ptr();
    params.qv_ptr           = IS_DP_MLA_MLS ? nullptr : qv.data_ptr();
    params.k_ptr            = IS_DP_MLA_MLS ? kvcache.data_ptr() : kcache.data_ptr();
    params.v_ptr            = IS_DP_MLA_MLS ? kvcache.data_ptr() : vcache.data_ptr();
    params.o_ptr            = out.data_ptr();
    params.softmax_lse_ptr  = softmax_lse.data_ptr<float>();
    params.scores_max_ptr   = scores_max.data_ptr<float>();
    params.scores_sum_ptr   = scores_sum.data_ptr<float>();
    params.block_table      = reinterpret_cast<int32_t*>(page_table.data_ptr());
    params.block_table_batch_stride = page_table.stride(0);
    params.page_block_size  = page_block_size;
    params.is_causal        = is_causal;
    params.q_batch_stride   = IS_DP_MLA_MLS ? q_all.stride(0) : q.stride(0);
    params.q_row_stride     = IS_DP_MLA_MLS ? q_all.stride(1) : q.stride(1);
    params.q_head_stride    = IS_DP_MLA_MLS ? q_all.stride(2) : q.stride(2);
    params.qv_batch_stride  = qv.stride(0);
    params.qv_row_stride    = qv.stride(1);
    params.qv_head_stride   = qv.stride(2);
    params.k_batch_stride   = IS_DP_MLA_MLS ? kvcache.stride(0) : kcache.stride(0);
    params.k_row_stride     = IS_DP_MLA_MLS ? kvcache.stride(1) : kcache.stride(1);
    params.k_head_stride    = IS_DP_MLA_MLS ? kvcache.stride(2) : kcache.stride(2);
    params.v_batch_stride   = IS_DP_MLA_MLS ? kvcache.stride(0) : vcache.stride(0);
    params.v_row_stride     = IS_DP_MLA_MLS ? kvcache.stride(1) : vcache.stride(1);
    params.v_head_stride    = IS_DP_MLA_MLS ? kvcache.stride(2) : vcache.stride(2);
    params.o_batch_stride   = out.stride(0);
    params.o_row_stride     = out.stride(1);
    params.o_head_stride    = out.stride(2);
    params.seqlen_q         = seqlen_q;
    params.ngroups          = ngroups;
    params.is_bf16          = q.dtype() == at::ScalarType::BFloat16;
    params.cu_count         = props.multiProcessorCount;
    params.seqlenq_ngroups_swapped = true;

    // DEBUG
    const char* fa_debug = std::getenv("FA_DEBUG");
    if (fa_debug != nullptr) {
        PRINT_MLA_PARAMS
        if (strcmp(fa_debug, "2") == 0) { // print operations listed below may interrupt cudagraph, and thus only print tensors util FA_DEBUG=2
            PRINT_TENSOR(cache_seqlens, "cache_seqlens")
        }
        PRINT_TENSOR_INFO(q, "q")
        PRINT_TENSOR_INFO(kcache, "kcache")
        PRINT_TENSOR_INFO(vcache, "vcache")
        PRINT_TENSOR_INFO(qv, "qv")
    }
zhangshao's avatar
zhangshao committed
4487

hly's avatar
hly committed
4488
4489
4490
4491
4492
4493
4494
4495
4496
    // 准备启动 kernel
    const hipStream_t stream = at::hip::getCurrentHIPStreamMasqueradingAsCUDA();
    if (std::getenv("MLA_DECODE_EMPTY") == nullptr) {
        FP16_SWITCH(!params.is_bf16, [&] {
            run_mla_fwd_dispatch<elem_type, 576, 512>(params, stream);
        });
    } else {
        out.zero_();
    }
zhangshao's avatar
zhangshao committed
4497

hly's avatar
hly committed
4498
4499
4500
4501
4502
4503
    // GQA 优化重排
    out = out.view({o_batch_size, seqlen_q_ori, ngroups * num_heads_k, headdim_v});
    if (params.mtp == 1) {
        softmax_lse = softmax_lse.view({o_batch_size, ngroups * num_heads_k, seqlen_q_ori});
    } else {
        softmax_lse = softmax_lse.view({o_batch_size, num_heads_k, seqlen_q_ori, ngroups}).transpose(-1, -2).contiguous().view({o_batch_size, ngroups * num_heads_k, seqlen_q_ori});
zhangshao's avatar
zhangshao committed
4504
4505
    }

hly's avatar
hly committed
4506
4507
4508
4509
4510
    return {out, softmax_lse, scores_max, scores_sum};
#else
    return {};
#endif
}
zhangshao's avatar
zhangshao committed
4511

hly's avatar
hly committed
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629

std::vector<at::Tensor> hg_fwd_kvcache_mla(
    at::Tensor &q_all,
    at::Tensor &kvcache,
    c10::optional<const at::Tensor> &vcache_,
    const int headdim_v,
    const at::Tensor &seqlens_k,
    const at::Tensor &block_table,
    const float softmax_scale,
    const bool is_causal,
    const c10::optional<const at::Tensor> &tile_scheduler_metadata,
    const c10::optional<const at::Tensor> &num_splits,
    c10::optional<at::Tensor> &out_,
    int max_seqlen_k
) {
    int qheads = max(q_all.size(1), q_all.size(2));
    if (qheads == 128)
        return fwd_kvcache_mla_dataparallel(q_all, kvcache, vcache_, headdim_v, seqlens_k, block_table, softmax_scale, is_causal, tile_scheduler_metadata, num_splits, out_, max_seqlen_k);
    return fwd_kvcache_mla_decoding(q_all, kvcache, vcache_, headdim_v, seqlens_k, block_table, softmax_scale, is_causal, tile_scheduler_metadata, num_splits, out_, max_seqlen_k);
}




std::vector<at::Tensor> fwd_kvcache_mla_decoding_fp8(
    at::Tensor &q,
    const at::Tensor &kcache,
    c10::optional<const at::Tensor> &vcache,
    const int head_dim_v,
    const at::Tensor &cache_seqlens,
    const at::Tensor &block_table,
    const float softmax_scale,
    bool is_causal,
    const c10::optional<const at::Tensor> &tile_scheduler_metadata,
    const c10::optional<const at::Tensor> &num_splits,
    c10::optional<at::Tensor> &out_,
    int max_seqlen_k,
    const at::Tensor& descale_q,
    const at::Tensor& descale_k
) {
#if defined(BUILD_FLASHMLA)
    const at::cuda::HIPGuardMasqueradingAsCUDA device_guard(q.device().index());

    auto q_dtype = q.dtype();
    TORCH_CHECK(q_dtype == at::ScalarType::Float8_e4m3fn, "FlashMLA_FP8 only support fp8_e4m3 data type");
    TORCH_CHECK(kcache.dtype() == q_dtype, "Query and key must have the same dtype");
    CHECK_DEVICE(q); CHECK_DEVICE(kcache);
    TORCH_CHECK(q.stride(-1) == 1, "Input tensor must have contiguous last dimension");
    TORCH_CHECK(kcache.stride(-1) == 1, "Input tensor must have contiguous last dimension");
    CHECK_DEVICE(block_table);
    TORCH_CHECK(block_table.dtype() == at::ScalarType::Int, "block_table must have dtype torch.int32");
    TORCH_CHECK(block_table.stride(-1) == 1, "block_table must have contiguous last dimension");
    CHECK_DEVICE(descale_q);
    TORCH_CHECK(descale_q.dtype() == at::ScalarType::Float, "descale_q must have dtype torch.float32");
    TORCH_CHECK(descale_q.is_contiguous(), "descale_q must be contiguous");
    CHECK_SHAPE(descale_q, 1);
    CHECK_DEVICE(descale_k);
    TORCH_CHECK(descale_k.dtype() == at::ScalarType::Float, "descale_k must have dtype torch.float32");
    TORCH_CHECK(descale_k.is_contiguous(), "descale_k must be contiguous");
    CHECK_SHAPE(descale_k, 1);

    // decide layout ----> 0: bhsd, 1: bshd
    const int layout = (kcache.size(1) % 32 == 0/*page block size*/) and (kcache.size(2) == 1/*kvhead = 1, MQA*/);

    const auto sizes       = q.sizes();
    const int o_batch_size = sizes[0]; // fake batch size, may be padded in sglang, and thus o_batch_size >= batch_size
    int       num_heads    = layout == 1 ? sizes[2]: sizes[1];
    int       seqlen_q     = layout == 1 ? sizes[1]: sizes[2];
    const int head_size_og = sizes[3];
    const int head_dim_qk  = q.size(3);
    const int batch_size   = block_table.size(0); // true batch size
    const int max_num_blocks_per_seq = block_table.size(1);
    const int num_blocks   = kcache.size(0);
    const int page_block_size = layout == 1 ? kcache.size(1): kcache.size(2);
    const int num_heads_k  = layout == 1 ? kcache.size(2): kcache.size(1);
    const int mtp = seqlen_q;
    const bool is_prefill = bool(mtp > 16); // seqlen_q > 16, usage for prefill
    TORCH_CHECK(batch_size > 0 and o_batch_size > 0, "batch size must be positive");
    TORCH_CHECK(o_batch_size >= batch_size, "batch size of query must be larger than batch_size of query");
    // TORCH_CHECK(block_table.size(0) == batch_size, "For FlashMLA, batch size of block table is not compatible with query! Please check shape!");
    TORCH_CHECK(head_dim_qk == 576, "FlashMLA only supports QK headdim 576");
    TORCH_CHECK(head_dim_v == 512, "FlashMLA only supports V headdim 512");
    TORCH_CHECK(num_heads % num_heads_k == 0, "Number of heads in key/value must divide number of heads in query");
    TORCH_CHECK(not (num_heads == 128 and mtp > 1), "FlashMLA decoding doesn't support mtp when qheads = 128, not supported yet");

    // causal=true is the same as causal=false in this case
    if (mtp == 1) { is_causal = false; } else { is_causal = true; }

    // for ours flashmla, mtp and regroup are limited
    const bool use_tile_16x32 = std::getenv("MLA_USE_TILE32X32") == nullptr;
    const int MTP_REGROUP_COUNT = use_tile_16x32 ? 4: 8;
    const int MAX_MTP_ALLOWED = use_tile_16x32 ? 16 / MTP_REGROUP_COUNT: 32 / MTP_REGROUP_COUNT;

    // Faster to transpose q from (b, 1, (nheads_kv ngroups), d) to (b, ngroups, nheads_kv, d) in this case
    const int ngroups = num_heads / num_heads_k;
    const char* mla_regroup_control = std::getenv("MLA_REGROUP");
    const int mla_regroup = mla_regroup_control ? std::atoi(mla_regroup_control): 0;
    const int seqlenq_ngroups_swapped = (mtp == 1 or (mtp <= MAX_MTP_ALLOWED and num_heads <= 16)) and num_heads > num_heads_k and (mla_regroup == 0/*默认不指定 regroup*/ or (mla_regroup > 1 and mla_regroup <= num_heads/*指定的 regroup 在合理范围内*/ and (num_heads % mla_regroup == 0/*可以做 regroup*/)));
    if (seqlenq_ngroups_swapped) {
        // default reuse strategy
        if (mla_regroup == 0) {
            // limited seqlen_q_regroup due to 16x576 lds load limit
            int regroup_discount = std::ceil(ngroups * 1.f / 16);
            if (mtp > 1) {
                seqlen_q  = mtp * MTP_REGROUP_COUNT;
                num_heads = int(num_heads / MTP_REGROUP_COUNT);
            } else {
                seqlen_q  = int(ngroups / regroup_discount);
                num_heads = int(num_heads_k * regroup_discount);
            }
            if (layout == 0)      q = q.view({o_batch_size, num_heads, seqlen_q, head_dim_qk});
            else if (layout == 1) q = q.view({o_batch_size, seqlen_q, num_heads, head_dim_qk});
        } else { // use self-assigned regroup strategy
            seqlen_q  = mla_regroup;
            num_heads = num_heads_k * int(ngroups / mla_regroup);
            if (layout == 0)      q = q.view({o_batch_size, num_heads, mla_regroup, head_dim_qk});
            else if (layout == 1) q = q.view({o_batch_size, mla_regroup, num_heads, head_dim_qk});
        }
zhangshao's avatar
zhangshao committed
4630
    }
hly's avatar
hly committed
4631
    TORCH_CHECK(int64_t(o_batch_size * num_heads * seqlen_q * head_dim_qk) < /*2^31*/int64_t(2147483648), "The data amount of q must be smaller than the representation range of int");
zhangshao's avatar
zhangshao committed
4632

hly's avatar
hly committed
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
    // Allocate and check output
    auto opts = q.options();
    at::Tensor out;
    bool output_allocated_outside = out_.has_value();
    constexpr auto MLAFP8OutputDtype = at::ScalarType::BFloat16;
    if (output_allocated_outside) {
        out = out_.value();
        TORCH_CHECK(out.dtype() == MLAFP8OutputDtype, "Output must have the same dtype as inputs");
        CHECK_DEVICE(out);
        TORCH_CHECK(out.stride(-1) == 1, "Output tensor must have contiguous last dimension");
        // CHECK_SHAPE(out, batch_size, seqlen_q, num_heads, head_dim_v);
        out = out.view({q.size(0), q.size(1), q.size(2), head_dim_v});
    } else {
        out = at::empty({q.size(0), q.size(1), q.size(2), head_dim_v}, opts.dtype(MLAFP8OutputDtype));
    }
zhangshao's avatar
zhangshao committed
4648

hly's avatar
hly committed
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
    // Acquire and check cache_seqlens length information
    TORCH_CHECK(cache_seqlens.dtype() == at::ScalarType::Int, "seqlens_k must have dtype int32");
    CHECK_DEVICE(cache_seqlens);
    CHECK_CONTIGUOUS(cache_seqlens);
    auto cache_seqlens_ptr = cache_seqlens.data_ptr();

    Flash_fwd_mla_params params;
    // Reset the parameters
    memset(&params, 0, sizeof(params));
    // Set the status.
    params.layout = layout;
    params.mtp = mtp;
    params.is_e4m3 = true;
    params.seqlenq_ngroups_swapped = seqlenq_ngroups_swapped;
    params.is_seqlens_k_cumulative = cache_seqlens.size(0) == (batch_size + 1);
    // Set the pointers.
    params.q_ptr = q.data_ptr();
    params.k_ptr = kcache.data_ptr();
    params.v_ptr = kcache.data_ptr();
    params.o_ptr = out.data_ptr();
    params.cu_seqlens_q = static_cast<int *>(cache_seqlens_ptr);
    params.cu_seqlens_k = static_cast<int *>(cache_seqlens_ptr);
    // Set the descale
    params.scales_q_ptr = reinterpret_cast<float *>(descale_q.data_ptr<float>());
    params.scales_k_ptr = reinterpret_cast<float *>(descale_k.data_ptr<float>());
    // Set the strides.
    params.q_batch_stride = q.stride(0);
    params.o_batch_stride = out.stride(0);
    params.q_head_stride  = (layout == 1) ? q.stride(2): q.stride(1);
    params.k_head_stride  = (layout == 1) ? kcache.stride(2): kcache.stride(1);
    params.v_head_stride  = params.k_head_stride;
    params.o_head_stride  = (layout == 1) ? out.stride(2): out.stride(1);
    params.q_row_stride   = (layout == 1) ? q.stride(1): q.stride(2);
    params.k_row_stride   = (layout == 1) ? kcache.stride(1): kcache.stride(2);
    params.v_row_stride   = params.k_row_stride;
    params.o_row_stride   = (layout == 1) ? out.stride(1): out.stride(2);
    // Set the dimensions etc.
    params.b   = batch_size;
    params.h   = num_heads;
    params.h_k = num_heads_k;
    params.d   = head_dim_qk;
    params.d_v = head_dim_v;
    params.h_h_k_ratio = num_heads / num_heads_k;
    params.seqlen_q = seqlen_q;
    params.seqlen_k = max_seqlen_k;
    params.scale_softmax = softmax_scale;
    params.scale_softmax_log2 = softmax_scale * M_LOG2E;
    // Set the block table.
    params.block_table     = block_table.data_ptr<int>();
    params.page_block_size = page_block_size;
    params.block_table_batch_stride = block_table.stride(0);
    params.k_batch_stride  = kcache.stride(0);
    params.v_batch_stride  = kcache.stride(0);

    at::Tensor out_accum, softmax_lse_accum;
    // 对 seqkv 进行划分
    bool allow_splitkv = bool(std::getenv("MLA_NO_SPLITKV") == nullptr) and !is_prefill;
    if (allow_splitkv) {
        const int num_splits_assigned = 8;
        if (num_splits_assigned > 1 and batch_size <= 32) {
            // 传递给 kernel args
            params.partition_size = MLA_FIX_PARTITION;
            params.num_splits     = num_splits_assigned;
            while (o_batch_size * params.num_splits < 64) {
                params.num_splits *= 2;
            }
            params.num_splits = o_batch_size == 1 ? 32: params.num_splits; // for tiny batch size 1, splitkv reduce 64 may be the bottleneck
            params.num_splits = std::min(64, params.num_splits);
            // 申请 scores_max/sum 和 out_accum 的空间
            auto raw_memory = at::empty({1, params.num_splits, o_batch_size, num_heads, seqlen_q}, opts.dtype(at::kFloat));
            softmax_lse_accum = raw_memory.index({0});
            if (layout == 0) out_accum  = at::empty({params.num_splits, o_batch_size, num_heads, seqlen_q, head_dim_v}, opts.dtype(MLAFP8OutputDtype));
            else if (layout == 1) out_accum  = at::empty({params.num_splits, o_batch_size, seqlen_q, num_heads, head_dim_v}, opts.dtype(MLAFP8OutputDtype));
            params.softmax_lse_ptr = reinterpret_cast<float*>(softmax_lse_accum.data_ptr());
            params.oaccum_ptr      = out_accum.data_ptr();
        }
zhangshao's avatar
zhangshao committed
4725
4726
    }

hly's avatar
hly committed
4727
4728
4729
4730
    // decide accumulation dtype when splitkv
    if (params.partition_size > 0 and params.num_splits > 1) {
        params.splitkv_use_fp32_as_accum = out_accum.dtype() == at::ScalarType::Float;
    }
zhangshao's avatar
zhangshao committed
4731

hly's avatar
hly committed
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
    const char* env_info = std::getenv("FA_DEBUG");
    if (env_info != nullptr) {
        PRINT_MLA_PARAMS
        PRINT_QKV_INFO(q, kcache, kcache);
        PRINT_TENSOR_INFO(out, "out");
        std::cout << "block_table: " << block_table.sizes() << std::endl;
        if (std::strcmp(env_info, "2") == 0) {
            auto temp_tensor = cache_seqlens.to(at::DeviceType::CPU).contiguous(); // to cpu op may interrupt cudagraph
            std::vector<int32_t> temp_vector(temp_tensor.data_ptr<int32_t>(), temp_tensor.data_ptr<int32_t>() + temp_tensor.numel());
            printf("cache_seqlens: ["); for (const auto val: temp_vector) { printf("%d ", val); } printf("]\n");
        }
zhangshao's avatar
zhangshao committed
4743
4744
    }

hly's avatar
hly committed
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
    const hipStream_t stream = at::hip::getCurrentHIPStreamMasqueradingAsCUDA();
    if (max_seqlen_k > 0 and std::getenv("MLA_DECODE_EMPTY") == nullptr) {
        run_fp8_mla_fwd_splitkv_dispatch<BFloat16, 576, 512>(params, stream);
    } else {
        out.zero_();
    }

    if (seqlenq_ngroups_swapped) {
        if (layout == 0) {
            if (mtp > 1) {
                out = out.view({o_batch_size, num_heads * MTP_REGROUP_COUNT, mtp, head_dim_v});
                if (params.partition_size > 0) out_accum = out_accum.view({params.num_splits, o_batch_size, num_heads * MTP_REGROUP_COUNT, mtp, head_dim_v});
            } else {
                out = out.view({o_batch_size, num_heads_k * ngroups, mtp, head_dim_v});
                if (params.partition_size > 0) out_accum = out_accum.view({params.num_splits, o_batch_size, num_heads_k * ngroups, mtp, head_dim_v});
            }
        } else if (layout == 1) {
            if (mtp > 1) {
                out = out.view({o_batch_size, mtp, num_heads * MTP_REGROUP_COUNT, head_dim_v});
                if (params.partition_size > 0) out_accum = out_accum.view({params.num_splits, o_batch_size, mtp, num_heads * MTP_REGROUP_COUNT, head_dim_v});
            } else {
                out = out.view({o_batch_size, mtp, num_heads_k * ngroups, head_dim_v}); // kheads 为 1, 所以不用加一步 contiguous()
                if (params.partition_size > 0) out_accum = out_accum.view({params.num_splits, o_batch_size, mtp, num_heads_k * ngroups, head_dim_v});
            }
        }
    }

    if (output_allocated_outside) {
        return {};
    } else {
        return {out, out_accum, softmax_lse_accum};
    }
zhangshao's avatar
zhangshao committed
4777
#else
hly's avatar
hly committed
4778
    return {};
zhangshao's avatar
zhangshao committed
4779
4780
4781
#endif
}

hly's avatar
hly committed
4782
4783
4784
4785
4786
4787

at::Tensor flash_mla_convert_query_to_fp8(
    at::Tensor& q_nope,
    at::Tensor& q_rope,
    const bool is_fp8
) {
zhangshao's avatar
zhangshao committed
4788
#if defined(BUILD_FLASHMLA)
hly's avatar
hly committed
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
    const at::cuda::HIPGuardMasqueradingAsCUDA device_guard(q_nope.device().index());
    TORCH_CHECK(is_fp8, "flash_mla_convert_query only support return tensor of fp8 yet! Bf8 is not supported yet!");
    TORCH_CHECK(q_nope.dtype() == at::ScalarType::Half || q_nope.dtype() == at::ScalarType::BFloat16, "flash_mla_convert_query only support fp16 and bf16 data type for q");
    TORCH_CHECK(q_rope.dtype() == q_rope.dtype(), "flash_mla_convert_query only support same dtype for q_nope, q_rope");
    CHECK_DEVICE(q_nope);
    CHECK_DEVICE(q_rope);
    // Acquire basic information
    const int batch_size = q_nope.size(0);
    const int qheads = q_nope.size(-2);
    const int headdim_nope = q_nope.size(-1);
    const int headdim_rope = q_rope.size(-1);
    const int headdim_qk = headdim_nope + headdim_rope;
    const int seqlen_q = q_nope.dim() == 3 ? 1: q_nope.size(1);
    const bool is_bf16 = q_nope.dtype() == at::ScalarType::BFloat16;
    // Prepare output tensor
    at::Tensor query_fp8;
    query_fp8 = at::empty({batch_size, seqlen_q, qheads, headdim_qk}, q_nope.options().dtype(at::ScalarType::Float8_e4m3fn));
    if (q_nope.dim() == 3) query_fp8 = query_fp8.view({batch_size * seqlen_q, qheads, headdim_qk});
    // Params
    Flash_fwd_mla_params params;
    params.o_ptr          = query_fp8.data_ptr();
    params.qv_ptr         = q_nope.data_ptr();
    params.q_ptr          = q_rope.data_ptr();
    params.o_head_stride  = query_fp8.stride(-2);
    params.qv_head_stride = q_nope.stride(-2);
    params.q_head_stride  = q_rope.stride(-2);
    params.total_blocks   = batch_size * seqlen_q * qheads;
    params.qv_row_stride  = q_nope.stride(-3);
    params.q_row_stride   = q_rope.stride(-3);
    params.h              = qheads;
    // Debug
    const char* env_info = std::getenv("FA_DEBUG");
    if (env_info != nullptr) {
        std::cout << "flash_mla_convert_query_to_fp8 kernel: " << std::endl;
        std::cout << "batch_size: " << batch_size / seqlen_q << std::endl;
        std::cout << "q_nope: " << q_nope.sizes() << ", " << q_nope.strides() << ", " << q_nope.dtype() << std::endl;
        std::cout << "q_rope: " << q_rope.sizes() << ", " << q_rope.strides() << ", " << q_rope.dtype() << std::endl;
    }
    // Launch Kernel
    const hipStream_t stream = at::hip::getCurrentHIPStreamMasqueradingAsCUDA();
    FP16_SWITCH(!is_bf16, [&]{
        run_fp8_mla_convert_q_to_fp8_dispatch<elem_type, 576, 512>(params, stream);
    });
    return query_fp8;
zhangshao's avatar
zhangshao committed
4833
#else
hly's avatar
hly committed
4834
    return at::Tensor();
zhangshao's avatar
zhangshao committed
4835
4836
4837
#endif
}

hly's avatar
hly committed
4838

zhangshao's avatar
zhangshao committed
4839
4840
4841
4842
4843
#ifdef BUILD_FA_PERMUTE
#include "flash_permute_api.h"

// Preserved for emergency
at::Tensor varlen_fwd_bshd_with_permute(
hly's avatar
hly committed
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
        at::Tensor &q,
        at::Tensor &k,
        at::Tensor &v,
        c10::optional<at::Tensor> &out_,
        const at::Tensor &cu_seqlens_q,
        const at::Tensor &cu_seqlens_k,
        c10::optional<at::Tensor> &seqused_k,
        c10::optional<at::Tensor> &alibi_slopes_,
        const int max_seqlen_q,
        const int max_seqlen_k,
        const float p_dropout,
        const float softmax_scale,
        const bool zero_tensors,
        const bool is_causal,
        int window_size_left,
        int window_size_right,
        const float softcap,
        const bool return_softmax,
        c10::optional<at::Generator> gen_) {
    const at::cuda::HIPGuardMasqueradingAsCUDA device_guard(q.device().index());
    // [batch x seqlen, num_head, headdim] ----> [batch x num_head x seqlen, headdim]
    const auto query_size = q.sizes();
    const bool tensor_is_4dim = query_size.size() == 4;
    const int num_heads = tensor_is_4dim ? query_size[2]: query_size[1];
    const int num_heads_kv = tensor_is_4dim ? k.size(2): k.size(1);
    auto pre_permuted = varlen_fwd_permute_bshd2bhsd(q, k, v, cu_seqlens_q, max_seqlen_q); // 默认 cu_seqlens_q = cu_seqlens_k
    c10::optional<at::Tensor> q_descale_ = c10::nullopt;
    c10::optional<at::Tensor> k_descale_ = c10::nullopt;
    c10::optional<at::Tensor> v_descale_ = c10::nullopt;
    // FA kernel
    auto fa_out = varlen_fwd(
        pre_permuted[0],
        pre_permuted[1],
        pre_permuted[2],
        num_heads,
        num_heads_kv,
        out_,
        cu_seqlens_q,
        cu_seqlens_k,
        seqused_k,
        alibi_slopes_,
        max_seqlen_q,
        max_seqlen_k,
        p_dropout,
        softmax_scale,
        zero_tensors,
        is_causal,
        window_size_left,
        window_size_right,
        softcap,
        return_softmax,
        gen_,
        0/*bhsd*/,
        q_descale_,
        k_descale_,
        v_descale_,
        false)[0];
    // [batch x num_head x seqlen, headdim] ----> [batch x seqlen, num_head, headdim]
    return varlen_fwd_permute_bhsd2bshd(fa_out, cu_seqlens_q, num_heads, max_seqlen_q);
zhangshao's avatar
zhangshao committed
4903
4904
}

hly's avatar
hly committed
4905
4906


zhangshao's avatar
zhangshao committed
4907
4908
4909
4910
4911
4912
4913
/**
 * @brief FA Kernel, for sbhd layouts
 * @param main are listed below
           q [seqlen, batch_size, num_head, head_dim]
           k [seqlen, batch_size, num_head, head_dim]
           v [seqlen, batch_size, num_head, head_dim]
 * @return
hly's avatar
hly committed
4914
4915
           fa_output: a list of tensor, element [0] is of [seqlen, batch_size, num_head, head_dim] layouts
           Attention! Other returned results are of bhsd layouts, only output is changed by fwd_permute_bhsd2bshd
zhangshao's avatar
zhangshao committed
4916
 */
hly's avatar
hly committed
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
std::vector<at::Tensor> fwd_sbhd(
        at::Tensor &q,                            // seqlen_q x batch_size x num_heads x head_size
        at::Tensor &k,                            // seqlen_q x batch_size x num_heads x head_size
        at::Tensor &v,                            // seqlen_q x batch_size x num_heads x head_size
        c10::optional<at::Tensor> &out_,          // seqlen_q x batch_size x num_heads x head_size
        c10::optional<at::Tensor> &alibi_slopes_, // num_heads or batch_size x num_heads
        const float p_dropout,
        const float softmax_scale,
        bool is_causal,
        int window_size_left,
        int window_size_right,
        const float softcap,
        const bool return_softmax,
        c10::optional<at::Generator> gen_) {
    const at::cuda::HIPGuardMasqueradingAsCUDA device_guard(q.device().index());
    // [s, b, h, d] ---> [b, h, s, d]
    auto qkv_bhsd = fwd_permute_sbhd2bhsd(q, k, v);
    c10::optional<at::Tensor> q_descale_ = c10::nullopt;
    c10::optional<at::Tensor> k_descale_ = c10::nullopt;
    c10::optional<at::Tensor> v_descale_ = c10::nullopt;
    // bhsd FA kernel
    auto fa_output = hg_fwd_bhsd(
        qkv_bhsd[0],
        qkv_bhsd[1],
        qkv_bhsd[2],
        out_,
        alibi_slopes_,
        p_dropout,
        softmax_scale,
        is_causal,
        window_size_left,
        window_size_right,
        softcap,
        return_softmax,
        gen_,
        q_descale_,
        k_descale_,
        v_descale_,
        false);
    // [b, h, s, d] ---> [s, b, h x d]
    if (not fa_output.empty()) fa_output[0] = fwd_permute_bhsd2sbhd(fa_output[0]);
    // in this api call, some memory share operations can be applied to reduce hipMalloc
    return fa_output;
zhangshao's avatar
zhangshao committed
4960
4961
}

hly's avatar
hly committed
4962

zhangshao's avatar
zhangshao committed
4963
4964
4965
4966
4967
4968
4969
/**
 * @brief FA Kernel, for bshd layouts
 * @param main are listed below
           q [batch_size, seqlen, num_head, head_dim]
           k [batch_size, seqlen, num_head, head_dim]
           v [batch_size, seqlen, num_head, head_dim]
 * @return
hly's avatar
hly committed
4970
4971
           fa_output: a list of tensor, element [0] is of [batch_size, seqlen, num_head, head_dim] layouts
           Attention! Other returned results are of bhsd layouts, only output is changed by fwd_permute_bhsd2bshd
zhangshao's avatar
zhangshao committed
4972
4973
 */
std::vector<at::Tensor> fwd_bshd_with_permute(
hly's avatar
hly committed
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
        at::Tensor &q,                            // seqlen_q x batch_size x num_heads x head_size
        at::Tensor &k,                            // seqlen_q x batch_size x num_heads x head_size
        at::Tensor &v,                            // seqlen_q x batch_size x num_heads x head_size
        c10::optional<at::Tensor> &out_,          // seqlen_q x batch_size x num_heads x head_size
        c10::optional<at::Tensor> &alibi_slopes_, // num_heads or batch_size x num_heads
        const float p_dropout,
        const float softmax_scale,
        bool is_causal,
        int window_size_left,
        int window_size_right,
        const float softcap,
        const bool return_softmax,
        c10::optional<at::Generator> gen_) {
    const at::cuda::HIPGuardMasqueradingAsCUDA device_guard(q.device().index());
    // [b, s, h, d] ---> [b, h, s, d]
    auto qkv_bhsd = fwd_permute_bshd2bhsd(q, k, v);
    c10::optional<at::Tensor> q_descale_ = c10::nullopt;
    c10::optional<at::Tensor> k_descale_ = c10::nullopt;
    c10::optional<at::Tensor> v_descale_ = c10::nullopt;
    // bhsd FA kernel
    auto fa_output = hg_fwd_bhsd(
        qkv_bhsd[0],
        qkv_bhsd[1],
        qkv_bhsd[2],
        out_,
        alibi_slopes_,
        p_dropout,
        softmax_scale,
        is_causal,
        window_size_left,
        window_size_right,
        softcap,
        return_softmax,
        gen_,
        q_descale_,
        k_descale_,
        v_descale_,
        false);
    // [b, h, s, d] ---> [b, s, h, d]
    if (not fa_output.empty()) fa_output[0] = fwd_permute_bhsd2bshd(fa_output[0]);
    return fa_output;
zhangshao's avatar
zhangshao committed
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
}

#endif // end of BUILD_FA_PERMUTE

#define PREFIX_PREFILL_PY_ARGS                                                 \
  py::arg("q") = py::none(), py::arg("k") = py::none(),                        \
  py::arg("v") = py::none(), py::arg("out_") = py::none(),                     \
  py::arg("cu_seqlens_q") = py::none(), py::arg("cu_seqlens_k") = py::none(),  \
  py::arg("seqused_k") = py::none(), py::arg("alibi_slopes_") = py::none(),    \
  py::arg("block_table") = py::none(), py::arg("max_seqlen_q") = py::none(),   \
  py::arg("max_seqlen_k") = py::none(), py::arg("p_dropout") = py::none(),     \
  py::arg("softmax_scale") = py::none(), py::arg("zero_tensors") = py::none(), \
  py::arg("is_causal") = py::none(), py::arg("window_size_left") = py::none(), \
  py::arg("window_size_right") = py::none(), py::arg("softcap") = py::none(),  \
  py::arg("return_softmax") = py::none(), py::arg("layout") = py::none(),      \
  py::arg("scales_q_") = py::none(), py::arg("scales_k_") = py::none(),        \
hly's avatar
hly committed
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
  py::arg("scales_v_") = py::none(), py::arg("s_aux_") = py::none(),           \
  py::arg("is_bf16_output") = py::none()

#define FWD_PY_ARGS                                                            \
  py::arg("q") = py::none(), py::arg("k") = py::none(),                        \
  py::arg("v") = py::none(), py::arg("out_") = py::none(),                     \
  py::arg("alibi_slopes_") = py::none(), py::arg("p_dropout") = py::none(),    \
  py::arg("softmax_scale") = py::none(), py::arg("is_causal") = py::none(),    \
  py::arg("window_size_left") = py::none(),                                    \
  py::arg("window_size_right") = py::none(), py::arg("softcap") = py::none(),  \
  py::arg("return_softmax") = py::none(), py::arg("gen_") = py::none(),        \
  py::arg("q_descale_") = py::none(), py::arg("k_descale_") = py::none(),      \
  py::arg("v_descale_") = py::none(), py::arg("is_bf16_output") = true

#define VARLEN_FWD_PY_ARGS                                                     \
  py::arg("q") = py::none(), py::arg("k") = py::none(),                        \
  py::arg("v") = py::none(), py::arg("out_") = py::none(),                     \
  py::arg("cu_seqlens_q") = py::none(), py::arg("cu_seqlens_k") = py::none(),  \
  py::arg("seqused_k") = py::none(), py::arg("alibi_slopes_") = py::none(),    \
  py::arg("max_seqlen_q") = py::none(), py::arg("max_seqlen_k") = py::none(),  \
  py::arg("p_dropout") = py::none(), py::arg("softmax_scale") = py::none(),    \
  py::arg("zero_tensors") = py::none(), py::arg("is_causal") = py::none(),     \
  py::arg("window_size_left") = py::none(),                                    \
  py::arg("window_size_right") = py::none(), py::arg("softcap") = py::none(),  \
  py::arg("return_softmax") = py::none(), py::arg("gen_") = py::none(),        \
  py::arg("q_descale_") = py::none(), py::arg("k_descale_") = py::none(),      \
  py::arg("v_descale_") = py::none(), py::arg("is_bf16_output") = true
zhangshao's avatar
zhangshao committed
5058
5059

PYBIND11_MODULE(flash_attn_hg_cuda, m) {
hly's avatar
hly committed
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
    m.doc() = "FlashAttention";
    m.def("fwd", &hg_fwd_bshd, FWD_PY_ARGS, "Forward pass");
    m.def("bwd", &hg_bwd_bshd, "Backward pass");
    m.def("hg_fwd_bshd", &hg_fwd_bshd, FWD_PY_ARGS, "Forward pass, for inputs of bshd layout and return bshd layout");
    m.def("hg_fwd_bhsd", &hg_fwd_bhsd, FWD_PY_ARGS, "Forward pass, for inputs of bhsd layout and return bhsd layout");
    m.def("fwd_bshd", &hg_fwd_bshd, FWD_PY_ARGS, "Forward pass, for inputs of bshd layout and return bshd layout");
    m.def("fwd_bhsd", &hg_fwd_bhsd, FWD_PY_ARGS, "Forward pass, for inputs of bhsd layout and return bhsd layout");
    m.def("fwd_padding_mask", &fwd_padding_mask, "Forward pass, for inputs with padding mask in bert-liked models");
    m.def("fwd_attn_mask", &fwd_attn_mask, "Forward pass, for inputs of self-defined attn mask");
    m.def("hg_bwd_bshd", &hg_bwd_bshd, "Backward pass, for inputs of bshd layout and return bshd layout");
    m.def("hg_bwd_bhsd", &hg_bwd_bhsd, "Backward pass, for inputs of bhsd layout and return bhsd layout");
    m.def("bwd_bshd", &hg_bwd_bshd, "Backward pass, for inputs of bshd layout and return bshd layout");
    m.def("bwd_bhsd", &hg_bwd_bhsd, "Backward pass, for inputs of bhsd layout and return bhsd layout");
    m.def("varlen_fwd", &hg_varlen_fwd_bshd, VARLEN_FWD_PY_ARGS, "Forward pass (variable length), for inputs of bshd layout");
    m.def("hg_varlen_fwd_bshd", &varlen_fwd_bshd_infer, VARLEN_FWD_PY_ARGS, "Forward pass (variable length), for inputs of bshd layout, only return output, preserved for vllm/sglang interface");
    m.def("varlen_fwd_bshd", &varlen_fwd_bshd_infer, VARLEN_FWD_PY_ARGS, "Forward pass (variable length), for inputs of bshd layout, only return output, preserved for vllm/sglang interface");
    m.def("varlen_fwd_bhsd", &varlen_fwd_bhsd,  "Forward pass (variable length), for inputs of bhsd layout");
    m.def("varlen_fwd_inner", &varlen_fwd, "Forward pass (variable length) base function");
    m.def("varlen_bwd", &hg_varlen_bwd_bshd, "backward pass (variable length)");
    m.def("varlen_bwd_bshd", &hg_varlen_bwd_bshd, "backward pass (variable length), for inputs of bshd layout");
    m.def("varlen_bwd_bhsd", &mha_varlen_bwd_bhsd, "backward pass (variable length), for inputs of bhsd layout");
    m.def("fwd_kvcache", &hg_fwd_kvcache_bshd, "Forward pass, with KV-cache");
    m.def("fwd_kvcache_bhsd", &mha_fwd_kvcache_bhsd, "Forward pass, with KV-cache");
    m.def("fwd_kvcache_bshd", &hg_fwd_kvcache_bshd, "Forward pass, with KV-cache");
    m.def("hg_fwd_kvcache_mla", &hg_fwd_kvcache_mla, "HG forward pass, with FlashMLA decoding");
    m.def("fwd_kvcache_mla_fp8", &fwd_kvcache_mla_decoding_fp8, "Forward pass, with FlashMLA fp8 decoding");
    m.def("flash_mla_convert_query_to_fp8", &flash_mla_convert_query_to_fp8, "Forward pass, for convert q into fp8 dtype in FlashMLA fp8 decoding");
    m.def("hg_prefix_prefill_varlen_fwd", &hg_prefix_prefill_varlen_fwd, PREFIX_PREFILL_PY_ARGS, "Forward pass, for prefix prefill attention(bshd).");
    m.def("prefix_prefill_varlen_fwd_mla", &prefix_prefill_varlen_fwd_mla, "Forward pass, for prefix prefill attention(bshd).");
    m.def("hg_prefix_decode_varlen_fwd", &hg_prefix_decode_varlen_fwd, PREFIX_PREFILL_PY_ARGS, "Forward pass, for prefix decode attention(bshd).");
zhangshao's avatar
zhangshao committed
5090
#ifdef BUILD_FA_PERMUTE
hly's avatar
hly committed
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
    m.def("varlen_fwd_permute_bshd2bhsd", &varlen_fwd_permute_bshd2bhsd, "Forward pass (variable length), for permute layout");
    m.def("varlen_fwd_permute_bhsd2bshd", &varlen_fwd_permute_bhsd2bshd, "Forward pass (variable length), for permute layout");
    m.def("varlen_fwd_bshd_with_permute", &varlen_fwd_bshd_with_permute, "Forward pass (variable length), for inputs of bshd layout");
    m.def("fwd_permute_sbhd2bhsd", &fwd_permute_sbhd2bhsd, "Forward pass layout transformation, for inputs of sbhd -> bhsd layout");
    m.def("fwd_permute_bhsd2sbhd", &fwd_permute_bhsd2sbhd, "Forward pass layout transformation, for inputs of bhsd -> sbhd layout");
    m.def("fwd_permute_bshd2bhsd", &fwd_permute_bshd2bhsd, "Forward pass layout transformation, for inputs of bshd -> bhsd layout");
    m.def("fwd_permute_bhsd2bshd", &fwd_permute_bhsd2bshd, "Forward pass layout transformation, for inputs of bhsd -> bshd layout");
    m.def("fwd_sbhd", &fwd_sbhd, "Forward pass, for inputs of sbhd layout and return sb(hd) layout");
    m.def("fwd_bshd_with_permute", &fwd_bshd_with_permute, "Forward pass, for inputs of bshd layout and return bshd layout");
    m.def("bwd_permute_bhsd2sbhd", &bwd_permute_bhsd2sbhd, "Backward pass layout transformation, for inputs of bhsd -> sbhd layout");
    m.def("bwd_permute_bhsd2bshd", &bwd_permute_bhsd2bshd, "Backward pass layout transformation, for inputs of bhsd -> bshd layout");
    m.def("bwd_permute_sbhd2bhsd", &bwd_permute_sbhd2bhsd, "Backward pass layout transformation, for inputs of sbhd -> bhsd layout");
    m.def("bwd_permute_bshd2bhsd", &bwd_permute_bshd2bhsd, "Backward pass layout transformation, for inputs of bshd -> bhsd layout");
    m.def("permute_sbhd2bhsd", &permute_sbhd2bhsd, "Uniform layout transformation, for inputs of sbhd -> bhsd layout");
    m.def("permute_bhsd2sbhd", &permute_bhsd2sbhd, "Uniform layout transformation, for inputs of bhsd -> sbhd layout");
    m.def("permute_bhsd2bshd", &permute_bhsd2bshd, "Uniform layout transformation, for inputs of bhsd -> bshd layout");
    m.def("permute_bshd2bhsd", &permute_bshd2bhsd, "Uniform layout transformation, for inputs of bshd -> bhsd layout");
zhangshao's avatar
zhangshao committed
5108
5109
5110
5111
#endif // end of BUILD_FA_PERMUTE
}

#endif // else of no-def BUILD_C_INTERFACE