Compare commits

...
Author SHA1 Message Date
wang-xiangX a65b701123 flash attention spase pta 2023-06-16 07:03:22 +00:00
weili10 a3a89f9ffc Fix raw_delete bug
Signed-off-by: weili10 <liwei386@huawei.com>
2023-06-16 06:19:41 +00:00
wang-xiangX ac71cf3773 modify CmakeList 2023-06-14 08:52:30 +00:00
wang-xiangX d197fa5931 debug grad yaml 2023-06-14 07:17:10 +00:00
wang-xiangX 245be6d3de flash_attention_score_grad 2.0 2023-06-14 03:52:46 +00:00
zgx950813 2a734f2884 whole attention score pta 2023-06-13 06:59:16 +00:00
horming.tian 0fd0e5ccce Add a custom operator npu_flash_attention_score 2023-06-12 14:16:04 +00:00
秦传瑜 d1ecd71050 update OWNERS.
Signed-off-by: 秦传瑜 <qinchuanyu@huawei.com>
2023-06-12 14:14:26 +00:00
秦传瑜 2a9351683a update OWNERS.
Signed-off-by: 秦传瑜 <qinchuanyu@huawei.com>
2023-06-12 14:09:59 +00:00
9 changed files with 368 additions and 12 deletions
+3 -3
View File
@@ -3,10 +3,10 @@ approvers:
- weili10
- you-ansheng
- yskhhh
- clinglai
- guxinxin2@hisilicon.com
- lvpeiyuan
- xiepeng20
- xiong05
- wangkai86@huawei.com
- guoyafeng1@huawei.com
- guang-jun-zhang2
- shibo19
reviewers:
+4 -5
View File
@@ -112,11 +112,10 @@ def parse_native_and_custom_yaml(path: str, custom_path: str) -> ParsedYaml:
bs: Dict[DispatchKey, Dict[OperatorName, BackendMetadata]] = defaultdict(dict)
for e in es:
funcs = e.get('func')
if custom_data['supported']:
for op in custom_data['supported']:
if op['func'] == funcs.split('(')[0]:
op['func'] = funcs
e.update(op)
for op in custom_data['supported'] or custom_data['custom'] or custom_data['custom_autograd']:
if op['func'] == funcs.split('(')[0]:
op['func'] = funcs
e.update(op)
with context(lambda: f'in {path}:\n {funcs}'):
func, m = NativeFunction.from_yaml(e)
rs.append(func)
+2
View File
@@ -15,6 +15,7 @@
import os
import re
import gc
import sys
import builtins
import inspect
@@ -252,6 +253,7 @@ torch_npu._C._initExtension()
# NPU exit, need to synchronize devices
def _npu_shutdown():
gc.collect()
torch_npu._C._npu_shutdown()
@@ -1539,6 +1539,8 @@ custom:
- func: batch_norm_reduce(Tensor input, float eps) -> (Tensor, Tensor)
- func: batch_norm_gather_stats_update(Tensor input, Tensor mean, Tensor invstd, Tensor? running_mean, Tensor? running_var, float momentum, float eps, Tensor counts) -> (Tensor, Tensor)
- func: npu_fused_attention_score_backward(Tensor grad_output, Tensor softmax_output, Tensor query_layer, Tensor key_layer, Tensor value_layer, Tensor mask, Scalar scale, float keep_prob, bool query_transpose=False, bool key_transpose=False, bool value_transpose=False, bool dx_transpose=False) -> (Tensor, Tensor, Tensor)
- func: npu_flash_attention_score_grad(Tensor query, Tensor key, Tensor value, Tensor dy, *, Tensor? pse=None, Tensor? drop_mask=None, Tensor? padding_mask=None, Tensor? atten_mask=None, Tensor? softmax_max=None, Tensor? softmax_sum=None, Tensor? softmax_in=None, Tensor? attention_in=None, float scale_value=1., float keep_prob=1., bool query_transpose=False, bool key_transpose=True, bool value_transpose=False, bool dy_transpose=False, bool is_transpose_attention=True, int pre_tockens=INT_MAX, int next_tockens=INT_MAX) -> Tensor[]
op_api: True
- func: npu_fused_attention_score_fwd(Tensor query_layer, Tensor key_layer, Tensor value_layer, Tensor attention_mask, Scalar scale, float keep_prob, bool query_transpose=False, bool key_transpose=False, bool bmm_score_transpose_a=False, bool bmm_score_transpose_b=False, bool value_transpose=False, bool dx_transpose=False) -> (Tensor, Tensor, Tensor)
- func: npu_fused_attention_score_grad(Tensor grad_output, Tensor softmax_output, Tensor query_layer, Tensor key_layer, Tensor value_layer, Tensor mask, Scalar scale, float keep_prob, bool query_transpose=False, bool key_transpose=False, bool value_transpose=False, bool dx_transpose=False) -> (Tensor, Tensor, Tensor)
- func: npu_fused_attention_qkv_grad(Tensor grad_output_query, Tensor grad_output_key, Tensor grad_output_value, Tensor query_kernel, Tensor key_kernel, Tensor value_kernel, Tensor hidden_states, Tensor grad_output_ln) -> Tensor[]
@@ -1589,3 +1591,5 @@ custom_autograd:
- func: npu_ciou(Tensor self, Tensor gtboxes, bool trans=False, bool is_cross=True, int mode=0, bool atan_sub_flag=False) -> Tensor
- func: npu_lstm_cell(Tensor input, Tensor w_ih, Tensor w_hh, Tensor h, Tensor c, Tensor? b_ih=None, Tensor? b_hh=None) -> Tensor[]
- func: npu_fused_attention_score(Tensor query_layer, Tensor key_layer, Tensor value_layer, Tensor attention_mask, Scalar scale, float keep_prob, bool query_transpose=False, bool key_transpose=False, bool bmm_score_transpose_a=False, bool bmm_score_transpose_b=False, bool value_transpose=False, bool dx_transpose=False) -> Tensor
- func: npu_flash_attention_score(Tensor query_layer, Tensor key_layer, Tensor value_layer, *, Tensor? pse=None, Tensor? drop_mask=None, Tensor? padding_mask=None, Tensor? atten_mask=None, bool query_transpose=False, bool key_transpose=True, bool value_transpose=False, float scale=1., float keep_prob=1., bool is_transpose_out=True, int pre_tockens=INT_MAX, int next_tockens=INT_MAX) -> Tensor[]
op_api: True
@@ -0,0 +1,58 @@
// Copyright (c) 2023 Huawei Technologies Co., Ltd
// Copyright (c) 2019, Facebook CORPORATION.
// All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <torch/csrc/autograd/custom_function.h>
#include "torch_npu/csrc/framework/utils/OpAdapter.h"
#include "torch_npu/csrc/aten/NPUNativeOpApiFunctions.h"
#include "torch_npu/csrc/aten/ops/op_api/op_api_common.h"
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
namespace at_npu {
namespace native {
std::vector<at::Tensor> NPUNativeFunctions::npu_flash_attention_score_grad(
const at::Tensor &query,
const at::Tensor &key,
const at::Tensor &value,
const at::Tensor &dy,
const c10::optional<at::Tensor> &pse,
const c10::optional<at::Tensor> &drop_mask,
const c10::optional<at::Tensor> &padding_mask,
const c10::optional<at::Tensor> &atten_mask,
const c10::optional<at::Tensor> &softmax_max,
const c10::optional<at::Tensor> &softmax_sum,
const c10::optional<at::Tensor> &softmax_in,
const c10::optional<at::Tensor> &attention_in,
double scale_value,
double keep_prob,
bool query_transpose,
bool key_transpose,
bool value_transpose,
bool dy_transpose,
bool is_transpose_attention,
int64_t pre_tockens,
int64_t next_tockens)
{
return NPUNativeOpApiFunctions::npu_flash_attention_score_grad(query,
key, value, dy, pse, drop_mask, padding_mask, atten_mask,
softmax_max, softmax_sum, softmax_in, attention_in, scale_value,
keep_prob, query_transpose, key_transpose, value_transpose,
dy_transpose, is_transpose_attention, pre_tockens, next_tockens);
}
} // namespace native
} // namespace at_npu
@@ -0,0 +1,41 @@
// Copyright (c) 2023 Huawei Technologies Co., Ltd
// Copyright (c) 2019, Facebook CORPORATION.
// All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <torch/csrc/autograd/custom_function.h>
#include "torch_npu/csrc/framework/utils/OpAdapter.h"
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
#include "torch_npu/csrc/aten/NPUNativeOpApiFunctions.h"
#include "torch_npu/csrc/aten/ops/op_api/op_api_common.h"
namespace at_npu {
namespace native {
using torch::autograd::AutogradContext;
using torch::autograd::Function;
std::vector<at::Tensor> NPUNativeFunctions::npu_flash_attention_score(
const at::Tensor &query_layer, const at::Tensor &key_layer,
const at::Tensor &value_layer, const c10::optional<at::Tensor> &pse,
const c10::optional<at::Tensor> &drop_mask, const c10::optional<at::Tensor> &padding_mask,
const c10::optional<at::Tensor> &atten_mask, bool query_transpose, bool key_transpose, bool value_transpose,
double scale, double keep_prob, bool is_transpose_out, int64_t pre_tockens, int64_t next_tockens)
{
return NPUNativeOpApiFunctions::npu_flash_attention_score(
query_layer, key_layer, value_layer, pse, drop_mask, padding_mask,
atten_mask, query_transpose, key_transpose, value_transpose, scale, keep_prob,
is_transpose_out, pre_tockens, next_tockens);
}
} // namespace native
} // namespace at_npu
@@ -0,0 +1,69 @@
// Copyright (c) 2023 Huawei Technologies Co., Ltd
// Copyright (c) 2019, Facebook CORPORATION.
// All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <torch/csrc/autograd/custom_function.h>
#include "torch_npu/csrc/framework/utils/OpAdapter.h"
#include "torch_npu/csrc/aten/NPUNativeOpApiFunctions.h"
#include "torch_npu/csrc/aten/ops/op_api/op_api_common.h"
namespace at_npu {
namespace native {
std::vector<at::Tensor> NPUNativeOpApiFunctions::npu_flash_attention_score_grad(
const at::Tensor &query,
const at::Tensor &key,
const at::Tensor &value,
const at::Tensor &dy,
const c10::optional<at::Tensor> &pse,
const c10::optional<at::Tensor> &drop_mask,
const c10::optional<at::Tensor> &padding_mask,
const c10::optional<at::Tensor> &atten_mask,
const c10::optional<at::Tensor> &softmax_max,
const c10::optional<at::Tensor> &softmax_sum,
const c10::optional<at::Tensor> &softmax_in,
const c10::optional<at::Tensor> &attention_in,
double scale_value,
double keep_prob,
bool query_transpose,
bool key_transpose,
bool value_transpose,
bool dy_transpose,
bool is_transpose_attention,
int64_t pre_tockens,
int64_t next_tockens)
{
bool is_flash = true;
at::Tensor dq, dk, dv;
dq = OpPreparation::ApplyTensor(query);
dk = OpPreparation::ApplyTensor(key);
dv = OpPreparation::ApplyTensor(value);
EXEC_NPU_CMD_CLEAR_WORKSPACE(
aclnnFlashAttentionScoreGrad, query, key, value, dy, pse, drop_mask, padding_mask, atten_mask,
softmax_max, softmax_sum, softmax_in, attention_in, scale_value, keep_prob, query_transpose,
key_transpose, value_transpose, dy_transpose, is_transpose_attention, pre_tockens, next_tockens,
is_flash, dq, dk, dv);
return {dq, dk, dv,
at::Tensor(), at::Tensor(), at::Tensor(), at::Tensor(), at::Tensor(),
at::Tensor(), at::Tensor(), at::Tensor(), at::Tensor(), at::Tensor(),
at::Tensor(), at::Tensor(), at::Tensor(), at::Tensor(), at::Tensor()};
}
} // namespace native
} // namespace at_npu
@@ -0,0 +1,126 @@
// Copyright (c) 2023 Huawei Technologies Co., Ltd
// Copyright (c) 2019, Facebook CORPORATION.
// All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <torch/csrc/autograd/custom_function.h>
#include "torch_npu/csrc/framework/utils/OpAdapter.h"
#include "torch_npu/csrc/aten/NPUNativeOpApiFunctions.h"
#include "torch_npu/csrc/aten/ops/op_api/op_api_common.h"
namespace at_npu {
namespace native {
using torch::autograd::AutogradContext;
using torch::autograd::Function;
class NPUFlashAttentionScoreFunction : public torch::autograd::Function<NPUFlashAttentionScoreFunction> {
public:
static std::vector<at::Tensor> forward(
AutogradContext *ctx, const at::Tensor &query_layer, const at::Tensor &key_layer,
const at::Tensor &value_layer, const c10::optional<at::Tensor> &pse_opt,
const c10::optional<at::Tensor> &drop_mask_opt, const c10::optional<at::Tensor> &padding_mask_opt,
const c10::optional<at::Tensor> &atten_mask_opt, bool query_transpose, bool key_transpose, bool value_transpose,
double scale, double keep_prob, bool is_transpose_out, int64_t pre_tockens, int64_t next_tockens)
{
const at::Tensor &pse = pse_opt.value_or(at::Tensor());
const at::Tensor &padding_mask = padding_mask_opt.value_or(at::Tensor());
const at::Tensor &atten_mask = atten_mask_opt.value_or(at::Tensor());
const at::Tensor &drop_mask = drop_mask_opt.value_or(at::Tensor());
at::Tensor attention_score;
if (is_transpose_out) {
attention_score = OpPreparation::ApplyTensor(query_layer,
{query_layer.size(0), query_layer.size(2), query_layer.size(1) * query_layer.size(3)});
} else {
attention_score = OpPreparation::ApplyTensor(query_layer);
}
size_t dim = (query_layer.scalar_type() == at::ScalarType::Float) ? 8 : 16;
at::Tensor softmax_max = OpPreparation::ApplyTensor(query_layer,
{query_layer.size(0), query_layer.size(1), query_layer.size(2), dim});
at::Tensor softmax_sum = OpPreparation::ApplyTensor(query_layer,
{query_layer.size(0), query_layer.size(1), query_layer.size(2), dim});
bool is_flash = true;
at::Tensor softmax_out;
EXEC_NPU_CMD_CLEAR_WORKSPACE(aclnnFlashAttentionScore, query_layer, key_layer, value_layer,
pse_opt, drop_mask_opt, padding_mask_opt, atten_mask_opt,
query_transpose, key_transpose, value_transpose,
scale, keep_prob, is_transpose_out, pre_tockens, next_tockens, is_flash,
softmax_max, softmax_sum, softmax_out, attention_score);
at::AutoNonVariableTypeMode g;
ctx->save_for_backward({query_layer, key_layer, value_layer, softmax_max, softmax_sum, softmax_out,
pse, drop_mask, padding_mask, atten_mask, attention_score});
ctx->saved_data["is_flash"] = is_flash;
ctx->saved_data["scale"] = scale;
ctx->saved_data["keep_prob"] = keep_prob;
ctx->saved_data["query_transpose"] = query_transpose;
ctx->saved_data["key_transpose"] = key_transpose;
ctx->saved_data["pre_tockens"] = pre_tockens;
ctx->saved_data["next_tockens"] = next_tockens;
ctx->saved_data["value_transpose"] = value_transpose;
ctx->saved_data["is_transpose_out"] = is_transpose_out;
return {attention_score};
}
static std::vector<at::Tensor> backward(AutogradContext *ctx, std::vector<at::Tensor> grad_outputs)
{
auto scale = ctx->saved_data["scale"].toDouble();
auto keep_prob = ctx->saved_data["keep_prob"].toDouble();
auto query_transpose = ctx->saved_data["query_transpose"].toBool();
auto key_transpose = ctx->saved_data["key_transpose"].toBool();
auto value_transpose = ctx->saved_data["value_transpose"].toBool();
auto is_transpose_out = ctx->saved_data["is_transpose_out"].toBool();
auto pre_tockens = ctx->saved_data["pre_tockens"].toInt();
auto next_tockens = ctx->saved_data["next_tockens"].toInt();
auto is_flash = ctx->saved_data["is_flash"].toBool();
auto saved = ctx->get_saved_variables();
auto query = saved[0];
auto key = saved[1];
auto value = saved[2];
auto softmax_max = saved[3];
auto softmax_sum = saved[4];
auto softmax_out = saved[5];
auto pse = saved[6];
auto drop_mask = saved[7];
auto padding_mask = saved[8];
auto atten_mask = saved[9];
auto attention_score = saved[10];
bool dy_transpose = false;
return NPUNativeOpApiFunctions::npu_flash_attention_score_grad(query,
key, value, grad_outputs[0], pse, drop_mask, padding_mask, atten_mask,
softmax_max, softmax_sum, softmax_out, attention_score, scale,
keep_prob, query_transpose, key_transpose, value_transpose,
dy_transpose, is_transpose_out, pre_tockens, next_tockens);
}
};
std::vector<at::Tensor> NPUNativeOpApiFunctions::npu_flash_attention_score(
const at::Tensor &query_layer, const at::Tensor &key_layer,
const at::Tensor &value_layer, const c10::optional<at::Tensor> &pse,
const c10::optional<at::Tensor> &drop_mask, const c10::optional<at::Tensor> &padding_mask,
const c10::optional<at::Tensor> &atten_mask, bool query_transpose, bool key_transpose, bool value_transpose,
double scale, double keep_prob, bool is_transpose_out, int64_t pre_tockens, int64_t next_tockens)
{
return NPUFlashAttentionScoreFunction::apply(query_layer, key_layer, value_layer, pse, drop_mask, padding_mask,
atten_mask, query_transpose, key_transpose, value_transpose, scale, keep_prob,
is_transpose_out, pre_tockens, next_tockens);
}
} // namespace native
} // namespace at_npu
+61 -4
View File
@@ -62,12 +62,16 @@ inline const char *GetOpApiLibName(void) {
return "libopapi.so";
}
inline void *GetOpApiFuncAddr(const char *apiName) {
static auto handler = dlopen(GetOpApiLibName(), RTLD_LAZY);
inline const char *GetCustOpApiLibName(void) {
return "libcust_opapi.so";
}
inline void *GetOpApiFuncAddrInLib(const char *libName, const char *apiName) {
auto handler = dlopen(libName, RTLD_LAZY);
if (handler == nullptr) {
static bool firstOpen = true;
if (firstOpen) {
ASCEND_LOGW("dlopen %s failed, error:%s.", GetOpApiLibName(), dlerror());
ASCEND_LOGW("dlopen %s failed, error:%s.", libName, dlerror());
firstOpen = false;
}
return nullptr;
@@ -75,11 +79,19 @@ inline void *GetOpApiFuncAddr(const char *apiName) {
auto funcAddr = dlsym(handler, apiName);
if (funcAddr == nullptr) {
ASCEND_LOGW("dlsym %s from %s failed, error:%s.", apiName, GetOpApiLibName(), dlerror());
ASCEND_LOGW("dlsym %s from %s failed, error:%s.", apiName, libName, dlerror());
}
return funcAddr;
}
inline void *GetOpApiFuncAddr(const char *apiName) {
auto funcAddr = GetOpApiFuncAddrInLib(GetCustOpApiLibName(), apiName);
if (funcAddr != nullptr) {
return funcAddr;
}
return GetOpApiFuncAddrInLib(GetOpApiLibName(), apiName);
}
inline aclTensor *ConvertType(const at::Tensor &at_tensor) {
static const auto aclCreateTensor = GET_OP_API_FUNC(aclCreateTensor);
if (aclCreateTensor == nullptr) {
@@ -381,6 +393,51 @@ auto ConvertToOpApiFunc(const Tuple &params, void *opApiAddr) {
cmd.Run(); \
} while (false)
/**
* 异步调用npu执行, 无返回值.
*/
#define EXEC_NPU_CMD_CLEAR_WORKSPACE(aclnn_api, ...) \
do { \
static const auto getWorkspaceSizeFuncAddr = GetOpApiFuncAddr(#aclnn_api "GetWorkspaceSize"); \
static const auto opApiFuncAddr = GetOpApiFuncAddr(#aclnn_api); \
TORCH_CHECK(getWorkspaceSizeFuncAddr != nullptr && opApiFuncAddr != nullptr, \
#aclnn_api, " or ", #aclnn_api "GetWorkspaceSize", " not in ", GetOpApiLibName(), ", or ", \
GetOpApiLibName(), "not found."); \
TORCH_CHECK(at_npu::native::env::CheckForbidInternalFormat(), #aclnn_api ": Internal format not support,"\
" please set 'torch.npu.config.allow_internal_format=False'"); \
auto acl_stream = c10_npu::getCurrentNPUStream().stream(false); \
uint64_t workspace_size = 0; \
uint64_t *workspace_size_addr = &workspace_size; \
aclOpExecutor *executor = nullptr; \
aclOpExecutor **executor_addr = &executor; \
auto converted_params = ConvertTypes(__VA_ARGS__, workspace_size_addr, executor_addr); \
static auto getWorkspaceSizeFunc = ConvertToOpApiFunc(converted_params, getWorkspaceSizeFuncAddr); \
auto workspace_status = call(getWorkspaceSizeFunc, converted_params); \
TORCH_CHECK(workspace_status == 0, "call " #aclnn_api " failed, detail:", aclGetRecentErrMsg()); \
void *workspace_addr = nullptr; \
if (workspace_size != 0) { \
int deviceIdx = 0; \
NPU_CHECK_ERROR(aclrtGetDevice(&deviceIdx)); \
auto workspace_tensor = \
at::empty({static_cast<int64_t>(workspace_size)}, \
at::TensorOptions().device(at_npu::key::NativeDeviceType, deviceIdx).dtype(at::kByte)); \
workspace_addr = workspace_tensor.storage().data(); \
aclrtMemset(workspace_addr, workspace_size, 0, workspace_size); \
} \
auto acl_call = [converted_params, workspace_addr, workspace_size, acl_stream, executor]() -> int { \
typedef int(*OpApiFunc)(void*, uint64_t, aclOpExecutor*, const aclrtStream); \
OpApiFunc opApiFunc = reinterpret_cast<OpApiFunc>(opApiFuncAddr); \
auto api_ret = opApiFunc(workspace_addr, workspace_size, executor, acl_stream); \
TORCH_CHECK(api_ret == 0, "call " #aclnn_api " failed, detail:", aclGetRecentErrMsg()); \
ReleaseConvertTypes(converted_params); \
return api_ret; \
}; \
at_npu::native::OpCommand cmd; \
cmd.Name(#aclnn_api); \
cmd.SetCustomHandler(acl_call); \
cmd.Run(); \
} while (false)
template<typename Tuple>
class ConvertedParams {
public: