Skip to content

Commit

Permalink
fix: Align code with flash_api.cpp when num_splits > 1 (#22)
Browse files Browse the repository at this point in the history
  • Loading branch information
Seventeen17 authored Nov 21, 2024
1 parent ee9724f commit 0451484
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
2 changes: 1 addition & 1 deletion test/test_flash_attention_forward.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def setup_env():
@pytest.mark.parametrize("alibi", [False, True])
@pytest.mark.parametrize("local", [False, True])
@pytest.mark.parametrize("causal", [False, True])
@pytest.mark.parametrize("d", [8])
@pytest.mark.parametrize("d", [256])
@pytest.mark.parametrize("softmax_scale", [0.25])
@pytest.mark.parametrize(
"seqlen_q,seqlen_k",
Expand Down
28 changes: 24 additions & 4 deletions torch_xla/csrc/ops/flash_attention_forward.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -234,15 +234,31 @@ void custom_call_flash_attention_forward(cudaStream_t stream, void** buffers,
// kernel. In any case we don't expect seqlen_q to be larger than 64 for
// inference.
const int num_m_blocks = (params.seqlen_q + 64 - 1) / 64;
launch_params.num_splits = 0;
if (1 - params.p_dropout == 0.0f) { // SplitKV is not implemented for dropout
launch_params.num_splits = params.num_splits;
if (params.p_dropout == 1.0f) { // SplitKV is not implemented for dropout
if (launch_params.num_splits < 1) {
auto dprops = at::cuda::getCurrentDeviceProperties();
launch_params.num_splits =
num_splits_heuristic(params.b * params.h * num_m_blocks,
dprops->multiProcessorCount, num_n_blocks, 128);
}
}
const int num_splits =
launch_params.num_splits == 0 ? 1 : launch_params.num_splits;
at::Tensor softmax_lse_accum =
torch::empty({num_splits, params.b, params.h, launch_params.seqlen_q},
opts.dtype(at::kFloat));
at::Tensor out_accum =
torch::empty({num_splits, params.b, params.h, launch_params.seqlen_q,
launch_params.d_rounded},
opts.dtype(at::kFloat));
if (fabs(1 - params.p_dropout) <
1e-6) { // SplitKV is not implemented for dropout
if (launch_params.num_splits > 1) {
launch_params.softmax_lseaccum_ptr = softmax_lse_accum.data_ptr();
launch_params.oaccum_ptr = out_accum.data_ptr();
}
}

int64_t counter_offset = params.b * params.h * 32;

Expand All @@ -269,8 +285,12 @@ void custom_call_flash_attention_forward(cudaStream_t stream, void** buffers,

FP16_SWITCH(!launch_params.is_bf16, [&] {
HEADDIM_SWITCH(launch_params.d, [&] {
// TODO(wenting.swt): support split_kv
run_mha_fwd_<elem_type, kHeadDim>(launch_params, torch_stream);
if (launch_params.num_splits <= 1) {
run_mha_fwd_<elem_type, kHeadDim>(launch_params, torch_stream);
} else {
run_mha_fwd_splitkv_dispatch<elem_type, kHeadDim>(launch_params,
torch_stream);
}
});
});

Expand Down

0 comments on commit 0451484

Please sign in to comment.