123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221 |
- #include <torch/python.h>
- #include <torch/nn/functional.h>
- #include <ATen/cuda/CUDAContext.h>
- #include <c10/cuda/CUDAGuard.h>
- #include <cutlass/numeric_types.h>
- #include "flash.h"
- #include "static_switch.h"
- #define CHECK_DEVICE(x) TORCH_CHECK(x.is_cuda(), #x " must be on CUDA")
- #define CHECK_SHAPE(x, ...) TORCH_CHECK(x.sizes() == torch::IntArrayRef({__VA_ARGS__}), #x " must have shape (" #__VA_ARGS__ ")")
- #define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x " must be contiguous")
- void set_params_fprop(Flash_fwd_params ¶ms,
-
- 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 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 *p_d,
- void *softmax_lse_d,
- float p_dropout,
- float softmax_scale,
- bool is_causal) {
-
- memset(¶ms, 0, sizeof(params));
- params.is_bf16 = q.dtype() == torch::kBFloat16;
-
- params.q_ptr = q.data_ptr();
- params.k_ptr = k.data_ptr();
- params.v_ptr = v.data_ptr();
-
- params.q_row_stride = q.stride(-3);
- params.k_row_stride = k.stride(-3);
- params.v_row_stride = v.stride(-3);
- params.q_head_stride = q.stride(-2);
- params.k_head_stride = k.stride(-2);
- params.v_head_stride = v.stride(-2);
- params.o_ptr = out.data_ptr();
- params.o_row_stride = out.stride(-3);
- params.o_head_stride = out.stride(-2);
- if (cu_seqlens_q_d == nullptr) {
- 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.cu_seqlens_q = static_cast<int *>(cu_seqlens_q_d);
- params.cu_seqlens_k = static_cast<int *>(cu_seqlens_k_d);
-
- params.p_ptr = p_d;
-
- params.softmax_lse_ptr = softmax_lse_d;
-
- 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.scale_softmax = softmax_scale;
- params.scale_softmax_log2 = softmax_scale * M_LOG2E;
-
- params.p_dropout = 1.f - p_dropout;
-
-
-
-
- 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);
- params.is_causal = is_causal;
- params.is_seqlens_k_cumulative = true;
- }
- void set_params_dgrad(Flash_bwd_params ¶ms,
-
- 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 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 *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,
- bool is_causal) {
- set_params_fprop(params,
- b, seqlen_q, seqlen_k, seqlen_q_rounded, seqlen_k_rounded, h, h_k, d, d_rounded,
- q, k, v, out,
- cu_seqlens_q_d,
- cu_seqlens_k_d,
- nullptr,
- softmax_lse_d,
- p_dropout,
- softmax_scale,
- is_causal);
-
- params.do_ptr = dout.data_ptr();
- params.do_row_stride = dout.stride(-3);
- params.do_head_stride = dout.stride(-2);
- params.dq_ptr = dq.data_ptr();
- params.dk_ptr = dk.data_ptr();
- params.dv_ptr = dv.data_ptr();
- params.dq_row_stride = dq.stride(-3);
- params.dk_row_stride = dk.stride(-3);
- params.dv_row_stride = dv.stride(-3);
- params.dq_head_stride = dq.stride(-2);
- params.dk_head_stride = dk.stride(-2);
- params.dv_head_stride = dv.stride(-2);
- 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_accum_ptr = dq_accum_d;
- params.dk_accum_ptr = dk_accum_d;
- params.dv_accum_ptr = dv_accum_d;
-
- params.dsoftmax_sum = dsoftmax_sum_d;
- }
- void run_mha_fwd(Flash_fwd_params ¶ms, cudaStream_t stream, bool force_split_kernel=false) {
- FP16_SWITCH(!params.is_bf16, [&] {
- FWD_HEADDIM_SWITCH(params.d, [&] {
- if (params.num_splits <= 1 && !force_split_kernel) {
- run_mha_fwd_<elem_type, kHeadDim>(params, stream);
- } else {
- run_mha_fwd_splitkv_dispatch<elem_type, kHeadDim>(params, stream);
- }
- });
- });
- }
- inline int num_splits_heuristic(int batch_nheads_mblocks, int num_SMs, int num_n_blocks, int max_splits) {
-
- 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; };
-
-
-
-
- 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);
-
- if (eff > max_efficiency) { max_efficiency = eff; }
- efficiency.push_back(eff);
- }
- }
- 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) {
-
- return num_splits;
- }
- }
- return 1;
- }
- std::vector<at::Tensor>
- mha_fwd(const at::Tensor &q,
- const at::Tensor &k,
- const at::Tensor &v,
- c10::optional<at::Tensor> &out_,
- const float p_dropout,
- const float softmax_scale,
- const bool is_causal,
- const bool return_softmax,
- c10::optional<at::Generator> gen_) {
- auto dprops = at::cuda::getCurrentDeviceProperties();
-
- bool is_sm8x = dprops->major == 8 && dprops->minor >= 0;
- bool is_sm90 = dprops->major == 9 && dprops->minor == 0;
- TORCH_CHECK(is_sm90 || is_sm8x, "FlashAttention only supports Ampere GPUs or newer.");
-
-
- auto q_dtype = q.dtype();
- TORCH_CHECK(q_dtype == torch::kFloat16 || q_dtype == torch::kBFloat16,
- "FlashAttention only support fp16 and bf16 data type");
- if (q_dtype == torch::kBFloat16) {
- TORCH_CHECK(is_sm90 || is_sm8x, "bfloat16 is only supported on Ampere GPUs or newer");
- }
- 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 auto sizes = q.sizes();
- const int batch_size = sizes[0];
- const int seqlen_q = sizes[1];
- const int num_heads = sizes[2];
- const int head_size_og = sizes[3];
- const int seqlen_k = k.size(1);
- const int num_heads_k = 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(num_heads % num_heads_k == 0, "Number of heads in key/value must divide number of heads in query");
- 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);
- at::Tensor q_padded, k_padded, v_padded;
- if (head_size_og % 8 != 0) {
- q_padded = torch::nn::functional::pad(q, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
- k_padded = torch::nn::functional::pad(k, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
- v_padded = torch::nn::functional::pad(v, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
- } else {
- q_padded = q;
- k_padded = k;
- v_padded = v;
- }
- 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, batch_size, seqlen_q, num_heads, head_size_og);
- if (head_size_og % 8 != 0) { out = torch::empty_like(q_padded); }
- } else {
- out = torch::empty_like(q_padded);
- }
- 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 seqlen_q_rounded = round_multiple(seqlen_q, 128);
- const int seqlen_k_rounded = round_multiple(seqlen_k, 128);
-
-
- at::cuda::CUDAGuard device_guard{(char)q.get_device()};
- auto opts = q.options();
- auto softmax_lse = torch::empty({batch_size, num_heads, seqlen_q}, opts.dtype(at::kFloat));
- at::Tensor p;
-
- if (return_softmax) {
- TORCH_CHECK(p_dropout > 0.0f, "return_softmax is only supported when p_dropout > 0.0");
- p = torch::empty({ batch_size, num_heads, seqlen_q_rounded, seqlen_k_rounded }, opts);
- }
- 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,
- q_padded, k_padded, v_padded, out,
- nullptr,
- nullptr,
- return_softmax ? p.data_ptr() : nullptr,
- softmax_lse.data_ptr(),
- p_dropout,
- softmax_scale,
- is_causal);
-
- const int block_n = is_sm90 || is_sm8x
- ? (head_size <= 64 ? 256 : (head_size <= 160 ? 128 : 64))
- : (head_size <= 64 ? 256 : (head_size <= 128 ? 128 : 64));
- const int num_n_blocks = (seqlen_k + block_n - 1) / block_n;
-
-
- const int num_m_blocks = (seqlen_q + 64 - 1) / 64;
- params.num_splits = 1;
- if (p_dropout == 0.0f) {
- params.num_splits = num_splits_heuristic(batch_size * num_heads * num_m_blocks, dprops->multiProcessorCount, num_n_blocks, 128);
- if (params.num_splits > 1) {
- at::Tensor softmax_lse_accum = torch::empty({params.num_splits, batch_size, num_heads, seqlen_q}, opts.dtype(at::kFloat));
- at::Tensor out_accum = torch::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();
- }
- }
-
-
-
- int64_t counter_offset = params.b * params.h * 32;
- auto options = torch::TensorOptions().dtype(torch::kFloat32).device(torch::kCUDA);
- auto rng_state = torch::empty({2}, options.dtype(torch::kInt64));
-
- params.rng_state = reinterpret_cast<uint64_t*>(rng_state.data_ptr());
- if (p_dropout > 0.0) {
- auto gen = at::get_generator_or_default<at::CUDAGeneratorImpl>(
- gen_, at::cuda::detail::getDefaultCUDAGenerator());
-
- std::lock_guard<std::mutex> lock(gen->mutex_);
- params.philox_args = gen->philox_cuda_state(counter_offset);
- }
- auto stream = at::cuda::getCurrentCUDAStream().stream();
- run_mha_fwd(params, stream);
- at::Tensor out_padded = out;
- if (head_size_og % 8 != 0) {
- out = out.index({"...", torch::indexing::Slice(torch::indexing::None, head_size_og)});
- if (out_.has_value()) { out_.value().copy_(out); }
- }
- return {out, q_padded, k_padded, v_padded, out_padded, softmax_lse, p, rng_state};
- }
- std::vector<at::Tensor>
- mha_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,
- const at::Tensor &cu_seqlens_k,
- 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,
- const bool return_softmax,
- c10::optional<at::Generator> gen_) {
- auto dprops = at::cuda::getCurrentDeviceProperties();
-
- bool is_sm8x = dprops->major == 8 && dprops->minor >= 0;
- bool is_sm90 = dprops->major == 9 && dprops->minor == 0;
- TORCH_CHECK(is_sm90 || is_sm8x, "FlashAttention only supports Ampere GPUs or newer.");
-
-
- auto q_dtype = q.dtype();
- TORCH_CHECK(q_dtype == torch::kFloat16 || q_dtype == torch::kBFloat16,
- "FlashAttention only support fp16 and bf16 data type");
- if (q_dtype == torch::kBFloat16) {
- TORCH_CHECK(is_sm90 || is_sm8x, "bfloat16 is only supported on Ampere GPUs or newer");
- }
- 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() == 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(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 = sizes[0];
- const int batch_size = cu_seqlens_q.numel() - 1;
- const int num_heads = sizes[1];
- const int head_size_og = 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_og <= 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");
- CHECK_SHAPE(q, total_q, num_heads, head_size_og);
- CHECK_SHAPE(k, total_k, num_heads_k, head_size_og);
- CHECK_SHAPE(v, total_k, num_heads_k, head_size_og);
- CHECK_SHAPE(cu_seqlens_q, batch_size + 1);
- CHECK_SHAPE(cu_seqlens_k, batch_size + 1);
- at::Tensor q_padded, k_padded, v_padded;
- if (head_size_og % 8 != 0) {
- q_padded = torch::nn::functional::pad(q, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
- k_padded = torch::nn::functional::pad(k, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
- v_padded = torch::nn::functional::pad(v, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
- } else {
- q_padded = q;
- k_padded = k;
- v_padded = v;
- }
- 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_og);
- if (head_size_og % 8 != 0) { out = torch::empty_like(q_padded); }
- } else {
- out = torch::empty_like(q_padded);
- }
- 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 seqlen_q_rounded = round_multiple(max_seqlen_q, 128);
- const int seqlen_k_rounded = round_multiple(max_seqlen_k, 128);
-
-
- at::cuda::CUDAGuard device_guard{(char)q.get_device()};
- auto opts = q.options();
- auto softmax_lse = torch::empty({batch_size, num_heads, max_seqlen_q}, opts.dtype(at::kFloat));
- at::Tensor p;
-
- if (return_softmax) {
- TORCH_CHECK(p_dropout > 0.0f, "return_softmax is only supported when p_dropout > 0.0");
- p = torch::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,
- q_padded, k_padded, v_padded, out,
- cu_seqlens_q.data_ptr(),
- cu_seqlens_k.data_ptr(),
- return_softmax ? p.data_ptr() : nullptr,
- softmax_lse.data_ptr(),
- p_dropout,
- softmax_scale,
- is_causal);
-
-
-
- int64_t counter_offset = params.b * params.h * 32;
- auto options = torch::TensorOptions().dtype(torch::kFloat32).device(torch::kCUDA);
- auto rng_state = torch::empty({2}, options.dtype(torch::kInt64));
-
- params.rng_state = reinterpret_cast<uint64_t*>(rng_state.data_ptr());
- if (p_dropout > 0.0) {
- auto gen = at::get_generator_or_default<at::CUDAGeneratorImpl>(
- gen_, at::cuda::detail::getDefaultCUDAGenerator());
-
- std::lock_guard<std::mutex> lock(gen->mutex_);
- params.philox_args = gen->philox_cuda_state(counter_offset);
- }
- auto stream = at::cuda::getCurrentCUDAStream().stream();
- run_mha_fwd(params, stream);
- at::Tensor out_padded = out;
- if (head_size_og % 8 != 0) {
- out = out.index({"...", torch::indexing::Slice(torch::indexing::None, head_size_og)});
- if (out_.has_value()) { out_.value().copy_(out); }
- }
- return {out, q_padded, k_padded, v_padded, out_padded, softmax_lse, p, rng_state};
- }
- void run_mha_bwd(Flash_bwd_params ¶ms, cudaStream_t stream, const bool configure) {
- FP16_SWITCH(!params.is_bf16, [&] {
- if (params.d <= 32) {
- run_mha_bwd_<elem_type, 32>(params, stream, configure);
- } else if (params.d <= 64) {
- run_mha_bwd_<elem_type, 64>(params, stream, configure);
- } else if (params.d <= 96) {
- run_mha_bwd_<elem_type, 96>(params, stream, configure);
- } else if (params.d <= 128) {
- run_mha_bwd_<elem_type, 128>(params, stream, configure);
- } else if (params.d <= 160) {
- run_mha_bwd_<elem_type, 160>(params, stream, configure);
- } else if (params.d <= 192) {
- run_mha_bwd_<elem_type, 192>(params, stream, configure);
- } else if (params.d <= 224) {
- run_mha_bwd_<elem_type, 224>(params, stream, configure);
- } else if (params.d <= 256) {
- run_mha_bwd_<elem_type, 256>(params, stream, configure);
- }
- });
- }
- std::vector<at::Tensor>
- mha_bwd(const at::Tensor &dout,
- const at::Tensor &q,
- const at::Tensor &k,
- const at::Tensor &v,
- const at::Tensor &out,
- const at::Tensor &softmax_lse,
- c10::optional<at::Tensor> &dq_,
- c10::optional<at::Tensor> &dk_,
- c10::optional<at::Tensor> &dv_,
- const float p_dropout,
- const float softmax_scale,
- const bool is_causal,
- c10::optional<at::Generator> gen_,
- c10::optional<at::Tensor> &rng_state) {
- auto dprops = at::cuda::getCurrentDeviceProperties();
-
- bool is_sm8x = dprops->major == 8 && dprops->minor >= 0;
- bool is_sm80 = dprops->major == 8 && dprops->minor == 0;
- bool is_sm90 = dprops->major == 9 && dprops->minor == 0;
- TORCH_CHECK(is_sm90 || is_sm8x, "FlashAttention only supports Ampere GPUs or newer.");
-
-
- bool is_dropout = p_dropout > 0.0;
- auto stream = at::cuda::getCurrentCUDAStream().stream();
- auto q_dtype = q.dtype();
- TORCH_CHECK(q_dtype == torch::kFloat16 || q_dtype == torch::kBFloat16,
- "FlashAttention only support fp16 and bf16 data type");
- if (q_dtype == torch::kBFloat16) {
- TORCH_CHECK(is_sm90 || is_sm8x, "bfloat16 is only supported on Ampere GPUs or newer");
- }
- 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");
- const auto sizes = q.sizes();
- const int batch_size = sizes[0];
- const int seqlen_q = sizes[1];
- const int num_heads = sizes[2];
- const int head_size_og = dout.size(3);
- const int head_size = sizes[3];
- const int seqlen_k = k.size(1);
- const int num_heads_k = k.size(2);
- TORCH_CHECK(batch_size > 0, "batch size must be positive");
- TORCH_CHECK(head_size % 8 == 0, "head_size should be a multiple of 8");
- TORCH_CHECK(head_size <= 256, "FlashAttention backward only supports head dimension at most 256");
- if (head_size > 192) {
- TORCH_CHECK(is_sm80 || is_sm90, "FlashAttention backward for head dim > 192 requires A100/A800 or H100/H800");
- }
- TORCH_CHECK(num_heads % num_heads_k == 0, "Number of heads in key/value must divide number of heads in query");
- 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 seqlen_q_rounded = round_multiple(seqlen_q, 128);
- const int seqlen_k_rounded = round_multiple(seqlen_k, 128);
- TORCH_CHECK(head_size == round_multiple(head_size_og, 8), "head_size must be head_size_og rounded to a multiple of 8");
- 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);
- CHECK_SHAPE(out, batch_size, seqlen_q, num_heads, head_size);
- CHECK_SHAPE(dout, batch_size, seqlen_q, num_heads, head_size_og);
- at::Tensor dq, dk, dv;
- if (dq_.has_value()) {
- dq = dq_.value();
- TORCH_CHECK(dq.dtype() == q_dtype, "dq must have the same dtype as q");
- CHECK_DEVICE(dq);
- TORCH_CHECK(dq.stride(-1) == 1, "dq must have contiguous last dimension");
- CHECK_SHAPE(dq, batch_size, seqlen_q, num_heads, head_size);
- } else {
- dq = torch::empty_like(q);
- }
- if (dk_.has_value()) {
- dk = dk_.value();
- TORCH_CHECK(dk.dtype() == q_dtype, "dk must have the same dtype as q");
- CHECK_DEVICE(dk);
- TORCH_CHECK(dk.stride(-1) == 1, "dk must have contiguous last dimension");
- CHECK_SHAPE(dk, batch_size, seqlen_k, num_heads_k, head_size);
- } else {
- dk = torch::empty_like(k);
- }
- if (dv_.has_value()) {
- dv = dv_.value();
- TORCH_CHECK(dv.dtype() == q_dtype, "dv must have the same dtype as q");
- CHECK_DEVICE(dv);
- TORCH_CHECK(dv.stride(-1) == 1, "dv must have contiguous last dimension");
- CHECK_SHAPE(dv, batch_size, seqlen_k, num_heads_k, head_size);
- } else {
- dv = torch::empty_like(k);
- }
- at::Tensor dout_padded;
- if (head_size_og % 8 != 0) {
- dout_padded = torch::nn::functional::pad(dout, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
- } else {
- dout_padded = dout;
- }
-
-
- bool loop = true;
-
-
- at::cuda::CUDAGuard device_guard{(char)q.get_device()};
- auto opts = q.options();
- auto softmax_d = torch::empty({batch_size, num_heads, seqlen_q_rounded}, opts.dtype(at::kFloat));
- at::Tensor dq_accum;
- at::Tensor dk_accum, dv_accum;
- if (loop) {
- dq_accum = torch::empty({batch_size, num_heads, seqlen_q_rounded, head_size_rounded}, opts.dtype(at::kFloat));
-
-
- }
- at::Tensor dk_expanded, dv_expanded;
- if (num_heads_k != num_heads) {
- dk_expanded = torch::empty({batch_size, seqlen_k, num_heads, head_size}, opts);
- dv_expanded = torch::empty({batch_size, seqlen_k, num_heads, head_size}, opts);
- } else {
- dk_expanded = dk;
- dv_expanded = dv;
- }
- 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,
- q, k, v, out,
- dout_padded, dq, dk_expanded, dv_expanded,
- nullptr,
- nullptr,
- loop ? dq_accum.data_ptr() : nullptr,
-
-
- nullptr,
- nullptr,
- softmax_lse.data_ptr(),
- softmax_d.data_ptr(),
- p_dropout,
- softmax_scale,
- is_causal);
- auto launch = &run_mha_bwd;
-
- auto gen = at::get_generator_or_default<at::CUDAGeneratorImpl>(
- gen_, at::cuda::detail::getDefaultCUDAGenerator());
-
- int64_t counter_offset = params.b * params.h * 32;
- if ( rng_state.has_value() ) {
- params.rng_state = reinterpret_cast<uint64_t*>(rng_state.value().data_ptr());
- } else if( is_dropout ) {
-
- std::lock_guard<std::mutex> lock(gen->mutex_);
- params.philox_args = gen->philox_cuda_state(counter_offset);
- auto seeds = at::cuda::philox::unpack(params.philox_args);
- params.rng_state[0] = std::get<0>(seeds);
- params.rng_state[1] = std::get<1>(seeds);
- }
- launch(params, stream, false);
-
- if (num_heads_k != num_heads) {
- at::sum_out(dk, at::reshape(dk_expanded, {batch_size, seqlen_k, num_heads_k, num_heads / num_heads_k, head_size}), {3});
- at::sum_out(dv, at::reshape(dv_expanded, {batch_size, seqlen_k, num_heads_k, num_heads / num_heads_k, head_size}), {3});
- }
- if (head_size_og % 8 != 0) {
- dq = dq.index({"...", torch::indexing::Slice(torch::indexing::None, head_size_og)});
- dk = dk.index({"...", torch::indexing::Slice(torch::indexing::None, head_size_og)});
- dv = dv.index({"...", torch::indexing::Slice(torch::indexing::None, head_size_og)});
- }
- return { dq, dk, dv, softmax_d };
- }
- std::vector<at::Tensor>
- mha_varlen_bwd(const at::Tensor &dout,
- const at::Tensor &q,
- const at::Tensor &k,
- const at::Tensor &v,
- const at::Tensor &out,
- const at::Tensor &softmax_lse,
- c10::optional<at::Tensor> &dq_,
- c10::optional<at::Tensor> &dk_,
- c10::optional<at::Tensor> &dv_,
- const at::Tensor &cu_seqlens_q,
- const at::Tensor &cu_seqlens_k,
- 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,
- c10::optional<at::Generator> gen_,
- c10::optional<at::Tensor> &rng_state
- ) {
- auto dprops = at::cuda::getCurrentDeviceProperties();
-
- bool is_sm8x = dprops->major == 8 && dprops->minor >= 0;
- bool is_sm80 = dprops->major == 8 && dprops->minor == 0;
- bool is_sm90 = dprops->major == 9 && dprops->minor == 0;
- TORCH_CHECK(is_sm90 || is_sm8x, "FlashAttention only supports Ampere GPUs or newer.");
-
-
- bool is_dropout = p_dropout > 0.0;
- auto stream = at::cuda::getCurrentCUDAStream().stream();
- auto q_dtype = q.dtype();
- TORCH_CHECK(q_dtype == torch::kFloat16 || q_dtype == torch::kBFloat16,
- "FlashAttention only support fp16 and bf16 data type");
- if (q_dtype == torch::kBFloat16) {
- TORCH_CHECK(is_sm90 || is_sm8x, "bfloat16 is only supported on Ampere GPUs or newer");
- }
- 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 = sizes[0];
- const int batch_size = cu_seqlens_q.numel() - 1;
- const int num_heads = sizes[1];
- const int head_size_og = dout.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 % 8 == 0, "head_size should be a multiple of 8");
- TORCH_CHECK(head_size <= 256, "FlashAttention backward only supports head dimension at most 256");
- if (head_size > 192) {
- TORCH_CHECK(is_sm80 || is_sm90, "FlashAttention backward for head dim > 192 requires A100/A800 or H100/H800");
- }
- TORCH_CHECK(num_heads % num_heads_k == 0, "Number of heads in key/value must divide number of heads in query");
- 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 seqlen_q_rounded = round_multiple(max_seqlen_q, 128);
- const int seqlen_k_rounded = round_multiple(max_seqlen_k, 128);
- TORCH_CHECK(head_size == round_multiple(head_size_og, 8), "head_size must be head_size_og rounded to a multiple of 8");
- CHECK_SHAPE(q, total_q, num_heads, head_size);
- CHECK_SHAPE(k, total_k, num_heads_k, head_size);
- CHECK_SHAPE(v, total_k, num_heads_k, head_size);
- CHECK_SHAPE(out, total_q, num_heads, head_size);
- CHECK_SHAPE(dout, total_q, num_heads, head_size_og);
- CHECK_SHAPE(cu_seqlens_q, batch_size + 1);
- CHECK_SHAPE(cu_seqlens_k, batch_size + 1);
- at::Tensor dq, dk, dv;
- if (dq_.has_value()) {
- dq = dq_.value();
- TORCH_CHECK(dq.dtype() == q_dtype, "dq must have the same dtype as q");
- CHECK_DEVICE(dq);
- TORCH_CHECK(dq.stride(-1) == 1, "dq must have contiguous last dimension");
- CHECK_SHAPE(dq, total_q, num_heads, head_size);
- } else {
- dq = torch::empty_like(q);
- }
- if (dk_.has_value()) {
- dk = dk_.value();
- TORCH_CHECK(dk.dtype() == q_dtype, "dk must have the same dtype as q");
- CHECK_DEVICE(dk);
- TORCH_CHECK(dk.stride(-1) == 1, "dk must have contiguous last dimension");
- CHECK_SHAPE(dk, total_k, num_heads_k, head_size);
- } else {
- dk = torch::empty_like(k);
- }
- if (dv_.has_value()) {
- dv = dv_.value();
- TORCH_CHECK(dv.dtype() == q_dtype, "dv must have the same dtype as q");
- CHECK_DEVICE(dv);
- TORCH_CHECK(dv.stride(-1) == 1, "dv must have contiguous last dimension");
- CHECK_SHAPE(dv, total_k, num_heads_k, head_size);
- } else {
- dv = torch::empty_like(k);
- }
- at::Tensor dout_padded;
- if (head_size_og % 8 != 0) {
- dout_padded = torch::nn::functional::pad(dout, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
- } else {
- dout_padded = dout;
- }
-
-
- bool loop = true;
-
-
- at::cuda::CUDAGuard device_guard{(char)q.get_device()};
- auto opts = q.options();
- auto softmax_d = torch::empty({batch_size, num_heads, seqlen_q_rounded}, opts.dtype(at::kFloat));
- at::Tensor dq_accum;
- if (loop) {
- dq_accum = torch::empty({batch_size, num_heads, seqlen_q_rounded, head_size_rounded}, opts.dtype(at::kFloat));
- }
- at::Tensor dk_expanded, dv_expanded;
- if (num_heads_k != num_heads) {
- dk_expanded = torch::empty({total_k, num_heads, head_size}, opts);
- dv_expanded = torch::empty({total_k, num_heads, head_size}, opts);
- } else {
- dk_expanded = dk;
- dv_expanded = dv;
- }
- if( zero_tensors ) {
- dq.zero_();
- dk_expanded.zero_();
- dv_expanded.zero_();
- softmax_d.zero_();
- }
- 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,
- q, k, v, out,
- dout_padded, dq, dk_expanded, dv_expanded,
- cu_seqlens_q.data_ptr(),
- cu_seqlens_k.data_ptr(),
- loop ? dq_accum.data_ptr() : nullptr,
- nullptr,
- nullptr,
- softmax_lse.data_ptr(),
- softmax_d.data_ptr(),
- p_dropout,
- softmax_scale,
- is_causal);
- auto launch = &run_mha_bwd;
-
- auto gen = at::get_generator_or_default<at::CUDAGeneratorImpl>(
- gen_, at::cuda::detail::getDefaultCUDAGenerator());
-
- int64_t counter_offset = params.b * params.h * 32;
- if ( rng_state.has_value() ) {
- params.rng_state = reinterpret_cast<uint64_t*>(rng_state.value().data_ptr());
- } else if( is_dropout ) {
-
- std::lock_guard<std::mutex> lock(gen->mutex_);
- params.philox_args = gen->philox_cuda_state(counter_offset);
- auto seeds = at::cuda::philox::unpack(params.philox_args);
- params.rng_state[0] = std::get<0>(seeds);
- params.rng_state[1] = std::get<1>(seeds);
- }
- launch(params, stream, false);
-
- if (num_heads_k != num_heads) {
- at::sum_out(dk, at::reshape(dk_expanded, {total_k, num_heads_k, num_heads / num_heads_k, head_size}), {2});
- at::sum_out(dv, at::reshape(dv_expanded, {total_k, num_heads_k, num_heads / num_heads_k, head_size}), {2});
- }
- if (head_size_og % 8 != 0) {
- dq = dq.index({"...", torch::indexing::Slice(torch::indexing::None, head_size_og)});
- dk = dk.index({"...", torch::indexing::Slice(torch::indexing::None, head_size_og)});
- dv = dv.index({"...", torch::indexing::Slice(torch::indexing::None, head_size_og)});
- }
- return { dq, dk, dv, softmax_d };
- }
- std::vector<at::Tensor>
- mha_fwd_kvcache(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_k_,
- c10::optional<const at::Tensor> &rotary_cos_,
- c10::optional<const at::Tensor> &rotary_sin_,
- c10::optional<at::Tensor> &out_,
- const float softmax_scale,
- bool is_causal,
- bool is_rotary_interleaved,
- int num_splits
- ) {
- auto dprops = at::cuda::getCurrentDeviceProperties();
-
- bool is_sm8x = dprops->major == 8 && dprops->minor >= 0;
- bool is_sm90 = dprops->major == 9 && dprops->minor == 0;
- TORCH_CHECK(is_sm90 || is_sm8x, "FlashAttention only supports Ampere GPUs or newer.");
-
-
- auto q_dtype = q.dtype();
- TORCH_CHECK(q_dtype == torch::kFloat16 || q_dtype == torch::kBFloat16,
- "FlashAttention only support fp16 and bf16 data type");
- if (q_dtype == torch::kBFloat16) {
- TORCH_CHECK(is_sm90 || is_sm8x, "bfloat16 is only supported on Ampere GPUs or newer");
- }
- 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");
- const auto sizes = q.sizes();
- const int batch_size = sizes[0];
- int seqlen_q = sizes[1];
- int num_heads = sizes[2];
- const int head_size_og = sizes[3];
- const int seqlen_k = kcache.size(1);
- const int num_heads_k = kcache.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(num_heads % num_heads_k == 0, "Number of heads in key/value must divide number of heads in query");
- if (seqlen_q == 1) { is_causal = false; }
-
- const int seqlenq_nheads_swapped = seqlen_q == 1 && num_heads_k == 1 && num_heads > 1;
- if (seqlenq_nheads_swapped) {
- q = q.transpose(1, 2);
- std::swap(seqlen_q, num_heads);
- }
- CHECK_SHAPE(q, batch_size, seqlen_q, num_heads, head_size_og);
- CHECK_SHAPE(kcache, batch_size, seqlen_k, num_heads_k, head_size_og);
- CHECK_SHAPE(vcache, batch_size, seqlen_k, num_heads_k, head_size_og);
- at::Tensor q_padded, kcache_padded, vcache_padded;
- if (head_size_og % 8 != 0) {
- q_padded = torch::nn::functional::pad(q, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
- kcache_padded = torch::nn::functional::pad(kcache, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
- vcache_padded = torch::nn::functional::pad(vcache, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
- } else {
- q_padded = q;
- kcache_padded = kcache;
- vcache_padded = vcache;
- }
- 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, batch_size, seqlen_q, num_heads, head_size_og);
- if (head_size_og % 8 != 0) { out = torch::empty_like(q_padded); }
- } else {
- out = torch::empty_like(q_padded);
- }
- 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 seqlen_q_rounded = round_multiple(seqlen_q, 128);
- const int seqlen_k_rounded = round_multiple(seqlen_k, 128);
-
-
- at::cuda::CUDAGuard device_guard{(char)q.get_device()};
- auto opts = q.options();
- auto softmax_lse = torch::empty({batch_size, num_heads, seqlen_q}, opts.dtype(at::kFloat));
- 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,
- q_padded, kcache_padded, vcache_padded, out,
- nullptr,
- nullptr,
- nullptr,
- softmax_lse.data_ptr(),
- 0.f,
- softmax_scale,
- is_causal);
- at::Tensor k, v, k_padded, v_padded;
- if (k_.has_value()) {
- 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 <= seqlen_k, "If key is supplied, it must have seqlen <= the seqlen of the KV cache");
- k = k_.value();
- v = v_.value();
- 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, head_size_og);
- CHECK_SHAPE(v, batch_size, seqlen_knew, num_heads_k, head_size_og);
- if (head_size_og % 8 != 0) {
- k_padded = torch::nn::functional::pad(k, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
- v_padded = torch::nn::functional::pad(v, torch::nn::functional::PadFuncOptions({0, 8 - head_size_og % 8}));
- } else {
- k_padded = k;
- v_padded = v;
- }
- params.seqlen_knew = seqlen_knew;
- params.knew_ptr = k_padded.data_ptr();
- params.vnew_ptr = v_padded.data_ptr();
-
- 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);
- }
- if (seqlens_k_.has_value()) {
- auto seqlens_k = seqlens_k_.value();
- TORCH_CHECK(seqlens_k.dtype() == torch::kInt32, "seqlens_k must have dtype int32");
- CHECK_DEVICE(seqlens_k);
- CHECK_CONTIGUOUS(seqlens_k);
- CHECK_SHAPE(seqlens_k, batch_size);
- params.cu_seqlens_k = static_cast<int *>(seqlens_k.data_ptr());
- }
- params.is_seqlens_k_cumulative = !(seqlens_k_.has_value());
- 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 <= 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 >= 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;
- } else {
- params.rotary_dim = 0;
- }
-
- const int block_n = is_sm90 || is_sm8x
- ? (head_size <= 64 ? 256 : (head_size <= 160 ? 128 : 64))
- : (head_size <= 64 ? 256 : (head_size <= 128 ? 128 : 64));
- const int num_n_blocks = (seqlen_k + (params.knew_ptr == nullptr ? 0 : seqlen_q) + block_n - 1) / block_n;
-
-
- const int num_m_blocks = (seqlen_q + 64 - 1) / 64;
- params.num_splits = num_splits;
- if (num_splits < 1) {
- params.num_splits = num_splits_heuristic(batch_size * num_heads * num_m_blocks, dprops->multiProcessorCount, num_n_blocks, 128);
- }
- if (params.num_splits > 1) {
- at::Tensor softmax_lse_accum = torch::empty({params.num_splits, batch_size, num_heads, seqlen_q}, opts.dtype(at::kFloat));
- at::Tensor out_accum = torch::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();
- }
- auto stream = at::cuda::getCurrentCUDAStream().stream();
-
- run_mha_fwd(params, stream, k_.has_value());
- if (head_size_og % 8 != 0) {
- out = out.index({"...", torch::indexing::Slice(torch::indexing::None, head_size_og)});
- if (out_.has_value()) { out_.value().copy_(out); }
- if (k_.has_value()) {
-
-
- kcache.copy_(kcache_padded.index({"...", torch::indexing::Slice(torch::indexing::None, head_size_og)}));
- vcache.copy_(vcache_padded.index({"...", torch::indexing::Slice(torch::indexing::None, head_size_og)}));
- }
- }
- if (seqlenq_nheads_swapped) {
- out = out.transpose(1, 2);
- softmax_lse = softmax_lse.transpose(1, 2);
- }
- return {out, softmax_lse};
- }
- PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
- m.doc() = "FlashAttention";
- m.def("fwd", &mha_fwd, "Forward pass");
- m.def("varlen_fwd", &mha_varlen_fwd, "Forward pass (variable length)");
- m.def("bwd", &mha_bwd, "Backward pass");
- m.def("varlen_bwd", &mha_varlen_bwd, "Backward pass (variable length)");
- m.def("fwd_kvcache", &mha_fwd_kvcache, "Forward pass, with KV-cache");
- }
|