// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "contrib_ops/cpu/sparse/sparse_attention.h" #include "contrib_ops/cpu/sparse/sparse_attention_helper.h" #include "contrib_ops/cpu/bert/rotary_helper.h" #include "contrib_ops/cpu/bert/attention_utils.h" #include "contrib_ops/cpu/bert/rotary_embedding.h" #include "contrib_ops/cpu/bert/rotary_embedding_helper.h" #include "core/framework/tensorprotoutils.h" #include "core/graph/onnx_protobuf.h" #include "core/common/safeint.h" #include "core/platform/threadpool.h" #include #include using onnxruntime::concurrency::ThreadPool; namespace onnxruntime { namespace contrib { #define REGISTER_KERNEL_TYPED(T) \ ONNX_OPERATOR_TYPED_KERNEL_EX( \ SparseAttention, \ kMSDomain, \ 1, \ T, \ kCpuExecutionProvider, \ KernelDefBuilder() \ .TypeConstraint("T", DataTypeImpl::GetTensorType()) \ .TypeConstraint("M", DataTypeImpl::GetTensorType()), \ SparseAttention); REGISTER_KERNEL_TYPED(float) REGISTER_KERNEL_TYPED(MLFloat16) namespace { // Validate CSR row-pointer monotonicity and column-index range. // Must be called after CheckInputs has populated the parameters struct. Status ValidateCSRIndices(const SparseAttentionParameters& parameters, const Tensor& block_row_indices, const Tensor& block_col_indices) { const int num_layout = parameters.num_sparse_layout; const int max_blocks = parameters.stride_row_indices - 1; const int col_count = parameters.stride_col_indices; const int32_t* row_data = block_row_indices.Data(); const int32_t* col_data = block_col_indices.Data(); for (int l = 0; l < num_layout; ++l) { const int32_t* r = row_data + l * (max_blocks + 1); if (r[0] != 0) { return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "block_row_indices[", l, "][0] must be 0, got ", r[0]); } for (int i = 0; i < max_blocks; ++i) { if (r[i] < 0 || r[i] > r[i + 1] || r[i + 1] > col_count) { return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "block_row_indices values are not monotonically non-decreasing or exceed " "block_col_indices columns at layout ", l, " row ", i, ": r[", i, "]=", r[i], ", r[", i + 1, "]=", r[i + 1], ", col_count=", col_count); } } const int32_t* c = col_data + l * col_count; const int nnz = r[max_blocks]; for (int k = 0; k < nnz; ++k) { if (c[k] < 0 || c[k] >= max_blocks) { return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "block_col_indices[", l, "][", k, "]=", c[k], " is out of valid range [0, ", max_blocks, ")"); } } } return Status::OK(); } // Validate total_key_lengths element values. Status ValidateKeyLengths(const SparseAttentionParameters& parameters, const Tensor& total_key_lengths) { const int batch_size = parameters.batch_size; const int sequence_length = parameters.sequence_length; const int total_sequence_length = parameters.total_sequence_length; const auto* key_len_data = total_key_lengths.Data(); const bool is_prompt = (sequence_length == total_sequence_length); const int min_key_length = is_prompt ? 1 : sequence_length; for (int i = 0; i < batch_size; ++i) { const int key_length = key_len_data[i]; if (key_length < min_key_length || key_length > total_sequence_length) { return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "key_total_sequence_lengths value ", key_length, " at batch index ", i, " is out of range [", min_key_length, ", ", total_sequence_length, "]."); } } return Status::OK(); } } // namespace template SparseAttention::SparseAttention(const OpKernelInfo& info) : OpKernel(info), SparseAttentionBase(info) { } template Status SparseAttention::Compute(OpKernelContext* context) const { const Tensor* query = context->Input(0); const Tensor* key = context->Input(1); const Tensor* value = context->Input(2); const Tensor* past_key = context->Input(3); const Tensor* past_value = context->Input(4); const Tensor* block_row_indices = context->Input(5); const Tensor* block_col_indices = context->Input(6); const Tensor* total_seq_len = context->Input(7); const Tensor* total_key_lengths = context->Input(8); const Tensor* cos_cache = context->Input(9); const Tensor* sin_cache = context->Input(10); SparseAttentionParameters parameters = {}; // Parameters from node attribute shall be set before calling CheckInputs parameters.sparse_block_size = sparse_block_size_; parameters.num_heads = num_heads_; parameters.kv_num_heads = kv_num_heads_; parameters.scale = scale_; parameters.do_rotary = do_rotary_; parameters.rotary_interleaved = rotary_interleaved_; ORT_RETURN_IF_ERROR(sparse_attention_helper::CheckInputs(¶meters, query, key, value, past_key, past_value, cos_cache, sin_cache, block_row_indices, block_col_indices, total_key_lengths, total_seq_len)); ORT_RETURN_IF_ERROR(ValidateCSRIndices(parameters, *block_row_indices, *block_col_indices)); ORT_RETURN_IF_ERROR(ValidateKeyLengths(parameters, *total_key_lengths)); const int batch_size = parameters.batch_size; const int sequence_length = parameters.sequence_length; int q_hidden_size = parameters.hidden_size; std::vector output_shape(3); output_shape[0] = static_cast(batch_size); output_shape[1] = static_cast(sequence_length); output_shape[2] = static_cast(q_hidden_size); Tensor* output = context->Output(0, output_shape); constexpr bool past_present_share_buffer = true; // Only supports share buffer for past and present for now. parameters.past_present_share_buffer = past_present_share_buffer; int head_size = parameters.head_size; const int cache_length = past_present_share_buffer ? parameters.max_cache_sequence_length : parameters.total_sequence_length; std::vector present_k_shape({static_cast(batch_size), static_cast(kv_num_heads_), static_cast(cache_length), static_cast(head_size)}); std::vector present_v_shape({static_cast(batch_size), static_cast(kv_num_heads_), static_cast(cache_length), static_cast(head_size)}); Tensor* present_key = context->Output(1, present_k_shape); Tensor* present_value = context->Output(2, present_v_shape); // Check past and present share buffer. if (past_present_share_buffer) { ORT_ENFORCE(past_key->DataRaw() == present_key->DataRaw() && past_value->DataRaw() == present_value->DataRaw()); } AllocatorPtr allocator; ORT_RETURN_IF_ERROR(context->GetTempSpaceAllocator(&allocator)); auto element_type = DataTypeImpl::GetType(); OrtValue Q; OrtValue K; OrtValue V; const bool packed_qkv = parameters.is_packed_qkv; if (packed_qkv) { ORT_RETURN_IF_ERROR(MaybeTransposeToBNSH( allocator, batch_size, num_heads_ + 2 * kv_num_heads_, sequence_length, head_size, query, Q)); } else { ORT_RETURN_IF_ERROR(MaybeTransposeToBNSH( allocator, batch_size, num_heads_, sequence_length, head_size, query, Q)); ORT_RETURN_IF_ERROR(MaybeTransposeToBNSH( allocator, batch_size, kv_num_heads_, sequence_length, head_size, key, K)); ORT_RETURN_IF_ERROR(MaybeTransposeToBNSH( allocator, batch_size, kv_num_heads_, sequence_length, head_size, value, V)); } OrtValue RotaryQKV; OrtValue RotaryQ; OrtValue RotaryK; T* q_rotary = Q.GetMutable()->MutableData(); T* k_rotary = packed_qkv ? nullptr : K.GetMutable()->MutableData(); if (do_rotary_) { ORT_ENFORCE(cos_cache != nullptr && sin_cache != nullptr, "cos_cache and sin_cache must be provided when do_rotary is true"); rotary_embedding_helper::RotaryParameters rotary_params = {}; rotary_params.batch_size = batch_size; rotary_params.sequence_length = sequence_length; rotary_params.hidden_size = q_hidden_size; rotary_params.head_size = head_size; rotary_params.rotary_embedding_dim = parameters.rotary_dim; rotary_params.num_heads = num_heads_; rotary_params.max_sequence_length = parameters.max_rotary_sequence_length; rotary_params.seq_stride = head_size; rotary_params.head_stride = sequence_length * rotary_params.seq_stride; rotary_params.batch_stride = (packed_qkv ? (num_heads_ + 2 * kv_num_heads_) : num_heads_) * rotary_params.head_stride; rotary_params.position_ids_format = sequence_length == 1 ? 1 : 0; rotary_params.transposed = true; auto* tp = context->GetOperatorThreadPool(); const bool is_prompt = parameters.total_sequence_length == parameters.sequence_length; std::vector pos_ids(is_prompt ? 1 : batch_size * sequence_length); if (is_prompt) { pos_ids[0] = static_cast(0); } else if (sequence_length == 1) { for (int b = 0; b < batch_size; b++) { pos_ids[b] = static_cast(total_key_lengths->Data()[b]) - 1; } } else { // This supports a rare case that sequence_length > 1 when it is not prompt. for (int b = 0; b < batch_size; b++) { for (int s = 0; s < sequence_length; s++) { pos_ids[b * sequence_length + s] = static_cast(total_key_lengths->Data()[b]) - (sequence_length - s); } } } const T* q_input; const T* k_input; if (packed_qkv) { TensorShape qkv_shape({batch_size, num_heads_ + 2 * kv_num_heads_, sequence_length, head_size}); Tensor::InitOrtValue(element_type, qkv_shape, allocator, RotaryQKV); q_input = Q.Get().Data(); k_input = q_input + num_heads_ * sequence_length * head_size; q_rotary = RotaryQKV.GetMutable()->MutableData(); k_rotary = q_rotary + num_heads_ * sequence_length * head_size; } else { TensorShape q_shape({batch_size, num_heads_, sequence_length, head_size}); Tensor::InitOrtValue(element_type, q_shape, allocator, RotaryQ); TensorShape k_shape({batch_size, kv_num_heads_, sequence_length, head_size}); Tensor::InitOrtValue(element_type, k_shape, allocator, RotaryK); q_input = Q.Get().Data(); k_input = K.Get().Data(); q_rotary = RotaryQ.GetMutable()->MutableData(); k_rotary = RotaryK.GetMutable()->MutableData(); } ORT_RETURN_IF_ERROR(RunRotaryEmbedding(tp, rotary_params, q_input, pos_ids.data(), cos_cache->Data(), sin_cache->Data(), q_rotary, rotary_interleaved_)); rotary_params.num_heads = kv_num_heads_; rotary_params.hidden_size = parameters.kv_hidden_size; if (!packed_qkv) { rotary_params.batch_stride = kv_num_heads_ * rotary_params.head_stride; } ORT_RETURN_IF_ERROR(RunRotaryEmbedding(tp, rotary_params, k_input, pos_ids.data(), cos_cache->Data(), sin_cache->Data(), k_rotary, rotary_interleaved_)); if (packed_qkv) { const T* v_input = k_input + kv_num_heads_ * sequence_length * head_size; T* v_rotary = k_rotary + kv_num_heads_ * sequence_length * head_size; ORT_RETURN_IF_ERROR(rotary_helper::PackVIntoRotaryQKV(tp, parameters.batch_size, parameters.sequence_length, parameters.num_heads, parameters.kv_num_heads, parameters.head_size, v_input, v_rotary)); } } ORT_RETURN_IF_ERROR(context->GetTempSpaceAllocator(&allocator)); // Compute the attention score and apply the score to V return ApplyAttention(q_rotary, packed_qkv ? nullptr : k_rotary, packed_qkv ? nullptr : V.Get().Data(), past_key, past_value, output, present_key, present_value, total_key_lengths, block_row_indices, block_col_indices, parameters, allocator, context); } } // namespace contrib } // namespace onnxruntime