Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

[GPU] PagedAttention initial implementation (#26123)

Sergey Shlyapnikove5ede07536bf
diff --git a/src/bindings/python/src/openvino/runtime/utils/data_helpers/data_dispatcher.py b/src/bindings/python/src/openvino/runtime/utils/data_helpers/data_dispatcher.py
index dfd79b5aa76..bce10c9c377 100644
--- a/src/bindings/python/src/openvino/runtime/utils/data_helpers/data_dispatcher.py
+++ b/src/bindings/python/src/openvino/runtime/utils/data_helpers/data_dispatcher.py
@@ -7,7 +7,7 @@ from typing import Any, Dict, Union, Optional
import numpy as np
-from openvino._pyopenvino import ConstOutput, Tensor, Type
+from openvino._pyopenvino import ConstOutput, Tensor, Type, RemoteTensor
from openvino.runtime.utils.data_helpers.wrappers import _InferRequestWrapper, OVDict
ContainerTypes = Union[dict, list, tuple, OVDict]
@@ -61,6 +61,16 @@ def _(
return value
+@value_to_tensor.register(RemoteTensor)
+def _(
+ value: RemoteTensor,
+ request: Optional[_InferRequestWrapper] = None,
+ is_shared: bool = False,
+ key: Optional[ValidKeys] = None,
+) -> RemoteTensor:
+ return value
+
+
@value_to_tensor.register(np.ndarray)
def _(
value: np.ndarray,
diff --git a/src/bindings/python/src/pyopenvino/core/common.cpp b/src/bindings/python/src/pyopenvino/core/common.cpp
index 5d44bb74a11..a202c3a3801 100644
--- a/src/bindings/python/src/pyopenvino/core/common.cpp
+++ b/src/bindings/python/src/pyopenvino/core/common.cpp
@@ -10,6 +10,7 @@
#include "openvino/core/except.hpp"
#include "openvino/runtime/shared_buffer.hpp"
#include "openvino/util/common_util.hpp"
+#include "pyopenvino/core/remote_tensor.hpp"
#define C_CONTIGUOUS py::detail::npy_api::constants::NPY_ARRAY_C_CONTIGUOUS_
@@ -565,7 +566,13 @@ ov::PartialShape partial_shape_from_list(const py::list& shape) {
}
const ov::Tensor& cast_to_tensor(const py::handle& tensor) {
- return tensor.cast<const ov::Tensor&>();
+ if (py::isinstance<ov::Tensor>(tensor)) {
+ return tensor.cast<const ov::Tensor&>();
+ } else if (py::isinstance<RemoteTensorWrapper>(tensor)) {
+ return tensor.cast<const RemoteTensorWrapper&>().tensor;
+ }
+
+ throw py::type_error("Unable to cast " + std::string(py::str(tensor.get_type())) + " object to ov::Tensor");
}
void set_request_tensors(ov::InferRequest& request, const py::dict& inputs) {
diff --git a/src/plugins/intel_gpu/include/intel_gpu/graph/network.hpp b/src/plugins/intel_gpu/include/intel_gpu/graph/network.hpp
index f7f2099ac56..b33bd37807a 100644
--- a/src/plugins/intel_gpu/include/intel_gpu/graph/network.hpp
+++ b/src/plugins/intel_gpu/include/intel_gpu/graph/network.hpp
@@ -187,7 +187,7 @@ public:
void validate_primitives();
void set_arguments();
// Implementation specific calls
- bool is_cpu_impl(const primitive_id& id) const;
+ bool does_node_need_lockable_output(const primitive_id& id) const;
std::shared_ptr<primitive_inst> get_primitive(const primitive_id& id);
std::shared_ptr<const primitive_inst> get_primitive(const primitive_id& id) const;
std::string get_primitive_info(const primitive_id& id) const;
diff --git a/src/plugins/intel_gpu/include/intel_gpu/plugin/primitives_list.hpp b/src/plugins/intel_gpu/include/intel_gpu/plugin/primitives_list.hpp
index 408f3dfb7cf..5ada8907304 100644
--- a/src/plugins/intel_gpu/include/intel_gpu/plugin/primitives_list.hpp
+++ b/src/plugins/intel_gpu/include/intel_gpu/plugin/primitives_list.hpp
@@ -290,3 +290,4 @@ REGISTER_FACTORY(internal, SDPA);
REGISTER_FACTORY(internal, IndirectSDPA);
REGISTER_FACTORY(internal, RoPE);
REGISTER_FACTORY(internal, DynamicQuantize);
+REGISTER_FACTORY(internal, PagedAttentionExtension);
diff --git a/src/plugins/intel_gpu/include/intel_gpu/primitives/paged_attention.hpp b/src/plugins/intel_gpu/include/intel_gpu/primitives/paged_attention.hpp
new file mode 100644
index 00000000000..f87f608597a
--- /dev/null
+++ b/src/plugins/intel_gpu/include/intel_gpu/primitives/paged_attention.hpp
@@ -0,0 +1,53 @@
+// Copyright (C) 2023 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+#include "primitive.hpp"
+#include "intel_gpu/graph/program.hpp"
+#include "intel_gpu/runtime/optionals.hpp"
+
+#include <vector>
+
+namespace cldnn {
+
+struct paged_attention : public primitive_base<paged_attention> {
+ CLDNN_DECLARE_PRIMITIVE(paged_attention)
+
+ static constexpr size_t block_size = 16;
+
+ paged_attention() : primitive_base("", {}) {}
+
+ paged_attention(const primitive_id& id,
+ const std::vector<input_info>& inputs)
+ : primitive_base(id, inputs) {
+ OPENVINO_ASSERT(inputs.size() == 13, "[GPU] Unexpected inputs number for PagedAttention primitive: ", inputs.size());
+ }
+
+ bool operator==(const primitive& rhs) const override {
+ return compare_common_params(rhs);
+ }
+
+ void save(BinaryOutputBuffer& ob) const override {
+ primitive_base<paged_attention>::save(ob);
+ ob << head_size;
+ ob << heads_num;
+ ob << kv_heads_num;
+ ob << has_alibi;
+ }
+
+ void load(BinaryInputBuffer& ib) override {
+ primitive_base<paged_attention>::load(ib);
+ ib >> head_size;
+ ib >> heads_num;
+ ib >> kv_heads_num;
+ ib >> has_alibi;
+ }
+
+ optional_value<float> scale_val{};
+ size_t head_size = 0;
+ size_t heads_num = 0;
+ size_t kv_heads_num = 0;
+ bool has_alibi = false;
+};
+} // namespace cldnn
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl/multi_stage_primitive.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl/multi_stage_primitive.hpp
index c335fabc117..91fb69376f4 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl/multi_stage_primitive.hpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl/multi_stage_primitive.hpp
@@ -54,6 +54,7 @@ struct multi_stage_primitive : public typed_primitive_impl<PType> {
this->can_reuse_memory = other.can_reuse_memory;
this->can_share_kernels = other.can_share_kernels;
this->_kernel_name = other._kernel_name;
+ this->can_reuse_memory = other.can_reuse_memory;
this->_is_dynamic = other._is_dynamic;
}
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl/paged_attention.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl/paged_attention.cpp
new file mode 100644
index 00000000000..e7a64185969
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl/paged_attention.cpp
@@ -0,0 +1,485 @@
+// Copyright (C) 2023-2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "intel_gpu/plugin/multi_tensor_variable_state.hpp"
+#include "intel_gpu/plugin/variable_state.hpp"
+#include "intel_gpu/runtime/debug_configuration.hpp"
+#include "intel_gpu/runtime/memory.hpp"
+
+#include "multi_stage_primitive.hpp"
+#include "paged_attention_inst.h"
+
+#include "sdpa/sdpa_kernel_base.h"
+#include "sdpa/sdpa_kernel_selector.h"
+#include "sdpa/pa_kv_cache_update_kernel_ref.h"
+#include "sdpa/pa_sdpa_kernel_opt.h"
+
+namespace cldnn {
+namespace ocl {
+
+struct paged_attention_impl : multi_stage_primitive<paged_attention> {
+ using parent = multi_stage_primitive<paged_attention>;
+ using parent::parent;
+
+ using sdpa_kernel_selector_t = kernel_selector::sdpa_kernel_selector;
+ using sdpa_kernel_params_t = kernel_selector::sdpa_params;
+
+ using pa_sdpa_kernel_selector_t = kernel_selector::pa_sdpa_kernel_selector;
+ using pa_sdpa_kernel_params_t = kernel_selector::pa_sdpa_params;
+
+ using kv_cache_update_kernel_selector_t = kernel_selector::kv_cache_update_kernel_selector;
+ using kv_cache_update_kernel_params_t = kernel_selector::kv_cache_update_params;
+
+ DECLARE_OBJECT_TYPE_SERIALIZATION(cldnn::ocl::paged_attention_impl)
+
+ std::unique_ptr<primitive_impl> clone() const override {
+ return make_unique<paged_attention_impl>(*this);
+ }
+
+ paged_attention_impl() = default;
+
+ paged_attention_impl(const std::vector<kernel_selector::kernel_data>& kd) : parent(kd) {
+ this->can_reuse_memory = true;
+ }
+
+ void set_arguments_impl(paged_attention_inst& instance) override {}
+ kernel_arguments_data get_arguments(const paged_attention_inst& instance, size_t stage) const override { return kernel_arguments_data(); }
+
+ enum Stage {
+ KV_CACHE_UPDATE,
+ SDPA,
+ PA_SDPA,
+ };
+
+ void load(BinaryInputBuffer& ib) override {
+ parent::load(ib);
+ if (is_dynamic()) {
+ auto& kv_cache_update_kernel_selector = kv_cache_update_kernel_selector_t::Instance();
+ auto kv_cache_update_kernel_impl = kv_cache_update_kernel_selector.GetImplementation(_kernels_data[Stage::KV_CACHE_UPDATE].kernelName);
+ kv_cache_update_kernel_impl->GetUpdateDispatchDataFunc(_kernels_data[Stage::KV_CACHE_UPDATE]);
+
+ auto& sdpa_kernel_selector = sdpa_kernel_selector_t::Instance();
+ auto sdpa_kernel_impl = sdpa_kernel_selector.GetImplementation(_kernels_data[Stage::SDPA].kernelName);
+ sdpa_kernel_impl->GetUpdateDispatchDataFunc(_kernels_data[Stage::SDPA]);
+
+ auto& pa_sdpa_kernel_selector = pa_sdpa_kernel_selector_t::Instance();
+ auto pa_sdpa_kernel_impl = pa_sdpa_kernel_selector.GetImplementation(_kernels_data[Stage::PA_SDPA].kernelName);
+ pa_sdpa_kernel_impl->GetUpdateDispatchDataFunc(_kernels_data[Stage::PA_SDPA]);
+ }
+ }
+
+ std::vector<layout> get_internal_buffer_layouts_impl() const override {
+ auto add_internal_buffers = [](std::vector<layout>& layouts, const kernel_selector::KernelData& kd) {
+ if (kd.internalBufferSizes.empty())
+ return;
+
+ auto dtype = from_data_type(kd.internalBufferDataType);
+ const auto bpp = data_type_traits::size_of(dtype);
+ for (auto size : kd.internalBufferSizes) {
+ layout inbuf_layout = {dtype, format::bfyx, // simple linear format (flattern to x channel)
+ {1, 1, 1, (tensor::value_type)(size / bpp)}};
+ layouts.push_back(inbuf_layout);
+ }
+ };
+
+ std::vector<layout> layouts;
+ add_internal_buffers(layouts, _kernels_data[Stage::SDPA]);
+ add_internal_buffers(layouts, _kernels_data[Stage::PA_SDPA]);
+
+ return layouts;
+ }
+
+ kernel_arguments_data get_arguments(const paged_attention_inst& instance, size_t stage, size_t kernel_idx) const {
+ const auto desc = instance.get_node().as<paged_attention>().get_primitive();
+
+ kernel_arguments_data args;
+ if (stage == Stage::KV_CACHE_UPDATE || stage == Stage::SDPA || (stage == Stage::PA_SDPA && kernel_idx == 0))
+ args.shape_info = instance.shape_info_memory_ptr();
+
+ if (stage == Stage::KV_CACHE_UPDATE) {
+ args.inputs = { instance.key_memory_ptr(),
+ instance.value_memory_ptr(),
+ instance.past_lens_memory_ptr(),
+ instance.block_indices_memory_ptr(),
+ instance.block_indices_begins_memory_ptr() };
+
+ args.outputs = { instance.key_cache_memory_ptr(),
+ instance.value_cache_memory_ptr() };
+ } else if (stage == Stage::SDPA) {
+ args.inputs = { instance.input_memory_ptr(0),
+ instance.key_memory_ptr(),
+ instance.value_memory_ptr(),
+ instance.subsequence_begins_memory_ptr() };
+
+ if (desc->has_alibi) {
+ args.inputs.push_back(instance.alibi_memory_ptr());
+ }
+
+ args.outputs = { instance.output_memory_ptr(0) };
+ } else if (stage == Stage::PA_SDPA) {
+ if (kernel_idx == 0) {
+ args.inputs = { instance.input_memory_ptr(0),
+ instance.key_cache_memory_ptr(),
+ instance.value_cache_memory_ptr(),
+ instance.past_lens_memory_ptr(),
+ instance.block_indices_memory_ptr(),
+ instance.block_indices_begins_memory_ptr() };
+
+ if (desc->has_alibi) {
+ args.inputs.push_back(instance.alibi_memory_ptr());
+ }
+ } else {
+ args.inputs = { instance.past_lens_memory_ptr(), };
+ }
+
+ args.outputs = { instance.output_memory_ptr(0) };
+ }
+
+ return args;
+ }
+
+ std::set<size_t> get_lockable_internal_buffers() const override {
+ return std::set<size_t>{ 0, 1, 2 }; /* SDPA and KV_CACHE_UPDATE indexes configuration */
+ };
+
+ void execute_stage(const std::vector<event::ptr>& events, paged_attention_inst& instance, std::vector<event::ptr>& all_events, size_t stage) {
+ stream& stream = instance.get_network().get_stream();
+ std::vector<event::ptr> tmp_events(events);
+ size_t kernel_offset = 0;
+ for (size_t s = 0; s < stage; s++) {
+ kernel_offset += _kernels_data[s].kernels.size();
+ }
+
+ // Stages SDPA and KV_CACHE_UPDATE reuse the same internal buffers at prefill stage
+ size_t internal_buffers_offset = 0;
+ size_t internal_buffers_count = 0;
+ if (stage == Stage::PA_SDPA) {
+ internal_buffers_offset = _kernels_data[Stage::SDPA].internalBufferSizes.size();
+ internal_buffers_count = _kernels_data[Stage::PA_SDPA].internalBufferSizes.size();
+ } else {
+ internal_buffers_count = _kernels_data[Stage::SDPA].internalBufferSizes.size();
+ }
+
+ for (size_t kd_idx = 0; kd_idx < _kernels_data[stage].kernels.size(); ++kd_idx) {
+ if (_kernels_data[stage].kernels[kd_idx].skip_execution)
+ continue;
+
+ size_t idx_final = kernel_offset + kd_idx;
+ // If any user of the prim's users is CPU implementation or network's output, set prim as a output event (event won't be nullptr)
+ bool needs_completion_event = instance.needs_completion_event();
+
+ auto& params = _kernels_data[stage].kernels[kd_idx].params;
+
+ auto args = get_arguments(instance, stage, kd_idx);
+ args.scalars = &params.scalars;
+
+ const auto& intermediate_memories = instance.get_intermediates_memories();
+ args.intermediates.insert(args.intermediates.end(),
+ intermediate_memories.begin() + internal_buffers_offset,
+ intermediate_memories.begin() + internal_buffers_offset + internal_buffers_count);
+
+ stream.set_arguments(*_kernels[idx_final], _kernels_data[stage].kernels[kd_idx].params, args);
+
+ const auto& gws = params.workGroups.global;
+ const auto& lws = params.workGroups.local;
+
+ GPU_DEBUG_TRACE_DETAIL << "Enqueue stage " << stage << " kernel " << idx_final << ": gws=[" << gws[0] << ", " << gws[1] << ", " << gws[2] << "] "
+ << "lws=[" << lws[0] << ", " << lws[1] << ", " << lws[2] << "]"
+ << (needs_completion_event ? " has_completion_event=true" : "") << std::endl;
+
+ auto ev = stream.enqueue_kernel(*_kernels[idx_final], params, args, tmp_events, needs_completion_event);
+ if (_kernels_data[stage].needs_sub_kernels_sync) {
+ tmp_events = {ev};
+ }
+
+ all_events.push_back(ev);
+ }
+ }
+
+ event::ptr execute_impl(const std::vector<event::ptr>& events, paged_attention_inst& instance) override {
+ std::vector<event::ptr> res_events;
+
+ execute_stage(events, instance, res_events, Stage::KV_CACHE_UPDATE);
+
+ std::vector<event::ptr> dep_events(res_events.begin(), res_events.end());
+ if (is_prefill_stage(*instance.get_impl_params())) {
+ execute_stage(dep_events, instance, res_events, Stage::SDPA);
+ } else {
+ execute_stage(dep_events, instance, res_events, Stage::PA_SDPA);
+ }
+
+ return aggregate_events(res_events, instance.get_network().get_stream(), res_events.size() > 1);
+ }
+
+ static kernel_selector::sdpa_configuration get_sdpa_configuration(const kernel_impl_params& impl_param) {
+ kernel_selector::sdpa_configuration config;
+
+ const auto desc = impl_param.typed_desc<paged_attention>();
+ config.head_size = desc->head_size;
+ config.heads_num = desc->heads_num;
+ config.kv_heads_num = desc->kv_heads_num;
+ config.has_alibi_input = desc->has_alibi;
+ config.is_causal = true;
+ config.is_paged_attention = true;
+ config.paged_attention_block_size = static_cast<int64_t>(paged_attention::block_size);
+
+ if (desc->scale_val.has_value()) {
+ config.has_scale_val = true;
+ config.scale_val = desc->scale_val.value();
+ }
+
+ if (desc->heads_num != desc->kv_heads_num) {
+ config.broadcast_axis = 1;
+ config.group_size = desc->heads_num / desc->kv_heads_num;
+ }
+
+ return config;
+ }
+
+ static kv_cache_update_kernel_params_t get_kv_cache_update_kernel_params(const kernel_impl_params& impl_param, bool is_dynamic = false) {
+ auto params = get_default_params<kv_cache_update_kernel_params_t>(impl_param, is_dynamic);
+
+ const auto& key_layout = impl_param.get_input_layout(1);
+ const auto& value_layout = impl_param.get_input_layout(2);
+ const auto& key_cache_layout = impl_param.get_input_layout(3);
+ const auto& value_cache_layout = impl_param.get_input_layout(4);
+ const auto& past_lens_layout = impl_param.get_input_layout(5);
+ const auto& block_indices_layout = impl_param.get_input_layout(7);
+ const auto& block_indices_begins_layout = impl_param.get_input_layout(8);
+
+ const auto inputs_number = 5;
+ const auto outputs_number = 2;
+ params.inputs.resize(inputs_number);
+ params.outputs.resize(outputs_number);
+ params.inputs[0] = convert_data_tensor(key_layout);
+ params.inputs[1] = convert_data_tensor(value_layout);
+ params.inputs[2] = convert_data_tensor(past_lens_layout);
+ params.inputs[3] = convert_data_tensor(block_indices_layout);
+ params.inputs[4] = convert_data_tensor(block_indices_begins_layout);
+ params.outputs[0] = convert_data_tensor(key_cache_layout);
+ params.outputs[1] = convert_data_tensor(value_cache_layout);
+
+ params.conf = get_sdpa_configuration(impl_param);
+
+ const auto& in_offsets_map = impl_param.in_port_to_shape_info_offset;
+ std::map<size_t, size_t> in_tensor_to_offset_map = {
+ {0, in_offsets_map.at(1)},
+ {1, in_offsets_map.at(2)},
+ {2, in_offsets_map.at(5)},
+ {3, in_offsets_map.at(7)},
+ {4, in_offsets_map.at(8)},
+ };
+ std::map<size_t, size_t> out_tensor_to_offset_map = {
+ {0, in_offsets_map.at(3)},
+ {1, in_offsets_map.at(4)},
+ };
+
+ params.set_dynamic_shape_offsets(in_tensor_to_offset_map, out_tensor_to_offset_map);
+
+ return params;
+ }
+
+ static sdpa_kernel_params_t get_sdpa_kernel_params(const kernel_impl_params& impl_param, bool is_dynamic = false) {
+ auto params = get_default_params<sdpa_kernel_params_t>(impl_param, is_dynamic);
+
+ const auto& query_layout = impl_param.get_input_layout(0);
+ const auto& key_layout = impl_param.get_input_layout(1);
+ const auto& value_layout = impl_param.get_input_layout(2);
+ const auto& subsequence_begins_layout = impl_param.get_input_layout(6);
+ const auto& alibi_layout = impl_param.get_input_layout(11);
+ const auto has_alibi = alibi_layout.count() > 0;
+
+ auto inputs_number = 4;
+ if (has_alibi)
+ inputs_number++;
+
+ auto input_idx = 0;
+ params.inputs.resize(inputs_number);
+ params.inputs[input_idx++] = convert_data_tensor(query_layout);
+ params.inputs[input_idx++] = convert_data_tensor(key_layout);
+ params.inputs[input_idx++] = convert_data_tensor(value_layout);
+ params.inputs[input_idx++] = convert_data_tensor(subsequence_begins_layout);
+
+ if (has_alibi)
+ params.inputs[input_idx++] = convert_data_tensor(alibi_layout);
+
+ params.conf = get_sdpa_configuration(impl_param);
+
+ const auto& in_offsets_map = impl_param.in_port_to_shape_info_offset;
+ const auto& out_offsets_map = impl_param.out_port_to_shape_info_offset;
+ std::map<size_t, size_t> in_tensor_to_offset_map = {
+ {0, in_offsets_map.at(0)},
+ {1, in_offsets_map.at(1)},
+ {2, in_offsets_map.at(2)},
+ {3, in_offsets_map.at(6)},
+ };
+ std::map<size_t, size_t> out_tensor_to_offset_map = {
+ {0, out_offsets_map.at(0)},
+ };
+
+ if (has_alibi)
+ in_tensor_to_offset_map.insert({4, in_offsets_map.at(11)});
+
+ if (is_prefill_stage(impl_param) && !is_dynamic) {
+ auto get_aligned_seq_len = [&](int64_t target_seq_len_block_size = 16) {
+ // Since at prefill stage Q, K, V inputs may contain multiple sequences with arbitrary
+ // target sequence lengths each (shape is [sequences_num * target_seq_len, num_heads * head_size]),
+ // to apply blocking to the first dimension (target_seq_len of each sequence), we need to calculate aligned total
+ // target sequence length for proper kernel dispatching
+ // For instance, if input contains two sequences with 35 and 28 sequence lengths each,
+ // the Q, K, V inputs at prefill stage will have shapes [35 + 28, num_heads * head_size]; considering kernel's
+ // target_seq_len_block_size equals 16, we need to launch kernel instances for the following ranges:
+ // [0, 15], [16, 31], [32, 34], [35, 50], [51, 62], so aligned target_seq_len_block_size should be 5 * 16 = 80,
+ // and 5 kernels instances should be launched (for each range, some of them containing leftovers)
+ //
+ // In general, to obtain length for each sequence, we have to parse subsequence_begins input,
+ // which contains begin and end indexes for each sequence (for above example it will contain three values: {0, 35, 63})
+ // However, as long as kernel's target_seq_len_block_size matches with vLLM's block_size,
+ // we can reuse block_indices_shape[0] size to determine total aligned sequences length size, avoiding
+ // memory access at runtime, because vLLM internally uses similar logic to configure blocks for KV cache
+
+ int64_t aligned_seq_len = 0;
+ const auto desc = impl_param.typed_desc<paged_attention>();
+ if (static_cast<int64_t>(paged_attention::block_size) == target_seq_len_block_size) {
+ const auto block_indices_input_idx = 7;
+ const auto& block_indices_ps = impl_param.get_input_layout(block_indices_input_idx).get_partial_shape();
+
+ aligned_seq_len = block_indices_ps[0].get_length() * target_seq_len_block_size;
+ } else {
+ const auto& input_mem = impl_param.memory_deps;
+ const auto subsequence_begins_mem = input_mem.at(6);
+ mem_lock<int32_t, mem_lock_type::read> subsequence_begins_mem_lock(subsequence_begins_mem, *impl_param.strm);
+
+ for (size_t i = 0; i < subsequence_begins_mem_lock.size() - 1; i++) {
+ auto prompt_length = subsequence_begins_mem_lock[i + 1] - subsequence_begins_mem_lock[i];
+ aligned_seq_len += align_to(prompt_length, target_seq_len_block_size);
+ }
+ }
+
+ return aligned_seq_len;
+ };
+
+ params.conf.paged_attention_aligned_seq_len = get_aligned_seq_len();
+ }
+
+ params.set_dynamic_shape_offsets(in_tensor_to_offset_map, out_tensor_to_offset_map);
+
+ return params;
+ }
+
+ static pa_sdpa_kernel_params_t get_pa_sdpa_params(const kernel_impl_params& impl_param, bool is_dynamic = false) {
+ auto params = get_default_params<pa_sdpa_kernel_params_t>(impl_param, is_dynamic);
+
+ const auto& query_layout = impl_param.get_input_layout(0);
+ const auto& key_cache_layout = impl_param.get_input_layout(3);
+ const auto& value_cache_layout = impl_param.get_input_layout(4);
+ const auto& past_lens_layout = impl_param.get_input_layout(5);
+ const auto& block_indices_layout = impl_param.get_input_layout(7);
+ const auto& block_indices_begins_layout = impl_param.get_input_layout(8);
+ const auto& alibi_layout = impl_param.get_input_layout(11);
+ const auto has_alibi = alibi_layout.count() > 0;
+
+ auto inputs_number = 6;
+ if (has_alibi)
+ inputs_number++;
+
+ auto input_idx = 0;
+ params.inputs.resize(inputs_number);
+ params.inputs[input_idx++] = convert_data_tensor(query_layout);
+ params.inputs[input_idx++] = convert_data_tensor(key_cache_layout);
+ params.inputs[input_idx++] = convert_data_tensor(value_cache_layout);
+ params.inputs[input_idx++] = convert_data_tensor(past_lens_layout);
+ params.inputs[input_idx++] = convert_data_tensor(block_indices_layout);
+ params.inputs[input_idx++] = convert_data_tensor(block_indices_begins_layout);
+ params.conf = get_sdpa_configuration(impl_param);
+
+ if (has_alibi)
+ params.inputs[input_idx++] = convert_data_tensor(alibi_layout);
+
+ if (!is_prefill_stage(impl_param) && !is_dynamic) {
+ const auto& input_mem = impl_param.memory_deps;
+ const auto max_context_len = input_mem.at(12);
+ mem_lock<int32_t, mem_lock_type::read> max_context_len_mem_lock(max_context_len, *impl_param.strm);
+ params.max_context_len = max_context_len_mem_lock[0];
+ }
+
+ const auto& in_offsets_map = impl_param.in_port_to_shape_info_offset;
+ const auto& out_offsets_map = impl_param.out_port_to_shape_info_offset;
+
+ std::map<size_t, size_t> in_tensor_to_offset_map = {
+ {0, in_offsets_map.at(0)},
+ {1, in_offsets_map.at(3)},
+ {2, in_offsets_map.at(4)},
+ {3, in_offsets_map.at(5)},
+ {4, in_offsets_map.at(7)},
+ {5, in_offsets_map.at(8)},
+ };
+ std::map<size_t, size_t> out_tensor_to_offset_map = {
+ {0, out_offsets_map.at(0)},
+ };
+
+ if (has_alibi)
+ in_tensor_to_offset_map.insert({6, in_offsets_map.at(11)});
+
+ params.set_dynamic_shape_offsets(in_tensor_to_offset_map, out_tensor_to_offset_map);
+
+ return params;
+ }
+
+ void update_dispatch_data(const kernel_impl_params& impl_param) override {
+ auto kv_cache_update_kernel_params = get_kv_cache_update_kernel_params(impl_param, impl_param.is_dynamic());
+ (_kernels_data[Stage::KV_CACHE_UPDATE].update_dispatch_data_func)(kv_cache_update_kernel_params, _kernels_data[Stage::KV_CACHE_UPDATE]);
+
+ if (is_prefill_stage(impl_param)) {
+ auto sdpa_kernel_params = get_sdpa_kernel_params(impl_param, impl_param.is_dynamic());
+ (_kernels_data[Stage::SDPA].update_dispatch_data_func)(sdpa_kernel_params, _kernels_data[Stage::SDPA]);
+ } else {
+ auto pa_sdpa_kernel_params = get_pa_sdpa_params(impl_param, impl_param.is_dynamic());
+ (_kernels_data[Stage::PA_SDPA].update_dispatch_data_func)(pa_sdpa_kernel_params, _kernels_data[Stage::PA_SDPA]);
+ }
+ }
+
+ static std::unique_ptr<primitive_impl> create(const typed_program_node<paged_attention>& arg, const kernel_impl_params& impl_param) {
+ std::vector<kernel_selector::kernel_data> kernels_data;
+
+ auto kv_cache_update_kernel_params = get_kv_cache_update_kernel_params(impl_param, impl_param.is_dynamic());
+ auto& kv_cache_update_kernel_selector = kv_cache_update_kernel_selector_t::Instance();
+ kernels_data.push_back(kv_cache_update_kernel_selector.get_best_kernel(kv_cache_update_kernel_params));
+
+ auto sdpa_kernel_params = get_sdpa_kernel_params(impl_param, impl_param.is_dynamic());
+ auto& sdpa_kernel_selector = sdpa_kernel_selector_t::Instance();
+ kernels_data.push_back(sdpa_kernel_selector.get_best_kernel(sdpa_kernel_params));
+
+ auto pa_sdpa_kernel_params = get_pa_sdpa_params(impl_param, impl_param.is_dynamic());
+ auto& pa_sdpa_kernel_selector = pa_sdpa_kernel_selector_t::Instance();
+ kernels_data.push_back(pa_sdpa_kernel_selector.get_best_kernel(pa_sdpa_kernel_params));
+
+ return cldnn::make_unique<paged_attention_impl>(kernels_data);
+ }
+};
+
+namespace detail {
+
+attach_paged_attention_impl::attach_paged_attention_impl() {
+ auto types = { data_types::f16, data_types::f32 };
+ auto formats = { format::bfyx };
+ implementation_map<paged_attention>::add(impl_types::ocl,
+ shape_types::dynamic_shape,
+ paged_attention_impl::create,
+ types,
+ formats);
+
+ implementation_map<paged_attention>::add(impl_types::ocl,
+ shape_types::static_shape,
+ paged_attention_impl::create,
+ types,
+ formats);
+}
+
+} // namespace detail
+} // namespace ocl
+} // namespace cldnn
+
+BIND_BINARY_BUFFER_WITH_TYPE(cldnn::ocl::paged_attention_impl)
+BIND_BINARY_BUFFER_WITH_TYPE(cldnn::paged_attention)
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl/register.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl/register.cpp
index 07f409ab052..7b8163120d1 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl/register.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl/register.cpp
@@ -40,6 +40,7 @@ void register_implementations() {
REGISTER_OCL(grid_sample);
REGISTER_OCL(group_normalization);
REGISTER_OCL(kv_cache);
+ REGISTER_OCL(paged_attention);
REGISTER_OCL(lrn);
REGISTER_OCL(lstm_elt);
REGISTER_OCL(multiclass_nms);
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl/register.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl/register.hpp
index a0933a3ab58..c7cf4ca7bb3 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl/register.hpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl/register.hpp
@@ -74,6 +74,7 @@
#include "intel_gpu/primitives/non_zero.hpp"
#include "intel_gpu/primitives/eye.hpp"
#include "intel_gpu/primitives/unique.hpp"
+#include "intel_gpu/primitives/paged_attention.hpp"
#include "intel_gpu/primitives/kv_cache.hpp"
#include "intel_gpu/primitives/scaled_dot_product_attention.hpp"
#include "intel_gpu/primitives/rope.hpp"
@@ -122,6 +123,7 @@ REGISTER_OCL(generate_proposals);
REGISTER_OCL(grid_sample);
REGISTER_OCL(group_normalization);
REGISTER_OCL(kv_cache);
+REGISTER_OCL(paged_attention);
REGISTER_OCL(lrn);
REGISTER_OCL(lstm_elt);
REGISTER_OCL(multiclass_nms);
diff --git a/src/plugins/intel_gpu/src/graph/include/paged_attention_inst.h b/src/plugins/intel_gpu/src/graph/include/paged_attention_inst.h
new file mode 100644
index 00000000000..5fec71ba942
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/include/paged_attention_inst.h
@@ -0,0 +1,68 @@
+// Copyright (C) 2023 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "intel_gpu/primitives/paged_attention.hpp"
+#include "primitive_inst.h"
+
+namespace cldnn {
+
+bool is_prefill_stage(const kernel_impl_params& impl_param);
+
+template <>
+struct typed_program_node<paged_attention> : public typed_program_node_base<paged_attention> {
+private:
+ using parent = typed_program_node_base<paged_attention>;
+
+public:
+ using parent::parent;
+
+ std::set<size_t> get_lockable_input_ids() const override {
+ return { 6 /* subsequence_begins */, 12 /* max_context_len */ };
+ }
+
+ std::vector<size_t> get_shape_infer_dependencies() const override {
+ return { 6 /* subsequence_begins */, 12 /* max_context_len */ };
+ }
+};
+
+using paged_attention_node = typed_program_node<paged_attention>;
+
+template<>
+class typed_primitive_inst<paged_attention> : public typed_primitive_inst_base<paged_attention> {
+ using parent = typed_primitive_inst_base<paged_attention>;
+
+public:
+ template<typename ShapeType>
+ static std::vector<layout> calc_output_layouts(paged_attention_node const& /*node*/, const kernel_impl_params& impl_param);
+ static layout calc_output_layout(const paged_attention_node& node, kernel_impl_params const& impl_param);
+
+ static std::string to_string(const paged_attention_node& node);
+
+ typed_primitive_inst(network& network, const paged_attention_node& desc);
+ typed_primitive_inst(network& network) : parent(network) {}
+
+ memory::ptr query_memory_ptr() const { return input_memory_ptr(0); }
+ memory::ptr key_memory_ptr() const { return input_memory_ptr(1); }
+ memory::ptr value_memory_ptr() const { return input_memory_ptr(2); }
+ memory::ptr key_cache_memory_ptr() const { return input_memory_ptr(3); }
+ memory::ptr value_cache_memory_ptr() const { return input_memory_ptr(4); }
+ memory::ptr past_lens_memory_ptr() const { return input_memory_ptr(5); }
+ memory::ptr subsequence_begins_memory_ptr() const { return input_memory_ptr(6); }
+ memory::ptr block_indices_memory_ptr() const { return input_memory_ptr(7); }
+ memory::ptr block_indices_begins_memory_ptr() const { return input_memory_ptr(8); }
+ memory::ptr alibi_memory_ptr() const { return input_memory_ptr(11); }
+
+ std::shared_ptr<network> prefill_network;
+
+protected:
+ void on_execute() override;
+
+ void update_shape_info_tensor(const kernel_impl_params& params) override;
+};
+
+using paged_attention_inst = typed_primitive_inst<paged_attention>;
+
+} // namespace cldnn
diff --git a/src/plugins/intel_gpu/src/graph/include/primitive_inst.h b/src/plugins/intel_gpu/src/graph/include/primitive_inst.h
index 66241a95f54..7efbaa0fe4b 100644
--- a/src/plugins/intel_gpu/src/graph/include/primitive_inst.h
+++ b/src/plugins/intel_gpu/src/graph/include/primitive_inst.h
@@ -53,6 +53,7 @@ struct primitive_impl {
virtual ~primitive_impl() = default;
virtual std::vector<layout> get_internal_buffer_layouts() const = 0;
+ virtual std::set<size_t> get_lockable_internal_buffers() const { return {}; }
virtual void set_node_params(const program_node&) {}
virtual const std::string& get_type_info() const = 0;
virtual void set_arguments(primitive_inst& instance) = 0;
diff --git a/src/plugins/intel_gpu/src/graph/include/program_node.h b/src/plugins/intel_gpu/src/graph/include/program_node.h
index 2edee6a201a..e194c90b5e1 100644
--- a/src/plugins/intel_gpu/src/graph/include/program_node.h
+++ b/src/plugins/intel_gpu/src/graph/include/program_node.h
@@ -357,6 +357,8 @@ public:
return as<To>();
}
+ virtual std::set<size_t> get_lockable_input_ids() const;
+
void add_dependant_shape_of_node(const program_node* node);
const std::set<const program_node*>& get_dependant_shape_of_nodes() const {
diff --git a/src/plugins/intel_gpu/src/graph/network.cpp b/src/plugins/intel_gpu/src/graph/network.cpp
index 597ee61841d..429cbc32c19 100644
--- a/src/plugins/intel_gpu/src/graph/network.cpp
+++ b/src/plugins/intel_gpu/src/graph/network.cpp
@@ -26,6 +26,7 @@
#include "primitive_inst.h"
#include "input_layout_inst.h"
#include "fully_connected_inst.h"
+#include "paged_attention_inst.h"
#include "convolution_inst.h"
#include "deconvolution_inst.h"
#include "mutable_data_inst.h"
@@ -747,13 +748,25 @@ std::string network::get_primitive_info(const primitive_id& id) const {
return node.type()->to_string(node);
}
-bool network::is_cpu_impl(const primitive_id& id) const {
+bool network::does_node_need_lockable_output(const primitive_id& id) const {
auto prim_inst = find_primitive(id);
OPENVINO_ASSERT(prim_inst, "[GPU] Can't get implementation type, since topology ",
"doesn't contain primitive with requested id: ", id);
- return prim_inst->get_impl() ? prim_inst->get_impl()->is_cpu() : true;
+ const auto& node = prim_inst->get_node();
+ if (node.is_type<input_layout>()) {
+ for (const auto& user : node.get_users()) {
+ const auto& lockable_input_ids = user->get_lockable_input_ids();
+ if (lockable_input_ids.count(user->get_dependency_index(node))) {
+ return true;
+ }
+ }
+
+ return false;
+ } else {
+ return prim_inst->get_impl() ? prim_inst->get_impl()->is_cpu() : true;
+ }
}
std::string network::get_implementation_info(const primitive_id& id) const {
@@ -1525,10 +1538,12 @@ void network::transfer_memory_to_device(std::shared_ptr<primitive_inst> instance
if (!get_engine().get_device_info().has_separate_cache)
return;
-
if (node.is_shape_infer_dep())
return;
+ if (inst_mem.count() == 0)
+ return;
+
if (alloc_type == allocation_type::usm_host || alloc_type == allocation_type::usm_shared) {
// Allocate and transfer memory
auto device_mem = inst_mem.get_engine()->allocate_memory(inst_mem.get_layout(), allocation_type::usm_device, false);
diff --git a/src/plugins/intel_gpu/src/graph/paged_attention.cpp b/src/plugins/intel_gpu/src/graph/paged_attention.cpp
new file mode 100644
index 00000000000..094d83b8450
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/paged_attention.cpp
@@ -0,0 +1,131 @@
+// Copyright (C) 2018-2023 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+#include "paged_attention_inst.h"
+#include "primitive_type_base.h"
+#include "json_object.h"
+
+#include <string>
+#include <sstream>
+
+namespace cldnn {
+GPU_DEFINE_PRIMITIVE_TYPE_ID(paged_attention)
+
+constexpr size_t paged_attention::block_size;
+
+bool is_prefill_stage(const kernel_impl_params& impl_param) {
+ const auto& query_shape = impl_param.get_input_layout(0).get_partial_shape();
+ const auto& past_lens_shape = impl_param.get_input_layout(5).get_partial_shape();
+
+ if (query_shape.is_static() && past_lens_shape.is_static())
+ return query_shape[0].get_length() != past_lens_shape[0].get_length();
+
+ return false;
+}
+
+layout paged_attention_inst::calc_output_layout(const paged_attention_node& /*node*/, kernel_impl_params const& impl_param) {
+ auto out_layout = impl_param.get_input_layout(0);
+
+ return {out_layout};
+}
+
+template<typename ShapeType>
+std::vector<layout> paged_attention_inst::calc_output_layouts(paged_attention_node const& /*node*/, kernel_impl_params const& impl_param) {
+ auto out_layout = impl_param.get_input_layout(0);
+
+ const auto& key_cache_ps = impl_param.get_input_layout(3).get_partial_shape();
+ bool valid_block_size = key_cache_ps[3].is_dynamic() || key_cache_ps[3].get_length() == paged_attention::block_size;
+ OPENVINO_ASSERT(valid_block_size, "[GPU] Incorrect block size for Paged Attention operation. "
+ "Expected ", paged_attention::block_size, ", but got ", key_cache_ps[3].get_length());
+
+ return {out_layout};
+}
+
+template std::vector<layout>
+ paged_attention_inst::calc_output_layouts<ov::PartialShape>(paged_attention_node const& node, const kernel_impl_params& impl_param);
+
+std::string paged_attention_inst::to_string(const paged_attention_node& node) {
+ auto desc = node.get_primitive();
+ auto node_info = node.desc_to_json();
+
+ std::stringstream primitive_description;
+
+ json_composite paged_attention_info;
+ paged_attention_info.add("paged_attention_block_size", desc->block_size);
+ paged_attention_info.add("head_size", desc->head_size);
+ paged_attention_info.add("heads_num", desc->heads_num);
+ paged_attention_info.add("kv_heads_num", desc->kv_heads_num);
+ paged_attention_info.add("scale", desc->scale_val.value_or(1.0f));
+ paged_attention_info.add("has_alibi", desc->has_alibi);
+ node_info->add("paged_attention primitive info", paged_attention_info);
+ node_info->dump(primitive_description);
+
+ return primitive_description.str();
+}
+
+void paged_attention_inst::on_execute() {
+ if (!is_prefill_stage(*_impl_params))
+ return;
+
+ OPENVINO_ASSERT(_intermediates_memory.size() >= 3, "Unexpected number of intermediates buffers for Paged Attention at prefill stage");
+
+ const auto blocks_indexes_start_idx = 0;
+ const auto blocks_indexes_end_idx = 1;
+ const auto gws_seq_indexes_correspondence_idx = 2;
+
+ auto subsequence_begins_mem = subsequence_begins_memory_ptr();
+ auto blocks_indexes_start_mem = _intermediates_memory[blocks_indexes_start_idx];
+ auto blocks_indexes_end_mem = _intermediates_memory[blocks_indexes_end_idx];
+ auto gws_seq_indexes_correspondence_mem = _intermediates_memory[gws_seq_indexes_correspondence_idx];
+
+ OPENVINO_ASSERT(subsequence_begins_mem->get_layout().data_type == data_types::i32);
+
+ auto& stream = get_network().get_stream();
+ mem_lock<int32_t, mem_lock_type::read> subsequence_begins_mem_lock(subsequence_begins_mem, stream);
+ mem_lock<int32_t, mem_lock_type::write> blocks_indexes_start_lock(blocks_indexes_start_mem, stream);
+ mem_lock<int32_t, mem_lock_type::write> blocks_indexes_end_lock(blocks_indexes_end_mem, stream);
+ mem_lock<int32_t, mem_lock_type::write> gws_seq_indexes_correspondence_lock(gws_seq_indexes_correspondence_mem, stream);
+
+ size_t index = 0;
+ const auto target_seq_len_block_size = 16; // TODO: Get block size from the impl
+ for (size_t i = 0; i < subsequence_begins_mem_lock.size() - 1; i++) {
+ const auto seq_start = subsequence_begins_mem_lock[i];
+ const auto seq_end = subsequence_begins_mem_lock[i + 1];
+ const auto seq_length = seq_end - seq_start;
+
+ for (int32_t j = 0; j < seq_length; j += target_seq_len_block_size) {
+ auto block_start_pos = subsequence_begins_mem_lock[i] + j;
+ auto block_end_pos = std::min(block_start_pos + target_seq_len_block_size, seq_end);
+
+ blocks_indexes_start_lock[index] = block_start_pos;
+ blocks_indexes_end_lock[index] = block_end_pos;
+ gws_seq_indexes_correspondence_lock[index] = static_cast<int32_t>(i);
+
+ index++;
+ }
+ }
+}
+
+void paged_attention_inst::update_shape_info_tensor(const kernel_impl_params& params) {
+ parent::update_shape_info_tensor(params);
+}
+
+paged_attention_inst::typed_primitive_inst(network& network, const paged_attention_node& node)
+ : parent(network, node) {
+ const auto desc = node.get_primitive();
+
+ const auto head_size = desc->head_size;
+ const auto heads_num = desc->heads_num;
+ const auto kv_heads_num = desc->kv_heads_num;
+ const auto pa_block_size = desc->block_size;
+
+ if (desc->has_alibi) {
+ const auto alibi_input_idx = 11;
+ const auto alibi_layout = node.get_input_layout(alibi_input_idx);
+ OPENVINO_ASSERT(heads_num == alibi_layout.count());
+ }
+
+ OPENVINO_ASSERT(heads_num % kv_heads_num == 0);
+ OPENVINO_ASSERT(head_size % pa_block_size == 0);
+}
+} // namespace cldnn
diff --git a/src/plugins/intel_gpu/src/graph/pass_manager.cpp b/src/plugins/intel_gpu/src/graph/pass_manager.cpp
index 4af19379022..6dcbba55207 100644
--- a/src/plugins/intel_gpu/src/graph/pass_manager.cpp
+++ b/src/plugins/intel_gpu/src/graph/pass_manager.cpp
@@ -50,7 +50,7 @@ void pass_manager::run(program& p, base_pass& pass) {
using ms = std::chrono::duration<double, std::ratio<1, 1000>>;
using Time = std::chrono::high_resolution_clock;
- GPU_DEBUG_LOG << "Run pass " << pass.get_name() << std::endl;
+ GPU_DEBUG_LOG << "Run pass " << pass.get_name() << " (program_id=" << p.get_id() << ")" << std::endl;
GPU_DEBUG_DEFINE_MEM_LOGGER(pass.get_name());
auto start = Time::now();
pass.run(p);
diff --git a/src/plugins/intel_gpu/src/graph/primitive_inst.cpp b/src/plugins/intel_gpu/src/graph/primitive_inst.cpp
index 03c24440426..9d741e6c177 100644
--- a/src/plugins/intel_gpu/src/graph/primitive_inst.cpp
+++ b/src/plugins/intel_gpu/src/graph/primitive_inst.cpp
@@ -28,6 +28,7 @@
#include "read_value_inst.h"
#include "kv_cache_inst.h"
#include "condition_inst.h"
+#include "paged_attention_inst.h"
#include "gather_inst.h"
#include "broadcast_inst.h"
#include "dynamic_quantize_inst.h"
@@ -395,6 +396,12 @@ void primitive_inst::update_shape() {
auto dep_mem = dep->output_memory_ptr(dep_port);
memory_deps.insert({i, dep_mem});
+
+ // Ignore shape infer dependency for input_layout when processing paged_attention nodes
+ if (get_node().is_type<paged_attention>() && dep->get_node().is_type<input_layout>()) {
+ continue;
+ }
+
if (!get_node().is_type<shape_of>() && !dep->get_node().is_in_shape_of_subgraph()) {
has_runtime_deps = true;
@@ -1892,11 +1899,12 @@ memory::ptr primitive_inst::allocate_internal_buffer(size_t idx, bool reset) {
}
int64_t available_device_mem_size = engine.get_device_info().max_global_mem_size - total_device_mem_size;
+ // TODO: check if this logic is needed
// check if there is any device mem input
if (engine.supports_allocation(allocation_type::usm_device)) {
for (const auto& dep : inst_deps) {
- if (!dep.first->mem_allocated()) continue;
- if (dep.first->output_memory().get_allocation_type() == allocation_type::usm_device) {
+ if (dep.first->output_memory_ptr() &&
+ dep.first->output_memory_ptr()->get_allocation_type() == allocation_type::usm_device) {
input_device_mem = true;
break;
}
@@ -1904,10 +1912,13 @@ memory::ptr primitive_inst::allocate_internal_buffer(size_t idx, bool reset) {
}
// allocate intermediate memory for the updated layout of buffer
auto layout = ibuf_layouts[idx];
- GPU_DEBUG_LOG << "[" << _node->id() << ": internal buf " << idx << "]" << std::endl;
auto alloc_type = allocation_type::unknown;
+ const auto& lockable_buffers_indexes = _impl->get_lockable_internal_buffers();
+ auto need_lockable_allocation = lockable_buffers_indexes.find(idx) != lockable_buffers_indexes.end();
+ GPU_DEBUG_LOG << "[" << _node->id() << ": internal buf " << idx << "] "
+ << layout.to_short_string() << " need_lockable_allocation=" << need_lockable_allocation << std::endl;
if ((int64_t)available_device_mem_size - (int64_t)layout.bytes_count() >= 0 &&
- (input_device_mem || _node->get_preferred_impl_type() == impl_types::onednn)) {
+ (input_device_mem || _node->get_preferred_impl_type() == impl_types::onednn) && !need_lockable_allocation) {
// scratchpad memory type enforces to device mem.
GPU_DEBUG_LOG << " input is device mem and available device mem size (" << available_device_mem_size
<< ") > requested memory (" << layout.bytes_count() << " )" << std::endl;
diff --git a/src/plugins/intel_gpu/src/graph/program.cpp b/src/plugins/intel_gpu/src/graph/program.cpp
index 40d858c38fe..35dd0c77a70 100644
--- a/src/plugins/intel_gpu/src/graph/program.cpp
+++ b/src/plugins/intel_gpu/src/graph/program.cpp
@@ -703,12 +703,15 @@ void program::transfer_memory_to_device() {
auto& mem = data_node.get_attached_memory();
auto mem_layout = mem.get_layout();
auto alloc_type = mem.get_allocation_type();
+
+ if (mem_layout.count() == 0)
+ continue;
+
if (!mem_layout.compatible(data_node_layout)) {
std::string err_str("Node and memory layouts are incompatible, error occurred for " + node->id() + " node");
throw std::invalid_argument(err_str);
}
-
if (alloc_type == allocation_type::usm_host || alloc_type == allocation_type::usm_shared) {
GPU_DEBUG_LOG << "[" << data_node.id() << ": constant]" << std::endl;
// Allocate and transfer memory
diff --git a/src/plugins/intel_gpu/src/graph/program_node.cpp b/src/plugins/intel_gpu/src/graph/program_node.cpp
index 521da602104..09c35ce474a 100644
--- a/src/plugins/intel_gpu/src/graph/program_node.cpp
+++ b/src/plugins/intel_gpu/src/graph/program_node.cpp
@@ -525,6 +525,20 @@ bool program_node::is_fused_dep(size_t dep_idx) const {
return false;
}
+std::set<size_t> program_node::get_lockable_input_ids() const {
+ const auto impl = get_selected_impl();
+ const bool has_cpu_impl = get_preferred_impl_type() == impl_types::cpu || (impl && impl->is_cpu());
+ if (has_cpu_impl) {
+ std::set<size_t> dependencies_indexes;
+ for (size_t i = 0; i < get_dependencies().size(); i++)
+ dependencies_indexes.insert(i);
+
+ return dependencies_indexes;
+ } else {
+ return {};
+ }
+}
+
std::map<size_t, memory::ptr> program_node::get_const_memory_deps() const {
std::map<size_t, memory::ptr> mem_deps;
for (auto& i : get_shape_infer_dependencies()) {
diff --git a/src/plugins/intel_gpu/src/kernel_selector/cl_kernels/pa_kv_cache_update_ref.cl b/src/plugins/intel_gpu/src/kernel_selector/cl_kernels/pa_kv_cache_update_ref.cl
new file mode 100644
index 00000000000..d0c3ed5b13d
--- /dev/null
+++ b/src/plugins/intel_gpu/src/kernel_selector/cl_kernels/pa_kv_cache_update_ref.cl
@@ -0,0 +1,201 @@
+// Copyright (C) 2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "include/batch_headers/common.cl"
+
+KERNEL(pa_kv_cache_update)(
+ OPTIONAL_SHAPE_INFO_ARG
+ __global const INPUT0_TYPE* key_data,
+ __global const INPUT1_TYPE* value_data,
+ __global const INPUT2_TYPE* past_lens,
+ __global const INPUT3_TYPE* block_indices,
+ __global const INPUT4_TYPE* block_indices_begins,
+ __global OUTPUT_TYPE* key_cache_data,
+ __global OUTPUT1_TYPE* value_cache_data,
+ const __global int* blocked_indexes_start,
+ const __global int* blocked_indexes_end,
+ const __global int* gws_seq_indexes_correspondence
+) {
+ // If the the number of new tokens equals to the number of past_lens elements,
+ // then it's the 2nd+ iteration
+ if (INPUT0_BATCH_NUM == INPUT2_BATCH_NUM) {
+ // 2nd+ token
+ const uint seq_idx = (uint)get_global_id(0);
+ const uint head_idx = (uint)get_global_id(1);
+ const uint sglid = (uint)get_global_id(2);
+
+ const uint seq_len = past_lens[seq_idx];
+ const uint current_token_pos_in_block = seq_len % PAGED_ATTENTION_BLOCK_SIZE;
+ const uint seq_last_block_idx = block_indices_begins[seq_idx + 1] - 1;
+ const uint block_idx = block_indices[seq_last_block_idx];
+
+ uint key_value_in_offset = seq_idx * KV_HEADS_NUM * HEAD_SIZE + head_idx * HEAD_SIZE;
+
+ uint key_out_offset = block_idx * KV_HEADS_NUM * HEAD_SIZE * PAGED_ATTENTION_BLOCK_SIZE + head_idx * HEAD_SIZE * PAGED_ATTENTION_BLOCK_SIZE + current_token_pos_in_block;
+
+ uint value_out_offset = block_idx * KV_HEADS_NUM * HEAD_SIZE * PAGED_ATTENTION_BLOCK_SIZE + head_idx * HEAD_SIZE * PAGED_ATTENTION_BLOCK_SIZE + current_token_pos_in_block * HEAD_SIZE;
+
+ #define READ_BLOCK_SIZE GENERATE_STAGE_BLOCK_SIZE
+ for (uint head_idx_index = 0; head_idx_index < HEAD_SIZE; head_idx_index += SUBGROUP_SIZE * READ_BLOCK_SIZE) {
+ #define BLOCK_READ(ptr, offset) BLOCK_READN(INPUT0_TYPE, READ_BLOCK_SIZE, ptr, offset);
+ #define DATA_VEC MAKE_VECTOR_TYPE(INPUT0_TYPE, READ_BLOCK_SIZE)
+
+ DATA_VEC input_data = BLOCK_READ(key_data, key_value_in_offset + head_idx_index);
+
+ unroll_for (uint i = 0; i < READ_BLOCK_SIZE; i++) {
+ uint key_offset = key_out_offset + (head_idx_index + sglid + SUBGROUP_SIZE * i) * PAGED_ATTENTION_BLOCK_SIZE;
+ #if READ_BLOCK_SIZE == 1
+ key_cache_data[key_offset] = input_data;
+ #else
+ key_cache_data[key_offset] = input_data[i];
+ #endif
+ }
+
+ input_data = BLOCK_READ(value_data, key_value_in_offset + head_idx_index);
+
+ unroll_for (uint i = 0; i < READ_BLOCK_SIZE; i++) {
+ uint value_offset = value_out_offset + head_idx_index + sglid + SUBGROUP_SIZE * i;
+ #if READ_BLOCK_SIZE == 1
+ value_cache_data[value_offset] = input_data;
+ #else
+ value_cache_data[value_offset] = input_data[i];
+ #endif
+ }
+ }
+ } else {
+ // 1st token
+ const uint block_idx = get_global_id(0);
+ const uint head_idx = get_global_id(1);
+ const uint sglid = get_global_id(2);
+
+ const uint block_start_pos = blocked_indexes_start[block_idx];
+ const uint block_end_pos = blocked_indexes_end[block_idx];
+ const uint tokens_num = block_end_pos - block_start_pos;
+
+ uint key_value_in_offset = block_start_pos * KV_HEADS_NUM * HEAD_SIZE +
+ head_idx * HEAD_SIZE;
+
+ uint key_out_offset = block_indices[block_idx] * KV_HEADS_NUM * HEAD_SIZE * PAGED_ATTENTION_BLOCK_SIZE +
+ head_idx * HEAD_SIZE * PAGED_ATTENTION_BLOCK_SIZE;
+
+ uint value_out_offset = key_out_offset;
+
+ if (tokens_num == PAGED_ATTENTION_BLOCK_SIZE) {
+ unroll_for (uint token_num = 0; token_num < PAGED_ATTENTION_BLOCK_SIZE; token_num++) {
+ uint head_idx_index = 0;
+ #define READ_BLOCK_SIZE 8
+ for (; head_idx_index + (READ_BLOCK_SIZE * SUBGROUP_SIZE) <= HEAD_SIZE; head_idx_index += SUBGROUP_SIZE * READ_BLOCK_SIZE) {
+ #define BLOCK_READ(ptr, offset) BLOCK_READN(INPUT0_TYPE, READ_BLOCK_SIZE, ptr, offset);
+ #define DATA_VEC MAKE_VECTOR_TYPE(INPUT0_TYPE, READ_BLOCK_SIZE)
+
+ DATA_VEC input_data = BLOCK_READ(key_data, key_value_in_offset + head_idx_index);
+
+ unroll_for (uint i = 0; i < READ_BLOCK_SIZE; i++) {
+ uint key_offset = key_out_offset + (head_idx_index + sglid + SUBGROUP_SIZE * i) * PAGED_ATTENTION_BLOCK_SIZE;
+ key_cache_data[key_offset] = input_data[i];
+ }
+
+ input_data = BLOCK_READ(value_data, key_value_in_offset + head_idx_index);
+
+ unroll_for (uint i = 0; i < READ_BLOCK_SIZE; i++) {
+ uint value_offset = value_out_offset + head_idx_index + sglid + SUBGROUP_SIZE * i;
+ value_cache_data[value_offset] = input_data[i];
+ }
+ }
+
+ #define READ_BLOCK_SIZE 4
+ for (; head_idx_index + (READ_BLOCK_SIZE * SUBGROUP_SIZE) <= HEAD_SIZE; head_idx_index += SUBGROUP_SIZE * READ_BLOCK_SIZE) {
+ #define BLOCK_READ(ptr, offset) BLOCK_READN(INPUT0_TYPE, READ_BLOCK_SIZE, ptr, offset);
+ #define DATA_VEC MAKE_VECTOR_TYPE(INPUT0_TYPE, READ_BLOCK_SIZE)
+
+ DATA_VEC input_data = BLOCK_READ(key_data, key_value_in_offset + head_idx_index);
+
+ unroll_for (uint i = 0; i < READ_BLOCK_SIZE; i++) {
+ uint key_offset = key_out_offset + (head_idx_index + sglid + SUBGROUP_SIZE * i) * PAGED_ATTENTION_BLOCK_SIZE;
+ key_cache_data[key_offset] = input_data[i];
+ }
+
+ input_data = BLOCK_READ(value_data, key_value_in_offset + head_idx_index);
+
+ unroll_for (uint i = 0; i < READ_BLOCK_SIZE; i++) {
+ uint value_offset = value_out_offset + head_idx_index + sglid + SUBGROUP_SIZE * i;
+ value_cache_data[value_offset] = input_data[i];
+ }
+ }
+
+ #define READ_BLOCK_SIZE 2
+ for (; head_idx_index + (READ_BLOCK_SIZE * SUBGROUP_SIZE) <= HEAD_SIZE; head_idx_index += SUBGROUP_SIZE * READ_BLOCK_SIZE) {
+ #define BLOCK_READ(ptr, offset) BLOCK_READN(INPUT0_TYPE, READ_BLOCK_SIZE, ptr, offset);
+ #define DATA_VEC MAKE_VECTOR_TYPE(INPUT0_TYPE, READ_BLOCK_SIZE)
+
+ DATA_VEC input_data = BLOCK_READ(key_data, key_value_in_offset + head_idx_index);
+
+ unroll_for (uint i = 0; i < READ_BLOCK_SIZE; i++) {
+ uint key_offset = key_out_offset + (head_idx_index + sglid + SUBGROUP_SIZE * i) * PAGED_ATTENTION_BLOCK_SIZE;
+ key_cache_data[key_offset] = input_data[i];
+ }
+
+ input_data = BLOCK_READ(value_data, key_value_in_offset + head_idx_index);
+
+ unroll_for (uint i = 0; i < READ_BLOCK_SIZE; i++) {
+ uint value_offset = value_out_offset + head_idx_index + sglid + SUBGROUP_SIZE * i;
+ value_cache_data[value_offset] = input_data[i];
+ }
+ }
+
+ #define READ_BLOCK_SIZE 1
+ for (; head_idx_index + (READ_BLOCK_SIZE * SUBGROUP_SIZE) <= HEAD_SIZE; head_idx_index += SUBGROUP_SIZE * READ_BLOCK_SIZE) {
+ #define BLOCK_READ(ptr, offset) BLOCK_READN(INPUT0_TYPE, READ_BLOCK_SIZE, ptr, offset);
+ #define DATA_VEC MAKE_VECTOR_TYPE(INPUT0_TYPE, READ_BLOCK_SIZE)
+
+ DATA_VEC input_data = BLOCK_READ(key_data, key_value_in_offset + head_idx_index);
+
+ unroll_for (uint i = 0; i < READ_BLOCK_SIZE; i++) {
+ uint key_offset = key_out_offset + (head_idx_index + sglid + SUBGROUP_SIZE * i) * PAGED_ATTENTION_BLOCK_SIZE;
+ key_cache_data[key_offset] = input_data;
+ }
+
+ input_data = BLOCK_READ(value_data, key_value_in_offset + head_idx_index);
+
+ unroll_for (uint i = 0; i < READ_BLOCK_SIZE; i++) {
+ uint value_offset = value_out_offset + head_idx_index + sglid + SUBGROUP_SIZE * i;
+ value_cache_data[value_offset] = input_data;
+ }
+ }
+
+ key_value_in_offset += KV_HEADS_NUM * HEAD_SIZE;
+ key_out_offset += 1;
+ value_out_offset += HEAD_SIZE;
+ }
+ } else {
+ for (uint i = 0; i < tokens_num; i++) {
+ uint head_idx_index = 0;
+
+ #define READ_BLOCK_SIZE 1
+ for (; head_idx_index + (READ_BLOCK_SIZE * SUBGROUP_SIZE) <= HEAD_SIZE; head_idx_index += SUBGROUP_SIZE * READ_BLOCK_SIZE) {
+ #define BLOCK_READ(ptr, offset) BLOCK_READN(INPUT0_TYPE, READ_BLOCK_SIZE, ptr, offset);
+ #define DATA_VEC MAKE_VECTOR_TYPE(INPUT0_TYPE, READ_BLOCK_SIZE)
+
+ DATA_VEC input_data = BLOCK_READ(key_data, key_value_in_offset + head_idx_index);
+
+ unroll_for (uint i = 0; i < READ_BLOCK_SIZE; i++) {
+ uint key_offset = key_out_offset + (head_idx_index + sglid + SUBGROUP_SIZE * i) * PAGED_ATTENTION_BLOCK_SIZE;
+ key_cache_data[key_offset] = input_data;
+ }
+
+ input_data = BLOCK_READ(value_data, key_value_in_offset + head_idx_index);
+
+ unroll_for (uint i = 0; i < READ_BLOCK_SIZE; i++) {
+ uint value_offset = value_out_offset + head_idx_index + sglid + SUBGROUP_SIZE * i;
+ value_cache_data[value_offset] = input_data;
+ }
+ }
+
+ key_value_in_offset += KV_HEADS_NUM * HEAD_SIZE;
+ key_out_offset += 1;
+ value_out_offset += HEAD_SIZE;
+ }
+ }
+ }
+}
diff --git a/src/plugins/intel_gpu/src/kernel_selector/cl_kernels/pa_sdpa_opt.cl b/src/plugins/intel_gpu/src/kernel_selector/cl_kernels/pa_sdpa_opt.cl
new file mode 100644
index 00000000000..0d27a797fac
--- /dev/null
+++ b/src/plugins/intel_gpu/src/kernel_selector/cl_kernels/pa_sdpa_opt.cl
@@ -0,0 +1,453 @@
+// Copyright (C) 2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "include/batch_headers/common.cl"
+#include "include/batch_headers/sub_group_block_read.cl"
+#include "include/batch_headers/sub_group_block_write.cl"
+#include "include/batch_headers/sub_group_shuffle.cl"
+
+#define SUBGROUPS_PER_WG (HEAD_SIZE / SUBGROUP_SIZE)
+#define PAGED_ATTENTION_BLOCKS_PER_PARTITION (SEQ_LEN_PARTITION_SIZE / PAGED_ATTENTION_BLOCK_SIZE)
+
+#if HEAD_SIZE > 128
+ #define STORE_QUERY_TO_SLM 1
+#endif
+
+#ifdef SDPA_STAGE_0
+
+#if SEQ_LEN_PARTITION_SIZE % PAGED_ATTENTION_BLOCK_SIZE != 0
+ #error pa_sdpa_opt.cl
+#endif
+
+#if SUBGROUP_SIZE != PAGED_ATTENTION_BLOCK_SIZE
+ #error pa_sdpa_opt.cl
+#endif
+
+REQD_SUB_GROUP_SIZE(SUBGROUP_SIZE)
+__attribute__((reqd_work_group_size(1, 1, HEAD_SIZE)))
+KERNEL(pa_sdpa_opt)(
+ OPTIONAL_SHAPE_INFO_ARG
+ const __global INPUT0_TYPE* query,
+ const __global INPUT1_TYPE* key_cache,
+ const __global INPUT2_TYPE* value_cache,
+ const __global INPUT3_TYPE* past_lens,
+ const __global INPUT4_TYPE* block_indices,
+ const __global INPUT5_TYPE* block_indices_begins,
+#if HAS_ALIBI
+ const __global INPUT6_TYPE* alibi_slopes,
+#endif
+ __global OUTPUT_TYPE* output,
+ __global SOFTMAX_ACCUMULATOR_TYPE* exp_sums,
+ __global SOFTMAX_ACCUMULATOR_TYPE* max_logits,
+ __global OUTPUT_TYPE* tmp_out
+) {
+ // Input shapes:
+ // query: [sequences_num, HEADS_NUM * HEAD_SIZE]
+ // key_cache: [num_blocks, HEADS_NUM, HEAD_SIZE, PAGED_ATTENTION_BLOCK_SIZE]
+ // value_cache: [num_blocks, HEADS_NUM, PAGED_ATTENTION_BLOCK_SIZE, HEAD_SIZE]
+ // past_lens: [sequences_num]
+ // subsequence_begins: [sequences_num + 1]
+ // block_indices: [used_blocks_num]
+ // block_indices: [sequences_num + 1]
+ //
+ // Output shapes:
+ // output: [sequences_num, HEADS_NUM * HEAD_SIZE]
+ // exp_sums: [sequences_num, HEADS_NUM, total_partitions_num]
+ // max_logits: [sequences_num, HEADS_NUM, total_partitions_num]
+ // tmp_out: [sequences_num, HEADS_NUM, total_partitions_num, HEAD_SIZE]
+
+ const uint seq_idx = get_global_id(0);
+ const uint head_num_idx = get_global_id(1);
+ const uint head_size_idx = get_global_id(2);
+ const uint sglid = get_sub_group_local_id();
+ const uint sgid = get_sub_group_id();
+ const uint total_partitions_num = get_num_groups(2);
+
+ const uint batch_idx = seq_idx;
+
+ const uint seq_len = past_lens[seq_idx] + 1;
+
+ const uint partition_idx = get_group_id(2);
+ const uint block_start_idx = partition_idx * SEQ_LEN_PARTITION_SIZE / PAGED_ATTENTION_BLOCK_SIZE;
+
+ if (partition_idx * SEQ_LEN_PARTITION_SIZE >= seq_len) {
+ return;
+ }
+
+ const uint total_blocks_num = CEIL_DIV(seq_len, PAGED_ATTENTION_BLOCK_SIZE);
+
+#ifdef STORE_QUERY_TO_SLM
+ // SLM buffer for query inputs
+ __local INPUT0_TYPE slm_query[HEAD_SIZE * TARGET_SEQ_LEN_BLOCK_SIZE];
+#endif
+
+ // SLM for intermediate QK results
+ __local OUTPUT_TYPE slm_qk_vals[SEQ_LEN_PARTITION_SIZE];
+
+ // SLM buffers for SoftMax calculation and qk_max/qk_sums results aggregation across all WGs
+ __local SOFTMAX_ACCUMULATOR_TYPE slm_qk_max_vals[SUBGROUPS_PER_WG];
+ __local SOFTMAX_ACCUMULATOR_TYPE slm_exp_sum_vals[SUBGROUPS_PER_WG];
+
+ SOFTMAX_ACCUMULATOR_TYPE qk_max = SOFTMAX_ACCUMULATOR_VAL_MIN;
+
+ {
+#if STORE_QUERY_TO_SLM
+ const uint query_idx_local = sgid * SUBGROUP_SIZE + sglid;
+ const uint query_idx = seq_idx * HEAD_SIZE * HEADS_NUM +
+ head_num_idx * HEAD_SIZE +
+ query_idx_local;
+
+ slm_query[query_idx_local] = BLOCK_READN(INPUT0_TYPE, 1, query, query_idx);
+
+ barrier(CLK_LOCAL_MEM_FENCE);
+#else
+ INPUT0_TYPE q_val[HEAD_SIZE / SUBGROUP_SIZE];
+ unroll_for (uint i = 0; i < HEAD_SIZE / SUBGROUP_SIZE; i++) {
+ const uint query_idx = seq_idx * HEAD_SIZE * HEADS_NUM +
+ head_num_idx * HEAD_SIZE +
+ i * SUBGROUP_SIZE;
+ q_val[i] = BLOCK_READN(INPUT0_TYPE, 1, query, query_idx);
+ }
+#endif
+
+ const uint blocks_num_per_partition = min(total_blocks_num - partition_idx * PAGED_ATTENTION_BLOCKS_PER_PARTITION, (uint)PAGED_ATTENTION_BLOCKS_PER_PARTITION);
+
+ uint blocks_num = blocks_num_per_partition / SUBGROUPS_PER_WG;
+ if (sgid < blocks_num_per_partition % SUBGROUPS_PER_WG)
+ blocks_num++;
+
+ const uint start_block_idx = block_indices_begins[seq_idx] + partition_idx * PAGED_ATTENTION_BLOCKS_PER_PARTITION + sgid;
+ for (uint block_num = 0; block_num < blocks_num; block_num++) {
+#ifdef BROADCAST_GROUP_SIZE
+ const uint head_idx = head_num_idx / BROADCAST_GROUP_SIZE;
+#else
+ const uint head_idx = head_num_idx;
+#endif
+ const uint block_offset = block_indices[start_block_idx + block_num * SUBGROUPS_PER_WG] * HEAD_SIZE * KV_HEADS_NUM * SUBGROUP_SIZE + head_idx * HEAD_SIZE * SUBGROUP_SIZE;
+
+ INPUT0_TYPE qk_acc = INPUT0_VAL_ZERO;
+
+ #define KEY_VEC_SIZE SUBGROUP_SIZE
+ unroll_for (uint qk_idx = 0; qk_idx < HEAD_SIZE / KEY_VEC_SIZE; qk_idx++) {
+ MAKE_VECTOR_TYPE(INPUT1_TYPE, KEY_VEC_SIZE) k_vals = 0;
+ unroll_for (uint i = 0; i < KEY_VEC_SIZE; i++) {
+ k_vals[i] = BLOCK_READN(INPUT1_TYPE, 1, key_cache, block_offset + qk_idx * SUBGROUP_SIZE * KEY_VEC_SIZE + i * SUBGROUP_SIZE);
+ }
+
+#if STORE_QUERY_TO_SLM
+ INPUT0_TYPE q_val = slm_query[qk_idx * KEY_VEC_SIZE + sglid];
+#endif
+
+ unroll_for (uint i = 0; i < KEY_VEC_SIZE; i++) {
+#if STORE_QUERY_TO_SLM
+ qk_acc = mad(sub_group_broadcast(q_val, i), k_vals[i], qk_acc);
+#else
+ qk_acc = mad(sub_group_broadcast(q_val[qk_idx], i), k_vals[i], qk_acc);
+#endif
+ }
+ }
+
+#ifdef SCALE_VAL
+ qk_acc = TO_INPUT0_TYPE(SCALE_VAL) * qk_acc;
+#endif
+
+ const uint token_idx = partition_idx * SEQ_LEN_PARTITION_SIZE + block_num * SUBGROUPS_PER_WG * SUBGROUP_SIZE + sgid * SUBGROUP_SIZE + sglid;
+
+#ifdef HAS_ALIBI
+ const int alibi_val = (1 - seq_len) + token_idx;
+ qk_acc += alibi_slopes[head_num_idx] * alibi_val;
+#endif
+
+ if (token_idx >= seq_len)
+ qk_acc = INPUT0_VAL_MIN;
+
+ qk_max = SOFTMAX_ACCUMULATOR_MAX_FUNC(qk_max, TO_SOFTMAX_ACCUMULATOR_TYPE(qk_acc));
+
+ slm_qk_vals[block_num * SUBGROUPS_PER_WG * SUBGROUP_SIZE + sgid * SUBGROUP_SIZE + sglid] = qk_acc;
+ }
+
+ qk_max = sub_group_reduce_max(qk_max);
+ }
+
+ {
+ // SoftMax calculation
+ if (sglid == 0) {
+ slm_qk_max_vals[sgid] = qk_max;
+ }
+
+ barrier(CLK_LOCAL_MEM_FENCE);
+
+ qk_max = SOFTMAX_ACCUMULATOR_VAL_MIN;
+ if (sglid < SUBGROUPS_PER_WG)
+ qk_max = slm_qk_max_vals[sglid];
+
+ // Final max value after reduction across of all SG and WI
+ qk_max = sub_group_reduce_max(qk_max);
+
+ SOFTMAX_ACCUMULATOR_TYPE exp_sum = SOFTMAX_ACCUMULATOR_VAL_ZERO;
+
+ const uint qk_iters_num = CEIL_DIV(SEQ_LEN_PARTITION_SIZE, SUBGROUPS_PER_WG * SUBGROUP_SIZE);
+ for (uint qk_idx = 0; qk_idx < qk_iters_num; qk_idx++) {
+ const uint local_data_idx = qk_idx * (SUBGROUPS_PER_WG * SUBGROUP_SIZE) + sgid * SUBGROUP_SIZE + sglid;
+ // TODO: const uint global_data_idx = partition_idx * SEQ_LEN_PARTITION_SIZE + local_data_idx
+ const uint global_data_idx = partition_idx * SEQ_LEN_PARTITION_SIZE + qk_idx * (SUBGROUPS_PER_WG * SUBGROUP_SIZE) + sgid * SUBGROUP_SIZE + sglid;
+
+ if (global_data_idx < seq_len) {
+ SOFTMAX_ACCUMULATOR_TYPE qk_new = native_exp(TO_SOFTMAX_ACCUMULATOR_TYPE(slm_qk_vals[local_data_idx]) - qk_max);
+ slm_qk_vals[local_data_idx] = TO_OUTPUT_TYPE(qk_new);
+
+ exp_sum += qk_new;
+ }
+ }
+
+ exp_sum = sub_group_reduce_add(exp_sum);
+
+ if (sglid == 0)
+ slm_exp_sum_vals[sgid] = exp_sum;
+
+ barrier(CLK_LOCAL_MEM_FENCE);
+
+ exp_sum = SOFTMAX_ACCUMULATOR_VAL_ZERO;
+
+ if (sglid < SUBGROUPS_PER_WG)
+ exp_sum = slm_exp_sum_vals[sglid];
+
+ // Final sum of all exp_sum values
+ exp_sum = sub_group_reduce_add(exp_sum);
+
+ for (uint qk_idx = 0; qk_idx < qk_iters_num; qk_idx++) {
+ const uint local_data_idx = qk_idx * (SUBGROUPS_PER_WG * SUBGROUP_SIZE) + sgid * SUBGROUP_SIZE + sglid;
+ const uint global_data_idx = partition_idx * SEQ_LEN_PARTITION_SIZE + qk_idx * (SUBGROUPS_PER_WG * SUBGROUP_SIZE) + sgid * SUBGROUP_SIZE + sglid;
+
+ if (global_data_idx < seq_len) {
+ SOFTMAX_ACCUMULATOR_TYPE qk_new = TO_SOFTMAX_ACCUMULATOR_TYPE(slm_qk_vals[local_data_idx]) / exp_sum;
+ slm_qk_vals[local_data_idx] = TO_OUTPUT_TYPE(qk_new);
+ }
+ }
+
+ barrier(CLK_LOCAL_MEM_FENCE);
+
+ {
+ // Save temporary exm_sums and max_logits values for each partition_num
+ if (seq_len > SEQ_LEN_PARTITION_SIZE && sgid == 0) {
+ const uint exp_sums_offset = seq_idx * HEADS_NUM * total_partitions_num +
+ head_num_idx * total_partitions_num +
+ partition_idx;
+ exp_sums[exp_sums_offset] = exp_sum;
+
+ const uint max_logits_offset = exp_sums_offset;
+ max_logits[max_logits_offset] = qk_max;
+ }
+ }
+ }
+
+ {
+ // QK*V calculation
+ OUTPUT_TYPE acc = OUTPUT_VAL_ZERO;
+
+ const uint partition_seq_len = min(seq_len - partition_idx * SEQ_LEN_PARTITION_SIZE, (uint)SEQ_LEN_PARTITION_SIZE);
+ uint blocks_num_per_partition = min(total_blocks_num - partition_idx * PAGED_ATTENTION_BLOCKS_PER_PARTITION, (uint)PAGED_ATTENTION_BLOCKS_PER_PARTITION);
+
+ uint leftovers = blocks_num_per_partition * PAGED_ATTENTION_BLOCK_SIZE - partition_seq_len;
+ if (leftovers != 0) {
+ leftovers = PAGED_ATTENTION_BLOCK_SIZE - leftovers;
+ blocks_num_per_partition = blocks_num_per_partition - 1;
+ }
+
+ const uint start_block_idx = block_indices_begins[seq_idx] + partition_idx * PAGED_ATTENTION_BLOCKS_PER_PARTITION;
+
+ for (uint block_num = 0; block_num < blocks_num_per_partition; block_num++) {
+#ifdef BROADCAST_GROUP_SIZE
+ const uint head_idx = head_num_idx / BROADCAST_GROUP_SIZE;
+#else
+ const uint head_idx = head_num_idx;
+#endif
+ const uint block_offset = block_indices[start_block_idx + block_num] * KV_HEADS_NUM * HEAD_SIZE * PAGED_ATTENTION_BLOCK_SIZE + head_idx * HEAD_SIZE * PAGED_ATTENTION_BLOCK_SIZE + sgid * SUBGROUP_SIZE;
+
+ #define VALUE_VEC_SIZE SUBGROUP_SIZE
+ MAKE_VECTOR_TYPE(INPUT2_TYPE, VALUE_VEC_SIZE) value_vals;
+ unroll_for (uint i = 0; i < VALUE_VEC_SIZE; i++) {
+ value_vals[i] = BLOCK_READN(INPUT2_TYPE, 1, value_cache, block_offset + i * HEAD_SIZE);
+ }
+
+ OUTPUT_TYPE qk_val = slm_qk_vals[block_num * PAGED_ATTENTION_BLOCK_SIZE + sglid];
+
+ unroll_for (uint i = 0; i < VALUE_VEC_SIZE; i++) {
+ acc = mad(sub_group_broadcast(qk_val, i), value_vals[i], acc);
+ }
+ }
+
+ if (leftovers != 0) {
+#ifdef BROADCAST_GROUP_SIZE
+ const uint head_idx = head_num_idx / BROADCAST_GROUP_SIZE;
+#else
+ const uint head_idx = head_num_idx;
+#endif
+ const uint last_block_idx = start_block_idx + blocks_num_per_partition;
+ const uint block_offset = block_indices[last_block_idx] * HEAD_SIZE * KV_HEADS_NUM * PAGED_ATTENTION_BLOCK_SIZE + head_idx * HEAD_SIZE * PAGED_ATTENTION_BLOCK_SIZE + sgid * SUBGROUP_SIZE;
+
+ OUTPUT_TYPE qk_val = slm_qk_vals[blocks_num_per_partition * PAGED_ATTENTION_BLOCK_SIZE + sglid];
+ for (uint i = 0; i < leftovers; i++) {
+ INPUT2_TYPE value_val = BLOCK_READN(INPUT2_TYPE, 1, value_cache, block_offset + i * HEAD_SIZE);
+ acc = mad(sub_group_broadcast(qk_val, i), value_val, acc);
+ }
+ }
+
+ if (seq_len > SEQ_LEN_PARTITION_SIZE) {
+ const uint tmp_out_offset = seq_idx * (HEADS_NUM * HEAD_SIZE * total_partitions_num) +
+ head_num_idx * (HEAD_SIZE * total_partitions_num) +
+ partition_idx * HEAD_SIZE +
+ sgid * SUBGROUP_SIZE +
+ sglid;
+
+ tmp_out[tmp_out_offset] = acc;
+ } else {
+ const uint output_offset = seq_idx * (HEADS_NUM * HEAD_SIZE) +
+ head_num_idx * HEAD_SIZE +
+ sgid * SUBGROUP_SIZE +
+ sglid;
+
+ output[output_offset] = acc;
+ }
+
+ }
+}
+
+#endif
+
+#ifdef SDPA_STAGE_1
+
+#if SOFTMAX_ACCUMULATOR_TYPE_SIZE == 4
+#define REG_VERSION_MAX_VALUES_PER_WI 24
+#elif SOFTMAX_ACCUMULATOR_TYPE_SIZE == 2
+#define REG_VERSION_MAX_VALUES_PER_WI 48
+#else
+#error Unexpected SOFTMAX_ACCUMULATOR data type size
+#endif
+
+REQD_SUB_GROUP_SIZE(SUBGROUP_SIZE)
+KERNEL(pa_sdpa_finalization_stage)(
+ const __global INPUT3_TYPE* past_lens,
+ __global OUTPUT_TYPE* output,
+ const __global SOFTMAX_ACCUMULATOR_TYPE* exp_sums,
+ const __global SOFTMAX_ACCUMULATOR_TYPE* max_logits,
+ const __global OUTPUT_TYPE* tmp_out,
+ const uint total_partitions_num) {
+ const uint seq_idx = get_global_id(0);
+ const uint head_num_idx = get_global_id(1);
+ const uint head_size_idx = get_global_id(2);
+ const uint sglid = get_sub_group_local_id();
+
+ const uint seq_len = past_lens[seq_idx] + 1;
+
+ const uint num_of_partitions = CEIL_DIV(seq_len, SEQ_LEN_PARTITION_SIZE);
+
+ if (seq_len <= SEQ_LEN_PARTITION_SIZE) {
+ /* Short path, no need any actions for currently processing sequence */
+ return;
+ } else if (num_of_partitions <= SUBGROUP_SIZE * REG_VERSION_MAX_VALUES_PER_WI) {
+ /* Registers kernel version, can handle up to SEQ_LEN_PARTITION_SIZE(256) * SUBGROUP_SIZE(16) * REG_VERSION_MAX_VALUES_PER_WI(24) = 98304 tokens */
+ SOFTMAX_ACCUMULATOR_TYPE exp_sum[REG_VERSION_MAX_VALUES_PER_WI] = {SOFTMAX_ACCUMULATOR_VAL_ZERO};
+ SOFTMAX_ACCUMULATOR_TYPE max_logit[REG_VERSION_MAX_VALUES_PER_WI] = {SOFTMAX_ACCUMULATOR_VAL_MIN};
+ SOFTMAX_ACCUMULATOR_TYPE local_exp_sum = SOFTMAX_ACCUMULATOR_VAL_ZERO;
+ SOFTMAX_ACCUMULATOR_TYPE local_max_logit = SOFTMAX_ACCUMULATOR_VAL_MIN;
+
+ const uint iters_num = CEIL_DIV(num_of_partitions, SUBGROUP_SIZE);
+ for (uint i = 0; i < iters_num; i++) {
+ const uint partition_idx = i * SUBGROUP_SIZE + sglid;
+ const uint exp_sums_offset = seq_idx * HEADS_NUM * total_partitions_num +
+ head_num_idx * total_partitions_num + partition_idx;
+ const uint max_logit_offset = exp_sums_offset;
+
+ if (partition_idx < num_of_partitions) {
+ exp_sum[i] = exp_sums[exp_sums_offset];
+ max_logit[i] = max_logits[max_logit_offset];
+ local_max_logit = SOFTMAX_ACCUMULATOR_MAX_FUNC(local_max_logit, max_logit[i]);
+ }
+ }
+
+ SOFTMAX_ACCUMULATOR_TYPE global_max = sub_group_reduce_max(local_max_logit);
+
+ // Update exp_sum with respect to the global maximum
+ for (uint i = 0; i < iters_num; i++) {
+ const uint partition_idx = i * SUBGROUP_SIZE + sglid;
+ if (partition_idx < num_of_partitions) {
+ exp_sum[i] = exp_sum[i] * native_exp(max_logit[i] - global_max);
+ local_exp_sum += exp_sum[i];
+ }
+ }
+
+ SOFTMAX_ACCUMULATOR_TYPE global_sum = sub_group_reduce_add(local_exp_sum);
+
+ SOFTMAX_ACCUMULATOR_TYPE acc = 0.0f;
+ for (uint partition_num = 0; partition_num < num_of_partitions; partition_num++) {
+ const uint tmp_out_offset = seq_idx * (HEADS_NUM * total_partitions_num * HEAD_SIZE) +
+ head_num_idx * (total_partitions_num * HEAD_SIZE) +
+ partition_num * HEAD_SIZE +
+ head_size_idx;
+ OUTPUT_TYPE out_val = tmp_out[tmp_out_offset];
+ acc += TO_SOFTMAX_ACCUMULATOR_TYPE(out_val) * TO_SOFTMAX_ACCUMULATOR_TYPE(sub_group_broadcast(exp_sum[partition_num / SUBGROUP_SIZE], partition_num)) / TO_SOFTMAX_ACCUMULATOR_TYPE(global_sum);
+ }
+ const uint out_offset = seq_idx * (HEADS_NUM * HEAD_SIZE) +
+ head_num_idx * HEAD_SIZE +
+ head_size_idx;
+
+ output[out_offset] = TO_OUTPUT_TYPE(acc);
+ } else {
+ /* Global memory kernel version, can handle any number of tokens */
+ SOFTMAX_ACCUMULATOR_TYPE local_exp_sum = SOFTMAX_ACCUMULATOR_VAL_ZERO;
+ SOFTMAX_ACCUMULATOR_TYPE local_max_logit = SOFTMAX_ACCUMULATOR_VAL_MIN;
+
+ const uint iters_num = CEIL_DIV(num_of_partitions, SUBGROUP_SIZE);
+ for (uint i = 0; i < iters_num; i++) {
+ const uint partition_idx = i * SUBGROUP_SIZE + sglid;
+ const uint max_logit_offset = seq_idx * HEADS_NUM * total_partitions_num +
+ head_num_idx * total_partitions_num + partition_idx;
+
+ if (partition_idx < num_of_partitions) {
+ local_max_logit = SOFTMAX_ACCUMULATOR_MAX_FUNC(local_max_logit, max_logits[max_logit_offset]);
+ }
+ }
+
+ SOFTMAX_ACCUMULATOR_TYPE global_max = sub_group_reduce_max(local_max_logit);
+
+ // Calculate global sum
+ for (uint i = 0; i < iters_num; i++) {
+ const uint partition_idx = i * SUBGROUP_SIZE + sglid;
+ const uint exp_sums_offset = seq_idx * HEADS_NUM * total_partitions_num +
+ head_num_idx * total_partitions_num + partition_idx;
+ const uint max_logit_offset = exp_sums_offset;
+
+ if (partition_idx < num_of_partitions) {
+ local_exp_sum += exp_sums[exp_sums_offset] * native_exp(max_logits[max_logit_offset] - global_max);
+ }
+ }
+
+ SOFTMAX_ACCUMULATOR_TYPE global_sum = sub_group_reduce_add(local_exp_sum);
+
+ SOFTMAX_ACCUMULATOR_TYPE acc = 0.0f;
+ for (uint partition_num = 0; partition_num < num_of_partitions; partition_num++) {
+ const uint tmp_out_offset = seq_idx * (HEADS_NUM * total_partitions_num * HEAD_SIZE) +
+ head_num_idx * (total_partitions_num * HEAD_SIZE) +
+ partition_num * HEAD_SIZE +
+ head_size_idx;
+
+ const uint exp_sums_offset = seq_idx * HEADS_NUM * total_partitions_num +
+ head_num_idx * total_partitions_num + partition_num;
+ const uint max_logit_offset = exp_sums_offset;
+
+ SOFTMAX_ACCUMULATOR_TYPE new_exp_sum = exp_sums[exp_sums_offset] * native_exp(max_logits[max_logit_offset] - global_max);
+
+ OUTPUT_TYPE out_val = tmp_out[tmp_out_offset];
+ acc += TO_SOFTMAX_ACCUMULATOR_TYPE(out_val) * new_exp_sum / TO_SOFTMAX_ACCUMULATOR_TYPE(global_sum);
+ }
+ const uint out_offset = seq_idx * (HEADS_NUM * HEAD_SIZE) +
+ head_num_idx * HEAD_SIZE +
+ head_size_idx;
+
+ output[out_offset] = TO_OUTPUT_TYPE(acc);
+ }
+}
+
+#endif
diff --git a/src/plugins/intel_gpu/src/kernel_selector/cl_kernels/sdpa_opt.cl b/src/plugins/intel_gpu/src/kernel_selector/cl_kernels/sdpa_opt.cl
index 073de59337a..948bd3c0f1a 100644
--- a/src/plugins/intel_gpu/src/kernel_selector/cl_kernels/sdpa_opt.cl
+++ b/src/plugins/intel_gpu/src/kernel_selector/cl_kernels/sdpa_opt.cl
@@ -548,7 +548,24 @@ KERNEL(sdpa_opt)(
#else
/* This version is used for 1st token */
+#if IS_PAGED_ATTENTION
+ #define SOURCE_SEQ_LEN (subsequence_begins[gws_seq_indexes_correspondence[((uint)get_global_id(1))] + 1] - subsequence_begins[gws_seq_indexes_correspondence[((uint)get_global_id(1))]])
+ #define TARGET_SEQ_LEN (subsequence_begins[gws_seq_indexes_correspondence[((uint)get_global_id(1))] + 1] - subsequence_begins[gws_seq_indexes_correspondence[((uint)get_global_id(1))]])
+
+ #define PA_BUFFERS , subsequence_begins, \
+ blocked_indexes_start, \
+ blocked_indexes_end, \
+ gws_seq_indexes_correspondence
+
+ #define PA_BUFFERS_ARGS , const __global INPUT3_TYPE* subsequence_begins, \
+ const __global int* blocked_indexes_start, \
+ const __global int* blocked_indexes_end, \
+ const __global int* gws_seq_indexes_correspondence
+#else
+ #define PA_BUFFERS
+ #define PA_BUFFERS_ARGS
+#endif
#if HAS_ATTN_MASK_INPUT
#define ATTN_MASK_BUFFER , attn_mask
#define ATTN_MASK_BUFFER_ARG , const __global INPUT3_TYPE* attn_mask
@@ -573,7 +590,9 @@ inline MASK_VECTOR_TYPE FUNC(load_attn_mask)(OPTIONAL_SHAPE_INFO_ARG
uint target_seq_idx,
uint source_seq_idx
ATTN_MASK_BUFFER_ARG
- ATTN_SCALE_BUFFER_ARG) {
+ ATTN_SCALE_BUFFER_ARG
+ PA_BUFFERS_ARGS
+ ) {
MASK_VECTOR_TYPE mask_vec = INPUT0_VAL_ZERO;
#if !IS_CAUSAL && HAS_ATTN_MASK_INPUT
const uint attn_mask_offset = INPUT3_GET_INDEX_SAFE(b0_idx, b1_idx, target_seq_idx, source_seq_idx);
@@ -611,9 +630,15 @@ inline MASK_VECTOR_TYPE FUNC(load_attn_mask)(OPTIONAL_SHAPE_INFO_ARG
#endif
#if IS_CAUSAL
- for (uint i = 0; i < SUBGROUP_SIZE; i++) {
- if (source_seq_idx + i > target_seq_idx)
+ if (target_seq_idx >= (uint)TARGET_SEQ_LEN) {
+ unroll_for (uint i = 0; i < SUBGROUP_SIZE; i++) {
mask_vec[i] = NAN;
+ }
+ } else {
+ for (uint i = 0; i < SUBGROUP_SIZE; i++) {
+ if (source_seq_idx + i > target_seq_idx)
+ mask_vec[i] = NAN;
+ }
}
#endif
@@ -637,6 +662,12 @@ KERNEL(sdpa_opt)(
const __global INPUT0_TYPE* query_input,
const __global INPUT1_TYPE* key_input,
const __global INPUT2_TYPE* value_input,
+#if IS_PAGED_ATTENTION
+ const __global INPUT3_TYPE* subsequence_begins,
+#if HAS_ALIBI
+ const __global INPUT4_TYPE* alibi_slopes,
+#endif
+#endif
#if HAS_ATTN_MASK_INPUT
const __global INPUT3_TYPE* attn_mask,
#endif
@@ -647,9 +678,15 @@ KERNEL(sdpa_opt)(
#ifdef BEAM_TABLE_TYPE
const __global BEAM_TABLE_TYPE* beam_table,
#endif
+#if IS_PAGED_ATTENTION
+ const __global int* blocked_indexes_start,
+ const __global int* blocked_indexes_end,
+ const __global int* gws_seq_indexes_correspondence
+#else
__global SOFTMAX_ACCUMULATOR_TYPE* exp_sums,
__global SOFTMAX_ACCUMULATOR_TYPE* max_logits,
__global OUTPUT_TYPE* tmp_out
+#endif
)
{
#if TARGET_SEQ_LEN_BLOCK_SIZE != 16
@@ -657,9 +694,11 @@ KERNEL(sdpa_opt)(
#endif
// Define indexes variables using macro declarations to avoid register spills
- #define batch_idx (get_global_id(0))
+ #define batch_idx ((uint)get_global_id(0))
+ #define num_heads_dim ((uint)get_global_id(0))
#define b0_idx (batch_idx / NUM_HEADS)
#define b1_idx (batch_idx % NUM_HEADS)
+ #define target_seq_dim ((uint)get_global_id(1))
#define target_seq_idx ((uint)get_global_id(1) * TARGET_SEQ_LEN_BLOCK_SIZE)
#define head_size_idx ((uint)get_local_id(2) % HEAD_SIZE)
#define sglid (uint)get_sub_group_local_id()
@@ -683,6 +722,15 @@ KERNEL(sdpa_opt)(
{
// Load Q input to SLM and transpose it
+#if IS_PAGED_ATTENTION
+ const uint block_start_pos = blocked_indexes_start[target_seq_dim];
+ const uint block_end_pos = blocked_indexes_end[target_seq_dim];
+
+ uint query_offset = block_start_pos * HEAD_SIZE * NUM_HEADS + num_heads_dim * HEAD_SIZE + head_size_idx;
+ const uint query_pitch = HEAD_SIZE * NUM_HEADS;
+
+ const uint cur_target_seq_len_size = block_end_pos - block_start_pos;
+#else
#ifdef INPUT0_DIMS_ORDER
uint query_offset = FUNC_CALL(get_input0_index)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, target_seq_idx, (head_size_idx));
uint query_offset_next_seq = FUNC_CALL(get_input0_index)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, target_seq_idx + 1, (head_size_idx));
@@ -691,8 +739,9 @@ KERNEL(sdpa_opt)(
uint query_offset = INPUT0_GET_INDEX(b0_idx, b1_idx, target_seq_idx, (head_size_idx));
const uint query_pitch = HEAD_SIZE;
#endif
- uint query_local_offset = head_size_idx * TARGET_SEQ_LEN_BLOCK_SIZE;
const uint cur_target_seq_len_size = min(TARGET_SEQ_LEN - target_seq_idx, (uint)TARGET_SEQ_LEN_BLOCK_SIZE);
+#endif
+ uint query_local_offset = head_size_idx * TARGET_SEQ_LEN_BLOCK_SIZE;
if (cur_target_seq_len_size != TARGET_SEQ_LEN_BLOCK_SIZE) {
if (sgid * SUBGROUP_SIZE < HEAD_SIZE) {
@@ -770,6 +819,16 @@ KERNEL(sdpa_opt)(
const uint seq_len = start_partition_idx + sgid * SUBGROUP_SIZE;
const uint partition_seq_len = min((uint)SOURCE_SEQ_LEN - start_partition_idx, (uint)SEQ_LEN_PARTITION_SIZE);
+#if IS_PAGED_ATTENTION
+#ifdef BROADCAST_GROUP_SIZE
+ const uint heads_dim = num_heads_dim / BROADCAST_GROUP_SIZE;
+#else
+ const uint heads_dim = num_heads_dim;
+#endif
+ #define KEY_SEQ_OFFSET subsequence_begins[gws_seq_indexes_correspondence[target_seq_dim]]
+ uint key_offset = KEY_SEQ_OFFSET * HEAD_SIZE * NUM_KV_HEADS + heads_dim * HEAD_SIZE + seq_len * HEAD_SIZE * NUM_KV_HEADS;
+ const uint key_pitch = HEAD_SIZE * NUM_KV_HEADS;
+#else
#ifdef BEAM_TABLE_TYPE
const uint b_idx = beam_table[FUNC_CALL(get_bt_index_key)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, seq_len + sglid, 0)];
const uint key_offset = FUNC_CALL(get_input1_index)(OPTIONAL_SHAPE_INFO_TENSOR b_idx, b1_idx, 0, 0, seq_len + sglid, 0);
@@ -783,17 +842,24 @@ KERNEL(sdpa_opt)(
const uint key_pitch = HEAD_SIZE;
#endif
#endif
+#endif
+
int seq_len_calc_size = min((int)(SOURCE_SEQ_LEN) - (int)seq_len, (int)SUBGROUP_SIZE);
MAKE_VECTOR_TYPE(INPUT0_TYPE, TARGET_SEQ_LEN_BLOCK_SIZE) qk_acc;
qk_acc = FUNC_CALL(load_attn_mask)(OPTIONAL_SHAPE_INFO_TENSOR
b0_idx,
b1_idx,
+#if IS_PAGED_ATTENTION
+ blocked_indexes_start[target_seq_dim] - subsequence_begins[gws_seq_indexes_correspondence[target_seq_dim]] + sglid,
+#else
target_seq_idx + sglid,
+#endif
// TODO: pass seq_len_calc_size here
seq_len
ATTN_MASK_BUFFER
- ATTN_SCALE_BUFFER);
+ ATTN_SCALE_BUFFER
+ PA_BUFFERS);
if (seq_len_calc_size >= SUBGROUP_SIZE) {
__attribute__((opencl_unroll_hint(1)))
@@ -874,6 +940,11 @@ KERNEL(sdpa_opt)(
#endif
qk_acc[i] *= scale_val;
+#ifdef HAS_ALIBI
+ const int alibi_val = (1 - SOURCE_SEQ_LEN) + seq_len + i;
+ qk_acc[i] += alibi_slopes[num_heads_dim] * alibi_val;
+#endif
+
qk_acc[i] = INPUT0_MIN_FUNC(INPUT0_MAX_FUNC(qk_acc[i], INPUT0_VAL_MIN), INPUT0_VAL_MAX);
qk_max = SOFTMAX_ACCUMULATOR_MAX_FUNC(qk_max, TO_SOFTMAX_ACCUMULATOR_TYPE(qk_acc[i]));
@@ -938,18 +1009,30 @@ KERNEL(sdpa_opt)(
{
// QK*V calculation
MAKE_VECTOR_TYPE(OUTPUT_TYPE, TARGET_SEQ_LEN_BLOCK_SIZE) acc_output_res = OUTPUT_VAL_ZERO;
-
+#if IS_PAGED_ATTENTION
+ const uint value_pitch = HEAD_SIZE * NUM_KV_HEADS;
+#else
#ifdef INPUT2_DIMS_ORDER
uint value_offset_base = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, 0, 0);
uint value_offset_next_seq = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, 1, 0);
const uint value_pitch = value_offset_next_seq - value_offset_base;
#else
const uint value_pitch = HEAD_SIZE;
+#endif
#endif
if (partition_seq_len == SEQ_LEN_PARTITION_SIZE) {
uint seq_len_start = (sgid / (SUBGROUPS_PER_WG / SG_SCALE_FACTOR)) * (SEQ_LEN_PARTITION_SIZE / SG_SCALE_FACTOR);
for (uint seq_len = seq_len_start; seq_len < seq_len_start + (SEQ_LEN_PARTITION_SIZE / SG_SCALE_FACTOR); seq_len += SUBGROUP_SIZE) {
+#if IS_PAGED_ATTENTION
+#ifdef BROADCAST_GROUP_SIZE
+ const uint heads_dim = num_heads_dim / BROADCAST_GROUP_SIZE;
+#else
+ const uint heads_dim = num_heads_dim;
+#endif
+ const uint value_seq_offset = subsequence_begins[gws_seq_indexes_correspondence[target_seq_dim]];
+ uint value_offset = value_seq_offset * HEAD_SIZE * NUM_KV_HEADS + heads_dim * HEAD_SIZE + (start_partition_idx + (seq_len)) * HEAD_SIZE * NUM_KV_HEADS + head_size_idx;
+#else
#ifdef BEAM_TABLE_TYPE
const uint b_idx = beam_table[FUNC_CALL(get_bt_index_value)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, start_partition_idx + (seq_len) + sglid, sgid * SUBGROUP_SIZE)];
const uint value_offset = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b_idx, b1_idx, 0, 0, start_partition_idx + (seq_len) + sglid, sgid * SUBGROUP_SIZE);
@@ -959,6 +1042,7 @@ KERNEL(sdpa_opt)(
#else
uint value_offset = INPUT2_GET_INDEX(b0_idx, b1_idx, start_partition_idx + (seq_len), head_size_idx);
#endif
+#endif
#endif
MAKE_VECTOR_TYPE(OUTPUT_TYPE, TARGET_SEQ_LEN_BLOCK_SIZE) qk_val;
@@ -988,15 +1072,25 @@ KERNEL(sdpa_opt)(
seq_len_end = seq_len_start + min(partition_seq_len - seq_len_start, (uint)(SEQ_LEN_PARTITION_SIZE / SG_SCALE_FACTOR));;
for (uint seq_len = seq_len_start / SUBGROUP_SIZE; seq_len < seq_len_end / SUBGROUP_SIZE; seq_len++) {
+#if IS_PAGED_ATTENTION
+#ifdef BROADCAST_GROUP_SIZE
+ const uint heads_dim = num_heads_dim / BROADCAST_GROUP_SIZE;
+#else
+ const uint heads_dim = num_heads_dim;
+#endif
+ const uint value_seq_offset = subsequence_begins[gws_seq_indexes_correspondence[target_seq_dim]];
+ uint value_offset = value_seq_offset * HEAD_SIZE * NUM_KV_HEADS + heads_dim * HEAD_SIZE + (start_partition_idx + (seq_len * SUBGROUP_SIZE)) * HEAD_SIZE * NUM_KV_HEADS + head_size_idx;
+#else
#ifdef BEAM_TABLE_TYPE
const uint b_idx = beam_table[FUNC_CALL(get_bt_index_value)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, start_partition_idx + (seq_len * SUBGROUP_SIZE) + sglid, sgid * SUBGROUP_SIZE)];
- const uint value_offset = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b_idx, b1_idx, 0, 0, start_partition_idx + (seq_len * SUBGROUP_SIZE) + sglid, sgid * SUBGROUP_SIZE);
+ uint value_offset = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b_idx, b1_idx, 0, 0, start_partition_idx + (seq_len * SUBGROUP_SIZE) + sglid, sgid * SUBGROUP_SIZE);
#else
#ifdef INPUT2_DIMS_ORDER
uint value_offset = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, start_partition_idx + (seq_len * SUBGROUP_SIZE), head_size_idx);
#else
uint value_offset = INPUT2_GET_INDEX(b0_idx, b1_idx, start_partition_idx + (seq_len * SUBGROUP_SIZE), head_size_idx);
#endif
+#endif
#endif
MAKE_VECTOR_TYPE(OUTPUT_TYPE, TARGET_SEQ_LEN_BLOCK_SIZE) qk_val;
@@ -1029,6 +1123,15 @@ KERNEL(sdpa_opt)(
qk_val[seq_idx] = slm_qk_vals[qk_offset];
qk_offset += SEQ_LEN_PARTITION_SIZE;
}
+#if IS_PAGED_ATTENTION
+#ifdef BROADCAST_GROUP_SIZE
+ const uint heads_dim = num_heads_dim / BROADCAST_GROUP_SIZE;
+#else
+ const uint heads_dim = num_heads_dim;
+#endif
+ const uint value_seq_offset = subsequence_begins[gws_seq_indexes_correspondence[target_seq_dim]];
+ uint value_offset = value_seq_offset * HEAD_SIZE * NUM_KV_HEADS + heads_dim * HEAD_SIZE + (start_partition_idx + seq_len_leftovers_start) * HEAD_SIZE * NUM_KV_HEADS + head_size_idx;
+#else
#ifdef BEAM_TABLE_TYPE
const uint b_idx = beam_table[FUNC_CALL(get_bt_index_value)(OPTIONAL_SHAPE_INFO_TENSOR b0_idx, b1_idx, 0, 0, start_partition_idx + seq_len_leftovers_start + sglid, sgid * SUBGROUP_SIZE)];
const uint value_offset = FUNC_CALL(get_input2_index)(OPTIONAL_SHAPE_INFO_TENSOR b_idx, b1_idx, 0, 0, start_partition_idx + seq_len_leftovers_start + sglid, sgid * SUBGROUP_SIZE);
@@ -1038,6 +1141,7 @@ KERNEL(sdpa_opt)(
#else
uint value_offset = INPUT2_GET_INDEX(b0_idx, b1_idx, start_partition_idx + seq_len_leftovers_start, head_size_idx);
#endif
+#endif
#endif
for (uint seq_len_idx = 0; seq_len_idx < partition_seq_len - seq_len_leftovers_start; seq_len_idx++) {
@@ -1059,7 +1163,6 @@ KERNEL(sdpa_opt)(
}
-
{
// Rescale acc_output_res values and save current iter results to global accumulator
SOFTMAX_ACCUMULATOR_TYPE exp_sum_prev = slm_exp_sum_prev[sglid];
@@ -1069,7 +1172,14 @@ KERNEL(sdpa_opt)(
barrier(CLK_LOCAL_MEM_FENCE);
+#if IS_PAGED_ATTENTION
+ const uint block_start_pos_new = blocked_indexes_start[target_seq_dim];
+ const uint block_end_pos_new = blocked_indexes_end[target_seq_dim];
+ const uint seq_idx_end = block_end_pos_new - block_start_pos_new;
+#else
const uint seq_idx_end = min(TARGET_SEQ_LEN - target_seq_idx, (uint)TARGET_SEQ_LEN_BLOCK_SIZE);
+#endif
+
for (uint seq_idx = 0; seq_idx < seq_idx_end; seq_idx++) {
SOFTMAX_ACCUMULATOR_TYPE total_max = SOFTMAX_ACCUMULATOR_MAX_FUNC(sub_group_broadcast(max_val_prev, seq_idx), sub_group_broadcast(max_val_cur, seq_idx));
SOFTMAX_ACCUMULATOR_TYPE updated_exp_sum_prev = sub_group_broadcast(exp_sum_prev, seq_idx) * native_exp(sub_group_broadcast(max_val_prev, seq_idx) - total_max);
@@ -1110,17 +1220,32 @@ KERNEL(sdpa_opt)(
}
}
+#if IS_PAGED_ATTENTION
+ const uint block_start_pos_new = blocked_indexes_start[target_seq_dim];
+ const uint block_end_pos_new = blocked_indexes_end[target_seq_dim];
+
+ uint output_offset = block_start_pos_new * HEAD_SIZE * NUM_HEADS + num_heads_dim * HEAD_SIZE + sgid * SUBGROUP_SIZE;
+ const uint output_pitch = HEAD_SIZE * NUM_HEADS;
+#else
uint output_offset = OUTPUT_GET_INDEX(b0_idx, b1_idx, target_seq_idx, sgid * SUBGROUP_SIZE);
+ const uint output_pitch = HEAD_SIZE;
+#endif
+
+#if IS_PAGED_ATTENTION
+ if (block_start_pos_new + TARGET_SEQ_LEN_BLOCK_SIZE != block_end_pos_new) {
+ const uint seq_idx_end = block_end_pos_new - block_start_pos_new;
+#else
if (get_global_id(1) == get_global_size(1) - 1) {
const uint seq_idx_end = min((uint)TARGET_SEQ_LEN - target_seq_idx, (uint)TARGET_SEQ_LEN_BLOCK_SIZE);
+#endif
for (uint seq_idx = 0; seq_idx < seq_idx_end; seq_idx++) {
OUTPUT_BLOCK_WRITE(output, output_offset, output_acc[seq_idx]);
- output_offset += HEAD_SIZE;
+ output_offset += output_pitch;
}
} else {
unroll_for (uint seq_idx = 0; seq_idx < TARGET_SEQ_LEN_BLOCK_SIZE; seq_idx++) {
OUTPUT_BLOCK_WRITE(output, output_offset, output_acc[seq_idx]);
- output_offset += HEAD_SIZE;
+ output_offset += output_pitch;
}
}
}
diff --git a/src/plugins/intel_gpu/src/kernel_selector/common_types.h b/src/plugins/intel_gpu/src/kernel_selector/common_types.h
index 12e685e0b09..73717d76933 100644
--- a/src/plugins/intel_gpu/src/kernel_selector/common_types.h
+++ b/src/plugins/intel_gpu/src/kernel_selector/common_types.h
@@ -15,6 +15,8 @@ enum class KernelType {
UNKNOWN,
ARG_MAX_MIN,
BEAM_TABLE_UPDATE,
+ PA_KV_CACHE_UPDATE,
+ PA_SDPA,
CONVOLUTION,
DECONVOLUTION,
DFT,
diff --git a/src/plugins/intel_gpu/src/kernel_selector/kernels/sdpa/pa_kv_cache_update_kernel_ref.cpp b/src/plugins/intel_gpu/src/kernel_selector/kernels/sdpa/pa_kv_cache_update_kernel_ref.cpp
new file mode 100644
index 00000000000..312b340480d
--- /dev/null
+++ b/src/plugins/intel_gpu/src/kernel_selector/kernels/sdpa/pa_kv_cache_update_kernel_ref.cpp
@@ -0,0 +1,165 @@
+// Copyright (C) 2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "pa_kv_cache_update_kernel_ref.h"
+#include "sdpa_kernel_base.h"
+
+#include "kernel_selector_params.h"
+#include "kernel_selector_utils.h"
+
+namespace kernel_selector {
+
+constexpr size_t subgroup_size = 16;
+constexpr size_t paged_attention_block_size = 16;
+
+static size_t get_generate_stage_block_size(size_t head_size) {
+ auto preferred_block_size = { 4, 2, 1 };
+ for (const auto& block_size : preferred_block_size) {
+ if (head_size % (block_size * subgroup_size) == 0) {
+ return block_size;
+ }
+ }
+
+ return 1;
+}
+
+KernelsData KVCacheUpdateKernelRef::GetKernelsData(const Params& p) const {
+ if (!Validate(p)) {
+ return {};
+ }
+
+ KernelData kd = KernelData::Default<kv_cache_update_params>(p);
+ kd.needs_sub_kernels_sync = false;
+ GetUpdateDispatchDataFunc(kd);
+
+ const auto& params = static_cast<const kv_cache_update_params&>(p);
+ const auto dispatch_data = SetDefault(params);
+ const auto entry_point = GetEntryPoint(kernelName, params.layerID, p);
+ const auto jit_constants = GetJitConstants(params);
+ const auto jit = CreateJit(kernelName, jit_constants, entry_point);
+
+ auto& kernel = kd.kernels[0];
+ FillCLKernelData(kernel,
+ dispatch_data,
+ params.engineInfo,
+ kernelName,
+ jit,
+ entry_point,
+ {},
+ false,
+ false,
+ static_cast<int>(params.inputs.size()),
+ GetFusedPrimitiveInputsCount(params),
+ static_cast<int>(params.outputs.size()),
+ params.is_shape_agnostic);
+
+ kernel.params.arguments.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, 0});
+ kernel.params.arguments.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, 1});
+ kernel.params.arguments.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, 2});
+
+ return {kd};
+}
+
+ParamsKey KVCacheUpdateKernelRef::GetSupportedKey() const {
+ ParamsKey k;
+
+ k.EnableInputDataType(Datatype::F16);
+ k.EnableInputDataType(Datatype::F32);
+ k.EnableInputDataType(Datatype::INT32);
+
+ k.EnableOutputDataType(Datatype::F16);
+ k.EnableOutputDataType(Datatype::F32);
+ k.EnableOutputDataType(Datatype::INT32);
+
+ k.EnableInputLayout(DataLayout::bfyx);
+ k.EnableOutputLayout(DataLayout::bfyx);
+ k.EnableOutputLayout(DataLayout::bfzyx);
+
+ k.EnableDifferentTypes();
+ k.EnableTensorOffset();
+ k.EnableTensorPitches();
+ k.EnableBatching();
+ k.EnableDynamicShapesSupport();
+
+ return k;
+}
+
+bool KVCacheUpdateKernelRef::Validate(const Params& params) const {
+ if (params.GetType() != KernelType::PA_KV_CACHE_UPDATE)
+ return false;
+
+ const auto& kernel_params = dynamic_cast<const kv_cache_update_params&>(params);
+ if (kernel_params.inputs.size() != 5)
+ return false;
+
+ if (kernel_params.outputs.size() != 2)
+ return false;
+
+ if (!kernel_params.conf.is_paged_attention)
+ return false;
+
+ if (kernel_params.conf.paged_attention_block_size != static_cast<int64_t>(paged_attention_block_size))
+ return false;
+
+ return true;
+}
+
+JitConstants KVCacheUpdateKernelRef::GetJitConstants(const kv_cache_update_params& params) const {
+ JitConstants jit = MakeBaseParamsJitConstants(params);
+
+ jit.AddConstant(MakeJitConstant("HEAD_SIZE", params.conf.head_size));
+ jit.AddConstant(MakeJitConstant("HEADS_NUM", params.conf.heads_num));
+ jit.AddConstant(MakeJitConstant("KV_HEADS_NUM", params.conf.kv_heads_num));
+ jit.AddConstant(MakeJitConstant("PAGED_ATTENTION_BLOCK_SIZE", paged_attention_block_size));
+ jit.AddConstant(MakeJitConstant("SUBGROUP_SIZE", subgroup_size));
+ jit.AddConstant(MakeJitConstant("GENERATE_STAGE_BLOCK_SIZE", get_generate_stage_block_size(params.conf.head_size)));
+
+ return jit;
+}
+
+CommonDispatchData KVCacheUpdateKernelRef::SetDefault(const kv_cache_update_params& params) {
+ CommonDispatchData dispatch_data;
+
+ const auto& key_cache = params.outputs[0];
+ const auto& value_cache = params.outputs[1];
+ if (!value_cache.is_dynamic() && !key_cache.is_dynamic()) {
+ bool is_prefill = params.inputs[0].Batch().v != params.inputs[2].Batch().v;
+ auto heads_number = static_cast<size_t>(params.conf.kv_heads_num);
+
+ if (is_prefill) {
+ const auto& block_indices_input = params.inputs[3];
+ const auto blocks_number = block_indices_input.Batch().v;
+
+ dispatch_data.gws = { blocks_number,
+ heads_number,
+ subgroup_size};
+ dispatch_data.lws = { 1, 1, subgroup_size };
+ } else {
+ const auto& key_input = params.inputs[0];
+ const auto sequences_number = key_input.Batch().v;
+
+ dispatch_data.gws = { sequences_number,
+ heads_number,
+ subgroup_size };
+ dispatch_data.lws = { 1, 1, subgroup_size };
+ }
+ }
+
+ return dispatch_data;
+}
+
+void KVCacheUpdateKernelRef::GetUpdateDispatchDataFunc(KernelData& kd) const {
+ kd.update_dispatch_data_func = [](const Params& params, KernelData& kd) {
+ const auto& prim_params = static_cast<const kv_cache_update_params&>(params);
+
+ auto dispatch_data = SetDefault(prim_params);
+
+ OPENVINO_ASSERT(kd.kernels.size() == 1, "[GPU] Invalid kernels size for update dispatch data func");
+ kd.kernels[0].params.workGroups.global = dispatch_data.gws;
+ kd.kernels[0].params.workGroups.local = dispatch_data.lws;
+ kd.kernels[0].skip_execution = false;
+ };
+}
+
+} // namespace kernel_selector
diff --git a/src/plugins/intel_gpu/src/kernel_selector/kernels/sdpa/pa_kv_cache_update_kernel_ref.h b/src/plugins/intel_gpu/src/kernel_selector/kernels/sdpa/pa_kv_cache_update_kernel_ref.h
new file mode 100644
index 00000000000..3520996ceba
--- /dev/null
+++ b/src/plugins/intel_gpu/src/kernel_selector/kernels/sdpa/pa_kv_cache_update_kernel_ref.h
@@ -0,0 +1,32 @@
+// Copyright (C) 2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "kernel_base_opencl.h"
+#include "sdpa_kernel_base.h"
+
+namespace kernel_selector {
+
+struct kv_cache_update_params : base_params {
+ kv_cache_update_params() : base_params(KernelType::PA_KV_CACHE_UPDATE) {}
+
+ sdpa_configuration conf;
+};
+
+class KVCacheUpdateKernelRef : public KernelBaseOpenCL {
+public:
+ KVCacheUpdateKernelRef() : KernelBaseOpenCL{"pa_kv_cache_update_ref"} {}
+ KernelsData GetKernelsData(const Params& params) const override;
+ ParamsKey GetSupportedKey() const override;
+ virtual ~KVCacheUpdateKernelRef() {}
+
+protected:
+ bool Validate(const Params& params) const override;
+ JitConstants GetJitConstants(const kv_cache_update_params& kernel_params) const;
+ static CommonDispatchData SetDefault(const kv_cache_update_params& kernel_params);
+ void GetUpdateDispatchDataFunc(KernelData& kd) const override;
+};
+
+} // namespace kernel_selector
diff --git a/src/plugins/intel_gpu/src/kernel_selector/kernels/sdpa/pa_sdpa_kernel_opt.cpp b/src/plugins/intel_gpu/src/kernel_selector/kernels/sdpa/pa_sdpa_kernel_opt.cpp
new file mode 100644
index 00000000000..add33747152
--- /dev/null
+++ b/src/plugins/intel_gpu/src/kernel_selector/kernels/sdpa/pa_sdpa_kernel_opt.cpp
@@ -0,0 +1,235 @@
+// Copyright (C) 2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "pa_sdpa_kernel_opt.h"
+
+#include "kernel_selector_params.h"
+#include "kernel_selector_utils.h"
+
+namespace kernel_selector {
+
+namespace {
+enum KernelsTypes {
+ SINGLE_TOKEN = 0,
+ FINALIZATION,
+ TOTAL_KERNELS_NUM
+};
+
+constexpr size_t subgroup_size = 16;
+constexpr size_t seq_len_partition_size = 256;
+constexpr size_t paged_attention_block_size = 16;
+constexpr Datatype softmax_acc_dt = Datatype::F32;
+} // namespace
+
+static std::string GetKernelName(std::string base_name, KernelsTypes type) {
+ auto kernel_name = base_name;
+
+ if (type == KernelsTypes::SINGLE_TOKEN) {
+ kernel_name += "_single_token";
+ } else if (type == KernelsTypes::FINALIZATION) {
+ kernel_name += "_finalization";
+ }
+
+ return kernel_name;
+}
+
+KernelsData PagedAttentionSDPAKernelOpt::GetKernelsData(const Params& p) const {
+ if (!Validate(p)) {
+ return {};
+ }
+
+ const auto& params = static_cast<const pa_sdpa_params&>(p);
+ const std::vector<KernelsTypes> kernels_type = { KernelsTypes::SINGLE_TOKEN,
+ KernelsTypes::FINALIZATION };
+
+ KernelData kd = KernelData::Default<pa_sdpa_params>(params, kernels_type.size());
+ kd.needs_sub_kernels_sync = true;
+
+ GetUpdateDispatchDataFunc(kd);
+
+ size_t kd_kernels_idx = 0;
+ for (const auto& kernel_type : kernels_type) {
+ const auto dispatch_data = SetDefault(params);
+ const auto kernel_name = GetKernelName(kernelName, static_cast<KernelsTypes>(kernel_type));
+ const auto entry_point = GetEntryPoint(kernel_name, params.layerID, params);
+ auto jit_constants = GetJitConstants(params, kernel_type);
+
+ const auto jit = CreateJit(kernel_name, jit_constants, entry_point);
+
+ const size_t inputs_num = kernel_type == KernelsTypes::SINGLE_TOKEN ? static_cast<int>(params.inputs.size()) : 1;
+ auto& kernel = kd.kernels[kd_kernels_idx++];
+ FillCLKernelData(kernel,
+ dispatch_data,
+ params.engineInfo,
+ kernelName,
+ jit,
+ entry_point,
+ {},
+ false,
+ false,
+ static_cast<int>(inputs_num),
+ GetFusedPrimitiveInputsCount(params),
+ static_cast<int>(params.outputs.size()),
+ params.is_shape_agnostic);
+
+ kernel.params.arguments.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, 0});
+ kernel.params.arguments.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, 1});
+ kernel.params.arguments.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, 2});
+ kd.internalBufferDataType = softmax_acc_dt;
+
+ if (kernel_type == KernelsTypes::FINALIZATION) {
+ kernel.params.arguments.push_back({ArgumentDescriptor::Types::SCALAR, 0});
+
+ // Remove unused shape_info argument at finalization stage
+ kernel.params.arguments.erase(kernel.params.arguments.begin());
+ }
+ }
+
+ return {kd};
+}
+
+ParamsKey PagedAttentionSDPAKernelOpt::GetSupportedKey() const {
+ ParamsKey k;
+ k.EnableInputDataType(Datatype::F16);
+ k.EnableInputDataType(Datatype::F32);
+ k.EnableInputDataType(Datatype::INT32);
+
+ k.EnableOutputDataType(Datatype::F16);
+ k.EnableOutputDataType(Datatype::F32);
+ k.EnableOutputDataType(Datatype::INT32);
+
+ k.EnableInputLayout(DataLayout::bfyx);
+ k.EnableInputLayout(DataLayout::bfzyx);
+ k.EnableOutputLayout(DataLayout::bfyx);
+ k.EnableOutputLayout(DataLayout::bfzyx);
+
+ k.EnableDifferentTypes();
+ k.EnableTensorOffset();
+ k.EnableTensorPitches();
+ k.EnableBatching();
+ k.EnableDynamicShapesSupport();
+
+ return k;
+}
+
+bool PagedAttentionSDPAKernelOpt::Validate(const Params& p) const {
+ if (p.GetType() != KernelType::PA_SDPA)
+ return false;
+
+ const auto& params = static_cast<const pa_sdpa_params&>(p);
+ if (!params.conf.is_paged_attention)
+ return false;
+
+ if (seq_len_partition_size % params.conf.paged_attention_block_size != 0)
+ return false;
+
+ if (params.conf.head_size % subgroup_size != 0)
+ return false;
+
+ const auto subgroups_per_wg = params.conf.head_size / subgroup_size;
+ if (subgroups_per_wg > subgroup_size)
+ return false;
+
+ return true;
+}
+
+JitConstants PagedAttentionSDPAKernelOpt::GetJitConstants(const pa_sdpa_params& params, size_t kernel_idx) const {
+ JitConstants jit = MakeBaseParamsJitConstants(params);
+
+ const auto& config = params.conf;
+ jit.AddConstant(MakeJitConstant("HEAD_SIZE", config.head_size));
+ jit.AddConstant(MakeJitConstant("HEADS_NUM", config.heads_num));
+ jit.AddConstant(MakeJitConstant("KV_HEADS_NUM", config.kv_heads_num));
+ jit.AddConstant(MakeJitConstant("SEQ_LEN_PARTITION_SIZE", seq_len_partition_size));
+ jit.AddConstant(MakeJitConstant("PAGED_ATTENTION_BLOCK_SIZE", paged_attention_block_size));
+ jit.AddConstant(MakeJitConstant("SUBGROUP_SIZE", subgroup_size));
+
+ if (config.broadcast_axis != -1) {
+ jit.AddConstant(MakeJitConstant("BROADCAST_GROUP_SIZE", config.group_size));
+ }
+
+ auto sdpa_stage = kernel_idx == KernelsTypes::FINALIZATION ? 1 : 0;
+ jit.AddConstant(MakeJitConstant("SDPA_STAGE_" + std::to_string(sdpa_stage), 1));
+
+ if (config.has_scale_val)
+ jit.AddConstant(MakeJitConstant("SCALE_VAL", config.scale_val));
+
+ if (params.conf.has_alibi_input)
+ jit.AddConstant(MakeJitConstant("HAS_ALIBI", 1));
+
+ jit.Merge(MakeTypeJitConstants(softmax_acc_dt, "SOFTMAX_ACCUMULATOR"));
+
+ return jit;
+}
+
+CommonDispatchData PagedAttentionSDPAKernelOpt::SetDefault(const pa_sdpa_params& params, size_t kernel_idx) {
+ CommonDispatchData dispatch_data;
+
+ const auto& input = params.inputs[0];
+ if (!input.is_dynamic()) {
+ const size_t sequences_number = input.Batch().v;
+ const size_t num_of_partitions = CeilDiv(params.max_context_len, seq_len_partition_size);
+ const size_t heads_num = static_cast<size_t>(params.conf.heads_num);
+ const size_t head_size = static_cast<size_t>(params.conf.head_size);
+
+ if (kernel_idx == 0) {
+ dispatch_data.gws = { sequences_number,
+ heads_num,
+ head_size * num_of_partitions };
+ dispatch_data.lws = { 1, 1, head_size };
+ } else {
+ dispatch_data.gws = { sequences_number,
+ heads_num,
+ head_size };
+ dispatch_data.lws = { 1, 1, subgroup_size };
+ }
+ }
+
+ return dispatch_data;
+}
+
+void PagedAttentionSDPAKernelOpt::GetUpdateDispatchDataFunc(KernelData& kd) const {
+ kd.update_dispatch_data_func = [](const Params& params, KernelData& kd) {
+ const auto& prim_params = static_cast<const pa_sdpa_params&>(params);
+
+ const size_t expected_kernels_num = 2;
+ OPENVINO_ASSERT(kd.kernels.size() == expected_kernels_num, "[GPU] Invalid kernels size for update dispatch data func of SDPA kernel");
+
+ auto dispatch_data1 = SetDefault(prim_params, KernelsTypes::SINGLE_TOKEN);
+ kd.kernels[KernelsTypes::SINGLE_TOKEN].params.workGroups.global = dispatch_data1.gws;
+ kd.kernels[KernelsTypes::SINGLE_TOKEN].params.workGroups.local = dispatch_data1.lws;
+ kd.kernels[KernelsTypes::SINGLE_TOKEN].skip_execution = false;
+
+ const auto& input = prim_params.inputs[0];
+ const size_t sequences_number = input.Batch().v;
+ const size_t num_of_partitions = CeilDiv(prim_params.max_context_len, seq_len_partition_size);
+
+ auto dispatch_data2 = SetDefault(prim_params, KernelsTypes::FINALIZATION);
+ kd.kernels[KernelsTypes::FINALIZATION].params.workGroups.global = dispatch_data2.gws;
+ kd.kernels[KernelsTypes::FINALIZATION].params.workGroups.local = dispatch_data2.lws;
+ kd.kernels[KernelsTypes::FINALIZATION].skip_execution = num_of_partitions == 1;
+
+ ScalarDescriptor num_of_partitions_scalar;
+ num_of_partitions_scalar.t = ScalarDescriptor::Types::UINT32;
+ num_of_partitions_scalar.v.u32 = static_cast<uint32_t>(num_of_partitions);
+ kd.kernels[KernelsTypes::FINALIZATION].params.scalars.resize(1);
+ kd.kernels[KernelsTypes::FINALIZATION].params.scalars[0] = num_of_partitions_scalar;
+
+ auto buf_dt_size = BytesPerElement(softmax_acc_dt);
+ auto buf_elements_count = sequences_number * prim_params.conf.heads_num * num_of_partitions;
+ auto buf_size = buf_elements_count * buf_dt_size;
+
+ auto tmp_out_dt_size = BytesPerElement(softmax_acc_dt);
+ auto tmp_out_elements_count = sequences_number * prim_params.conf.heads_num * prim_params.conf.head_size * num_of_partitions;
+ auto tmp_out_size = tmp_out_elements_count * tmp_out_dt_size;
+
+ kd.internalBufferSizes.clear();
+ kd.internalBufferSizes.push_back(buf_size);
+ kd.internalBufferSizes.push_back(buf_size);
+ kd.internalBufferSizes.push_back(tmp_out_size);
+ kd.internalBufferDataType = softmax_acc_dt;
+ };
+}
+
+} // namespace kernel_selector
diff --git a/src/plugins/intel_gpu/src/kernel_selector/kernels/sdpa/pa_sdpa_kernel_opt.h b/src/plugins/intel_gpu/src/kernel_selector/kernels/sdpa/pa_sdpa_kernel_opt.h
new file mode 100644
index 00000000000..2f0d8a52c6e
--- /dev/null
+++ b/src/plugins/intel_gpu/src/kernel_selector/kernels/sdpa/pa_sdpa_kernel_opt.h
@@ -0,0 +1,33 @@
+// Copyright (C) 2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "kernel_base_opencl.h"
+#include "sdpa_kernel_base.h"
+
+namespace kernel_selector {
+
+struct pa_sdpa_params : base_params {
+ pa_sdpa_params() : base_params(KernelType::PA_SDPA) {}
+
+ sdpa_configuration conf;
+ size_t max_context_len = 0;
+};
+
+class PagedAttentionSDPAKernelOpt : public KernelBaseOpenCL {
+public:
+ PagedAttentionSDPAKernelOpt() : KernelBaseOpenCL{"pa_sdpa_opt"} {}
+ KernelsData GetKernelsData(const Params& params) const override;
+ ParamsKey GetSupportedKey() const override;
+ virtual ~PagedAttentionSDPAKernelOpt() {}
+
+protected:
+ bool Validate(const Params& params) const override;
+ JitConstants GetJitConstants(const pa_sdpa_params& kernel_params, size_t kernel_idx) const;
+ static CommonDispatchData SetDefault(const pa_sdpa_params& kernel_params, size_t kernel_idx = 0);
+ void GetUpdateDispatchDataFunc(KernelData& kd) const override;
+};
+
+} // namespace kernel_selector
diff --git a/src/plugins/intel_gpu/src/kernel_selector/kernels/sdpa/sdpa_kernel_base.cpp b/src/plugins/intel_gpu/src/kernel_selector/kernels/sdpa/sdpa_kernel_base.cpp
index 4871af9ed59..7556debd29d 100644
--- a/src/plugins/intel_gpu/src/kernel_selector/kernels/sdpa/sdpa_kernel_base.cpp
+++ b/src/plugins/intel_gpu/src/kernel_selector/kernels/sdpa/sdpa_kernel_base.cpp
@@ -69,14 +69,17 @@ JitConstants SDPAKernelBase::GetJitConstants(const sdpa_params& params) const {
auto jit = MakeBaseParamsJitConstants(params);
if (params.conf.broadcast_axis != -1) {
+ jit.AddConstant(MakeJitConstant("BROADCAST_GROUP_SIZE", params.conf.group_size));
jit.AddConstant(MakeJitConstant("DO_BROADCAST_KEY_VALUE", GetBroadcastInputStr(params.inputs[0].GetDims().size(),
params.conf.broadcast_axis,
params.conf.group_size)));
}
jit.AddConstant(MakeJitConstant("IS_CAUSAL", params.conf.is_causal));
- jit.AddConstant(MakeJitConstant("HAS_ATTN_MASK_INPUT", params.inputs.size() > 3));
- jit.AddConstant(MakeJitConstant("HAS_SCALE_INPUT", params.inputs.size() > 4));
+ if (!params.conf.is_paged_attention) {
+ jit.AddConstant(MakeJitConstant("HAS_ATTN_MASK_INPUT", params.inputs.size() > 3));
+ jit.AddConstant(MakeJitConstant("HAS_SCALE_INPUT", params.inputs.size() > 4));
+ }
auto is_default_order = [](const std::vector<int64_t>& order) {
for (size_t i = 0; i < order.size(); i++)
@@ -111,8 +114,10 @@ JitConstants SDPAKernelBase::GetJitConstants(const sdpa_params& params) const {
jit.AddConstant(MakeJitConstant("INPUT2_DIMS_ORDER", GetDimsOrder(params.input2_order)));
TransposedDimensionAccessHelperJit dims_q(params.inputs[0], params.input0_order);
+ const auto num_heads = params.conf.is_paged_attention ? std::to_string(params.conf.heads_num) : dims_q.f();
jit.AddConstant(MakeJitConstant("TARGET_SEQ_LEN", dims_q.y()));
- jit.AddConstant(MakeJitConstant("NUM_HEADS", dims_q.f()));
+ jit.AddConstant(MakeJitConstant("NUM_HEADS", num_heads));
+ jit.AddConstant(MakeJitConstant("NUM_KV_HEADS", params.conf.kv_heads_num));
TransposedDimensionAccessHelperJit dims_k(params.inputs[1], params.input1_order);
jit.AddConstant(MakeJitConstant("SOURCE_SEQ_LEN", dims_k.y()));
diff --git a/src/plugins/intel_gpu/src/kernel_selector/kernels/sdpa/sdpa_kernel_base.h b/src/plugins/intel_gpu/src/kernel_selector/kernels/sdpa/sdpa_kernel_base.h
index 215f19ecc88..6ea8d85527d 100644
--- a/src/plugins/intel_gpu/src/kernel_selector/kernels/sdpa/sdpa_kernel_base.h
+++ b/src/plugins/intel_gpu/src/kernel_selector/kernels/sdpa/sdpa_kernel_base.h
@@ -87,6 +87,14 @@ struct sdpa_configuration {
int64_t broadcast_axis = -1;
bool is_causal = false;
+ bool has_alibi_input = false;
+
+ // Paged Attention configuration
+ bool is_paged_attention = false;
+ int64_t paged_attention_aligned_seq_len = -1;
+ int64_t paged_attention_block_size = 0;
+ bool has_scale_val = false;
+ float scale_val = 0.f;
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -106,10 +114,6 @@ struct sdpa_params : public base_params {
sdpa_configuration conf;
};
-struct sdpa_fuse_params : fuse_params {
- sdpa_fuse_params() : fuse_params(KernelType::SDPA) {}
-};
-
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// SDPAKernelBase
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
diff --git a/src/plugins/intel_gpu/src/kernel_selector/kernels/sdpa/sdpa_kernel_micro.cpp b/src/plugins/intel_gpu/src/kernel_selector/kernels/sdpa/sdpa_kernel_micro.cpp
index 46c536ac0bd..04ebf2f2165 100644
--- a/src/plugins/intel_gpu/src/kernel_selector/kernels/sdpa/sdpa_kernel_micro.cpp
+++ b/src/plugins/intel_gpu/src/kernel_selector/kernels/sdpa/sdpa_kernel_micro.cpp
@@ -314,6 +314,9 @@ bool SDPAKernelMicro::Validate(const Params& p) const {
const sdpa_params& params = static_cast<const sdpa_params&>(p);
+ if (params.conf.is_paged_attention)
+ return false;
+
if (params.engineInfo.arch < gpu_arch::xe_hpg || !params.engineInfo.supports_microkernels)
return false;
diff --git a/src/plugins/intel_gpu/src/kernel_selector/kernels/sdpa/sdpa_kernel_opt.cpp b/src/plugins/intel_gpu/src/kernel_selector/kernels/sdpa/sdpa_kernel_opt.cpp
index 750695fc80c..e1854df1954 100644
--- a/src/plugins/intel_gpu/src/kernel_selector/kernels/sdpa/sdpa_kernel_opt.cpp
+++ b/src/plugins/intel_gpu/src/kernel_selector/kernels/sdpa/sdpa_kernel_opt.cpp
@@ -9,8 +9,7 @@
namespace kernel_selector {
-constexpr size_t subgroup_size = 16;
-
+namespace {
enum KernelsTypes {
SINGLE_TOKEN = 0,
MULTI_TOKENS,
@@ -18,10 +17,16 @@ enum KernelsTypes {
TOTAL_KERNELS_NUM
};
-static size_t get_sg_number_scale_factor(const sdpa_params& sdpa_params) {
- const size_t optimal_scale_factor = 2;
- if (sdpa_params.conf.head_size * optimal_scale_factor <= sdpa_params.engineInfo.maxWorkGroupSize)
- return optimal_scale_factor;
+constexpr size_t subgroup_size = 16;
+} // namespace
+
+static size_t get_sg_number_scale_factor(const sdpa_params& sdpa_params, size_t kernel_type) {
+ if (kernel_type == KernelsTypes::MULTI_TOKENS) {
+ const size_t optimal_scale_factor = 2;
+ if (sdpa_params.conf.head_size * optimal_scale_factor <= sdpa_params.engineInfo.maxWorkGroupSize) {
+ return optimal_scale_factor;
+ }
+ }
return 1;
}
@@ -31,12 +36,13 @@ static size_t get_target_seq_len_block_size() {
return block_size;
}
-static size_t get_seq_len_partition_size(const sdpa_params& sdpa_params, const size_t kernel_idx) {
+static size_t get_seq_len_partition_size(const sdpa_params& sdpa_params, size_t kernel_type) {
size_t seq_len = 0;
- if (kernel_idx == KernelsTypes::MULTI_TOKENS)
- seq_len = sdpa_params.conf.head_size * get_sg_number_scale_factor(sdpa_params);
- else
+ if (kernel_type == KernelsTypes::MULTI_TOKENS) {
+ seq_len = sdpa_params.conf.head_size * get_sg_number_scale_factor(sdpa_params, kernel_type);
+ } else {
seq_len = 256;
+ }
return seq_len;
}
@@ -45,8 +51,64 @@ static Datatype get_softmax_acc_type() {
return Datatype::F32;
}
-static std::string GetKernelName(std::string base_name, KernelsTypes type, bool is_indirect) {
- auto kernel_name = base_name;
+static bool is_prefill_stage(const sdpa_params& sdpa_params) {
+ TransposedDimensionAccessHelperBase dims_q(sdpa_params.inputs[0], sdpa_params.input0_order);
+ auto target_seq_len = dims_q.y_dim().v;
+
+ return target_seq_len > 1;
+}
+
+static size_t get_partitions_num(const sdpa_params& sdpa_params, size_t kernel_type) {
+ if (sdpa_params.has_dynamic_tensors() || kernel_type == KernelsTypes::MULTI_TOKENS)
+ return 1;
+
+ TransposedDimensionAccessHelperBase dims_k(sdpa_params.inputs[1], sdpa_params.input1_order);
+ auto source_seq_len = dims_k.y_dim().v;
+
+ return CeilDiv(source_seq_len, get_seq_len_partition_size(sdpa_params, kernel_type));
+}
+
+static std::vector<size_t> get_internal_buffer_sizes(const sdpa_params& sdpa_params, size_t kernel_type) {
+ if (sdpa_params.conf.is_paged_attention) {
+ const auto blocks_indexes_dt = Datatype::INT32;
+ const auto target_seq_len_block_size = get_target_seq_len_block_size();
+ const auto target_seq_len = sdpa_params.conf.paged_attention_aligned_seq_len;
+ const auto blocks_indexes_buf_size = CeilDiv(target_seq_len, target_seq_len_block_size) * BytesPerElement(blocks_indexes_dt);
+
+ return {blocks_indexes_buf_size};
+ } else {
+ if (sdpa_params.has_dynamic_tensors() || kernel_type == KernelsTypes::MULTI_TOKENS) {
+ return {1, 1};
+ } else {
+ TransposedDimensionAccessHelperBase dims_q(sdpa_params.inputs[0], sdpa_params.input0_order);
+ const auto& output = sdpa_params.outputs[0];
+
+ const auto head_size = dims_q.x_dim().v;
+ const auto num_of_partitions = get_partitions_num(sdpa_params, kernel_type);
+ const auto is_prefill = is_prefill_stage(sdpa_params);
+
+ const auto buf_dt_size = BytesPerElement(get_softmax_acc_type());
+ const auto buf_elements_count = (num_of_partitions == 1 || is_prefill) ? 1 : output.LogicalSize() / head_size * num_of_partitions;
+ const auto buf_size = buf_elements_count * buf_dt_size;
+
+ const auto tmp_out_dt_size = output.ElementSize();
+ const auto tmp_out_elements_count = (num_of_partitions == 1 || is_prefill) ? 1 : output.LogicalSize() * num_of_partitions;
+ const auto tmp_out_size = tmp_out_elements_count * tmp_out_dt_size;
+
+ return {buf_size, tmp_out_size};
+ }
+ }
+}
+
+static std::string GetKernelName(std::string base_name, KernelsTypes type, const sdpa_params& params) {
+ const bool is_indirect = params.indirect_axis != -1;
+ const bool is_paged_attention = params.conf.is_paged_attention;
+
+ std::string kernel_name = "";
+ if (is_paged_attention)
+ kernel_name += "pa_";
+
+ kernel_name += base_name;
if (is_indirect)
kernel_name += "_ind";
@@ -65,6 +127,7 @@ ParamsKey SDPAKernelOpt::GetSupportedKey() const {
ParamsKey k;
k.EnableInputDataType(Datatype::F16);
k.EnableInputDataType(Datatype::F32);
+ k.EnableInputDataType(Datatype::INT32);
k.EnableOutputDataType(Datatype::F16);
k.EnableOutputDataType(Datatype::F32);
@@ -109,17 +172,24 @@ JitConstants SDPAKernelOpt::GetJitConstants(const sdpa_params& params, size_t ke
auto sdpa_stage = kernel_idx == KernelsTypes::FINALIZATION ? 1 : 0;
jit.AddConstant(MakeJitConstant("SDPA_STAGE_" + std::to_string(sdpa_stage), 1));
+ jit.AddConstant(MakeJitConstant("SG_SCALE_FACTOR", get_sg_number_scale_factor(params, kernel_idx)));
- if (params.inputs.size() <= 4) {
+ if (params.conf.is_paged_attention) {
+ if (params.conf.has_alibi_input) {
+ jit.AddConstant(MakeJitConstant("HAS_ALIBI", 1));
+ }
+
+ if (params.conf.has_scale_val) {
+ jit.AddConstant(MakeJitConstant("STATIC_SCALE_VALUE_INV", 1.0f / params.conf.scale_val));
+ jit.AddConstant(MakeJitConstant("STATIC_SCALE_VALUE", params.conf.scale_val));
+ }
+ } else if (params.inputs.size() <= 4) {
jit.AddConstant(MakeJitConstant("STATIC_SCALE_VALUE_INV", std::sqrt(static_cast<float>(params.conf.head_size))));
jit.AddConstant(MakeJitConstant("STATIC_SCALE_VALUE", 1.0f / std::sqrt(static_cast<float>(params.conf.head_size))));
}
- if (kernel_idx == KernelsTypes::MULTI_TOKENS) {
- jit.AddConstant(MakeJitConstant("SG_SCALE_FACTOR", get_sg_number_scale_factor(params)));
- } else {
- jit.AddConstant(MakeJitConstant("SG_SCALE_FACTOR", 1));
- }
+ if (params.conf.is_paged_attention)
+ jit.AddConstant(MakeJitConstant("IS_PAGED_ATTENTION", 1));
if (params.engineInfo.supports_immad && params.conf.broadcast_axis == -1 && params.conf.head_size >= 128)
jit.AddConstant(MakeJitConstant("LOAD_KEY_LEFTOVERS_IN_CALC_LOOP", 1));
@@ -131,19 +201,32 @@ CommonDispatchData SDPAKernelOpt::SetDefault(const sdpa_params& params, size_t k
CommonDispatchData dispatch_data;
const auto& query_input = params.inputs[0];
-
if (!query_input.is_dynamic()) {
+ if (params.conf.is_paged_attention) {
+ OPENVINO_ASSERT(kernel_idx == KernelsTypes::MULTI_TOKENS);
+
+ const size_t sg_num_scale = get_sg_number_scale_factor(params, kernel_idx);
+ const size_t heads_num = static_cast<size_t>(params.conf.heads_num);
+ const size_t target_seq_len_block_size = get_target_seq_len_block_size();
+ const size_t target_seq_len = static_cast<size_t>(params.conf.paged_attention_aligned_seq_len);
+ const size_t head_size = static_cast<size_t>(params.conf.head_size);
+
+ dispatch_data.gws = { heads_num,
+ CeilDiv(target_seq_len, target_seq_len_block_size),
+ head_size * sg_num_scale };
+ dispatch_data.lws = { 1, 1, head_size * sg_num_scale };
+
+ return dispatch_data;
+ }
+
TransposedDimensionAccessHelperBase dims_q(params.inputs[0], params.input0_order);
- TransposedDimensionAccessHelperBase dims_k(params.inputs[1], params.input1_order);
TransposedDimensionAccessHelperBase output(params.outputs[0], params.output_order);
const size_t batch_size = output.b_dim().v;
const size_t heads_num = output.f_dim().v;
- const size_t source_seq_len = dims_k.y_dim().v;
const size_t target_seq_len = dims_q.y_dim().v;
const size_t head_size = static_cast<size_t>(params.conf.head_size);
- const size_t num_of_partitions =
- kernel_idx == KernelsTypes::MULTI_TOKENS ? 1 : CeilDiv(source_seq_len, get_seq_len_partition_size(params, kernel_idx));
+ const size_t num_of_partitions = get_partitions_num(params, kernel_idx);
const size_t target_seq_len_block_size = kernel_idx == 1 ? get_target_seq_len_block_size() : 1;
if (kernel_idx == KernelsTypes::SINGLE_TOKEN) {
@@ -152,7 +235,7 @@ CommonDispatchData SDPAKernelOpt::SetDefault(const sdpa_params& params, size_t k
head_size * num_of_partitions };
dispatch_data.lws = { 1, 1, head_size };
} else if (kernel_idx == KernelsTypes::MULTI_TOKENS) {
- const size_t sg_num_scale = get_sg_number_scale_factor(params);
+ const size_t sg_num_scale = get_sg_number_scale_factor(params, kernel_idx);
dispatch_data.gws = { batch_size * heads_num,
CeilDiv(target_seq_len, target_seq_len_block_size),
head_size * sg_num_scale };
@@ -160,8 +243,8 @@ CommonDispatchData SDPAKernelOpt::SetDefault(const sdpa_params& params, size_t k
} else if (kernel_idx == KernelsTypes::FINALIZATION) {
dispatch_data.gws = { batch_size * heads_num,
target_seq_len,
- 16 };
- dispatch_data.lws = { 1, 1, 16 };
+ subgroup_size };
+ dispatch_data.lws = { 1, 1, subgroup_size };
}
}
@@ -173,20 +256,16 @@ KernelsData SDPAKernelOpt::GetKernelsData(const Params& params) const {
return {};
}
- // Implementation contains multiple kernels:
- // kernel[KernelsTypes::SINGLE_TOKEN] - single token generation stage (2nd token)
- // kernel[KernelsTypes::MULTI_TOKENS] - multi tokens processing stage (1st token)
- // kernel[KernelsTypes::FINALIZATION] - results aggregation for 2nd token generation
-
std::vector<KernelsTypes> kernels_type;
const auto& prim_params = static_cast<const sdpa_params&>(params);
- if (params.is_shape_agnostic) {
+ if (prim_params.conf.is_paged_attention) {
+ kernels_type = { KernelsTypes::MULTI_TOKENS };
+ } else if (params.is_shape_agnostic) {
kernels_type = { KernelsTypes::SINGLE_TOKEN, KernelsTypes::MULTI_TOKENS, KernelsTypes::FINALIZATION };
} else {
TransposedDimensionAccessHelperBase dims_q(prim_params.inputs[0], prim_params.input0_order);
- const auto target_seq_len = dims_q.y_dim().v;
- const auto is_prefill = target_seq_len > 1;
+ const auto is_prefill = is_prefill_stage(prim_params);
if (is_prefill) {
kernels_type = { KernelsTypes::MULTI_TOKENS };
@@ -203,7 +282,7 @@ KernelsData SDPAKernelOpt::GetKernelsData(const Params& params) const {
size_t kd_kernels_idx = 0;
for (const auto& kernel_idx : kernels_type) {
auto dispatch_data = SetDefault(prim_params, kernel_idx);
- auto kernel_name = GetKernelName(kernelName, static_cast<KernelsTypes>(kernel_idx), prim_params.indirect_axis != -1);
+ auto kernel_name = GetKernelName(kernelName, static_cast<KernelsTypes>(kernel_idx), prim_params);
auto entry_point = GetEntryPoint(kernel_name, prim_params.layerID, params);
auto jit_constants = GetJitConstants(prim_params, kernel_idx);
auto jit = CreateJit(kernel_name, jit_constants, entry_point);
@@ -227,20 +306,6 @@ KernelsData SDPAKernelOpt::GetKernelsData(const Params& params) const {
static_cast<int>(prim_params.outputs.size()),
prim_params.is_shape_agnostic);
- const auto num_of_partitions = 1;
- auto& output = prim_params.outputs[0];
- auto head_size = output.X().v;
-
- auto can_skip_allocation = num_of_partitions == 1 || kernel_idx == KernelsTypes::MULTI_TOKENS;
-
- auto buf_dt_size = BytesPerElement(get_softmax_acc_type());
- auto buf_elements_count = can_skip_allocation ? 1 : output.LogicalSize() / head_size * num_of_partitions;
- auto buf_size = buf_elements_count * buf_dt_size;
-
- auto tmp_out_dt_size = output.ElementSize();
- auto tmp_out_elements_count = can_skip_allocation ? 1 : output.LogicalSize() * num_of_partitions;
- auto tmp_out_size = tmp_out_elements_count * tmp_out_dt_size;
-
if (prim_params.indirect_axis != -1 && kernel_idx != KernelsTypes::FINALIZATION)
kernel.params.arguments.push_back({ArgumentDescriptor::Types::INPUT, static_cast<uint32_t>(prim_params.inputs.size())});
@@ -248,18 +313,28 @@ KernelsData SDPAKernelOpt::GetKernelsData(const Params& params) const {
kernel.params.arguments.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, 1});
kernel.params.arguments.push_back({ArgumentDescriptor::Types::INTERNAL_BUFFER, 2});
- kd.internalBufferSizes.clear();
- kd.internalBufferSizes.push_back(buf_size);
- kd.internalBufferSizes.push_back(buf_size);
- kd.internalBufferSizes.push_back(tmp_out_size);
- kd.internalBufferDataType = prim_params.inputs[0].GetDType();
+ const auto buf_sizes = get_internal_buffer_sizes(prim_params, kernel_idx);
+ if (prim_params.conf.is_paged_attention) {
+ kd.internalBufferSizes.clear();
+ kd.internalBufferSizes.push_back(buf_sizes[0]);
+ kd.internalBufferSizes.push_back(buf_sizes[0]);
+ kd.internalBufferSizes.push_back(buf_sizes[0]);
+ kd.internalBufferDataType = Datatype::INT32;
+ } else {
+ kd.internalBufferSizes.clear();
+ kd.internalBufferSizes.push_back(buf_sizes[0]);
+ kd.internalBufferSizes.push_back(buf_sizes[0]);
+ kd.internalBufferSizes.push_back(buf_sizes[1]);
+ kd.internalBufferDataType = prim_params.inputs[0].GetDType();
+ }
if (kernel_idx == KernelsTypes::FINALIZATION) {
+ const auto num_of_partitions = get_partitions_num(prim_params, kernel_idx);
kernel.params.arguments.push_back({ArgumentDescriptor::Types::SCALAR, 0});
ScalarDescriptor num_of_partitions_scalar;
num_of_partitions_scalar.t = ScalarDescriptor::Types::UINT32;
- num_of_partitions_scalar.v.u32 = num_of_partitions;
+ num_of_partitions_scalar.v.u32 = static_cast<uint32_t>(num_of_partitions);
kernel.params.scalars.clear();
kernel.params.scalars.push_back(num_of_partitions_scalar);
@@ -273,56 +348,59 @@ void SDPAKernelOpt::GetUpdateDispatchDataFunc(KernelData& kd) const {
kd.update_dispatch_data_func = [this](const Params& params, KernelData& kernel_data) {
const auto& prim_params = static_cast<const sdpa_params&>(params);
- const size_t expected_kernels_num = KernelsTypes::TOTAL_KERNELS_NUM;
+ const size_t paged_attention_kernels_num = 1;
+ const size_t expected_kernels_num = prim_params.conf.is_paged_attention ? paged_attention_kernels_num
+ : KernelsTypes::TOTAL_KERNELS_NUM;
OPENVINO_ASSERT(kernel_data.kernels.size() == expected_kernels_num,
"[GPU] Invalid kernels size for update dispatch data func of SDPA kernel");
- TransposedDimensionAccessHelperBase dims_q(prim_params.inputs[0], prim_params.input0_order);
- TransposedDimensionAccessHelperBase dims_k(prim_params.inputs[1], prim_params.input1_order);
- auto& output = prim_params.outputs[0];
-
- auto target_seq_len = dims_q.y_dim().v;
- auto head_size = dims_q.x_dim().v;
- auto source_seq_len = dims_k.y_dim().v;
- auto is_prefill = target_seq_len > 1;
-
- auto num_of_partitions = CeilDiv(source_seq_len, get_seq_len_partition_size(prim_params, KernelsTypes::SINGLE_TOKEN));
-
- auto buf_dt_size = BytesPerElement(get_softmax_acc_type());
- auto buf_elements_count = (num_of_partitions == 1 || is_prefill) ? 1 : output.LogicalSize() / head_size * num_of_partitions;
- auto buf_size = buf_elements_count * buf_dt_size;
-
- auto tmp_out_dt_size = output.ElementSize();
- auto tmp_out_elements_count = (num_of_partitions == 1 || is_prefill) ? 1 : output.LogicalSize() * num_of_partitions;
- auto tmp_out_size = tmp_out_elements_count * tmp_out_dt_size;
-
- auto dispatch_data1 = SetDefault(prim_params, KernelsTypes::SINGLE_TOKEN);
- kernel_data.kernels[KernelsTypes::SINGLE_TOKEN].params.workGroups.global = dispatch_data1.gws;
- kernel_data.kernels[KernelsTypes::SINGLE_TOKEN].params.workGroups.local = dispatch_data1.lws;
- kernel_data.kernels[KernelsTypes::SINGLE_TOKEN].skip_execution = is_prefill;
-
- auto dispatch_data2 = SetDefault(prim_params, KernelsTypes::MULTI_TOKENS);
- kernel_data.kernels[KernelsTypes::MULTI_TOKENS].params.workGroups.global = dispatch_data2.gws;
- kernel_data.kernels[KernelsTypes::MULTI_TOKENS].params.workGroups.local = dispatch_data2.lws;
- kernel_data.kernels[KernelsTypes::MULTI_TOKENS].skip_execution = !is_prefill;
-
- ScalarDescriptor num_of_partitions_scalar;
- num_of_partitions_scalar.t = ScalarDescriptor::Types::UINT32;
- num_of_partitions_scalar.v.u32 = static_cast<uint32_t>(num_of_partitions);
-
- auto dispatch_data3 = SetDefault(prim_params, KernelsTypes::FINALIZATION);
- kernel_data.kernels[KernelsTypes::FINALIZATION].params.workGroups.global = dispatch_data3.gws;
- kernel_data.kernels[KernelsTypes::FINALIZATION].params.workGroups.local = dispatch_data3.lws;
- kernel_data.kernels[KernelsTypes::FINALIZATION].skip_execution = is_prefill || num_of_partitions == 1;
-
- kernel_data.kernels[KernelsTypes::FINALIZATION].params.scalars.clear();
- kernel_data.kernels[KernelsTypes::FINALIZATION].params.scalars.push_back(num_of_partitions_scalar);
-
- kernel_data.internalBufferSizes.clear();
- kernel_data.internalBufferSizes.push_back(buf_size);
- kernel_data.internalBufferSizes.push_back(buf_size);
- kernel_data.internalBufferSizes.push_back(tmp_out_size);
- kernel_data.internalBufferDataType = prim_params.inputs[0].GetDType();
+ if (prim_params.conf.is_paged_attention) {
+ auto dispatch_data = SetDefault(prim_params, KernelsTypes::MULTI_TOKENS);
+ kernel_data.kernels[0].params.workGroups.global = dispatch_data.gws;
+ kernel_data.kernels[0].params.workGroups.local = dispatch_data.lws;
+ kernel_data.kernels[0].skip_execution = false;
+
+ const auto blocks_indexes_dt = Datatype::INT32;
+ const auto buf_sizes = get_internal_buffer_sizes(prim_params, KernelsTypes::MULTI_TOKENS);
+
+ kernel_data.internalBufferSizes.clear();
+ kernel_data.internalBufferSizes.push_back(buf_sizes[0]);
+ kernel_data.internalBufferSizes.push_back(buf_sizes[0]);
+ kernel_data.internalBufferSizes.push_back(buf_sizes[0]);
+ kernel_data.internalBufferDataType = blocks_indexes_dt;
+ } else {
+ const auto num_of_partitions = get_partitions_num(prim_params, KernelsTypes::SINGLE_TOKEN);
+ const auto buf_sizes = get_internal_buffer_sizes(prim_params, KernelsTypes::SINGLE_TOKEN);
+ const auto is_prefill = is_prefill_stage(prim_params);
+
+ ScalarDescriptor num_of_partitions_scalar;
+ num_of_partitions_scalar.t = ScalarDescriptor::Types::UINT32;
+ num_of_partitions_scalar.v.u32 = static_cast<uint32_t>(num_of_partitions);
+
+ auto dispatch_data1 = SetDefault(prim_params, KernelsTypes::SINGLE_TOKEN);
+ kernel_data.kernels[KernelsTypes::SINGLE_TOKEN].params.workGroups.global = dispatch_data1.gws;
+ kernel_data.kernels[KernelsTypes::SINGLE_TOKEN].params.workGroups.local = dispatch_data1.lws;
+ kernel_data.kernels[KernelsTypes::SINGLE_TOKEN].skip_execution = is_prefill;
+
+ auto dispatch_data2 = SetDefault(prim_params, KernelsTypes::MULTI_TOKENS);
+ kernel_data.kernels[KernelsTypes::MULTI_TOKENS].params.workGroups.global = dispatch_data2.gws;
+ kernel_data.kernels[KernelsTypes::MULTI_TOKENS].params.workGroups.local = dispatch_data2.lws;
+ kernel_data.kernels[KernelsTypes::MULTI_TOKENS].skip_execution = !is_prefill;
+
+ auto dispatch_data3 = SetDefault(prim_params, KernelsTypes::FINALIZATION);
+ kernel_data.kernels[KernelsTypes::FINALIZATION].params.workGroups.global = dispatch_data3.gws;
+ kernel_data.kernels[KernelsTypes::FINALIZATION].params.workGroups.local = dispatch_data3.lws;
+ kernel_data.kernels[KernelsTypes::FINALIZATION].skip_execution = is_prefill || num_of_partitions == 1;
+
+ kernel_data.kernels[KernelsTypes::FINALIZATION].params.scalars.clear();
+ kernel_data.kernels[KernelsTypes::FINALIZATION].params.scalars.push_back(num_of_partitions_scalar);
+
+ kernel_data.internalBufferSizes.clear();
+ kernel_data.internalBufferSizes.push_back(buf_sizes[0]);
+ kernel_data.internalBufferSizes.push_back(buf_sizes[0]);
+ kernel_data.internalBufferSizes.push_back(buf_sizes[1]);
+ kernel_data.internalBufferDataType = prim_params.inputs[0].GetDType();
+ }
};
}
diff --git a/src/plugins/intel_gpu/src/kernel_selector/kernels/sdpa/sdpa_kernel_selector.cpp b/src/plugins/intel_gpu/src/kernel_selector/kernels/sdpa/sdpa_kernel_selector.cpp
index 7e88d0ad71f..e65fd7fd109 100644
--- a/src/plugins/intel_gpu/src/kernel_selector/kernels/sdpa/sdpa_kernel_selector.cpp
+++ b/src/plugins/intel_gpu/src/kernel_selector/kernels/sdpa/sdpa_kernel_selector.cpp
@@ -7,6 +7,9 @@
#include "sdpa_kernel_opt.h"
#include "sdpa_kernel_micro.h"
+#include "pa_sdpa_kernel_opt.h"
+#include "pa_kv_cache_update_kernel_ref.h"
+
namespace kernel_selector {
sdpa_kernel_selector::sdpa_kernel_selector() {
@@ -20,4 +23,20 @@ sdpa_kernel_selector::sdpa_kernel_selector() {
KernelsData sdpa_kernel_selector::GetBestKernels(const Params& params) const {
return GetNaiveBestKernel(params, KernelType::SDPA);
}
+
+kv_cache_update_kernel_selector::kv_cache_update_kernel_selector() {
+ Attach<KVCacheUpdateKernelRef>();
+}
+
+KernelsData kv_cache_update_kernel_selector::GetBestKernels(const Params& params) const {
+ return GetNaiveBestKernel(params, KernelType::PA_KV_CACHE_UPDATE);
+}
+
+pa_sdpa_kernel_selector::pa_sdpa_kernel_selector() {
+ Attach<PagedAttentionSDPAKernelOpt>();
+}
+
+KernelsData pa_sdpa_kernel_selector::GetBestKernels(const Params& params) const {
+ return GetNaiveBestKernel(params, KernelType::PA_SDPA);
+}
} // namespace kernel_selector
diff --git a/src/plugins/intel_gpu/src/kernel_selector/kernels/sdpa/sdpa_kernel_selector.h b/src/plugins/intel_gpu/src/kernel_selector/kernels/sdpa/sdpa_kernel_selector.h
index e4a5f245bfe..ea2a948e555 100644
--- a/src/plugins/intel_gpu/src/kernel_selector/kernels/sdpa/sdpa_kernel_selector.h
+++ b/src/plugins/intel_gpu/src/kernel_selector/kernels/sdpa/sdpa_kernel_selector.h
@@ -20,4 +20,32 @@ public:
KernelsData GetBestKernels(const Params& params) const override;
};
+
+class kv_cache_update_kernel_selector : public kernel_selector_base {
+public:
+ static kv_cache_update_kernel_selector& Instance() {
+ static kv_cache_update_kernel_selector instance_;
+ return instance_;
+ }
+
+ kv_cache_update_kernel_selector();
+
+ virtual ~kv_cache_update_kernel_selector() {}
+
+ KernelsData GetBestKernels(const Params& params) const override;
+};
+
+class pa_sdpa_kernel_selector : public kernel_selector_base {
+public:
+ static pa_sdpa_kernel_selector& Instance() {
+ static pa_sdpa_kernel_selector instance_;
+ return instance_;
+ }
+
+ pa_sdpa_kernel_selector();
+
+ virtual ~pa_sdpa_kernel_selector() {}
+
+ KernelsData GetBestKernels(const Params& params) const override;
+};
} // namespace kernel_selector
diff --git a/src/plugins/intel_gpu/src/plugin/ops/paged_attention.cpp b/src/plugins/intel_gpu/src/plugin/ops/paged_attention.cpp
new file mode 100644
index 00000000000..5d07488c676
--- /dev/null
+++ b/src/plugins/intel_gpu/src/plugin/ops/paged_attention.cpp
@@ -0,0 +1,63 @@
+// Copyright (C) 2018-2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "intel_gpu/plugin/program_builder.hpp"
+#include "intel_gpu/plugin/common_utils.hpp"
+
+#include "openvino/op/constant.hpp"
+#include "openvino/op/paged_attention.hpp"
+
+#include "intel_gpu/primitives/paged_attention.hpp"
+
+namespace ov {
+namespace op {
+namespace internal {
+using PagedAttentionExtension = ov::op::PagedAttentionExtension;
+} // namespace internal
+} // namespace op
+} // namespace ov
+
+namespace ov {
+namespace intel_gpu {
+
+static void CreatePagedAttentionExtensionOp(ProgramBuilder& p, const std::shared_ptr<ov::op::PagedAttentionExtension>& op) {
+ validate_inputs_count(op, {13});
+ auto inputs = p.GetInputInfo(op);
+ auto prim = cldnn::paged_attention(layer_type_name_ID(op), inputs);
+
+ auto key_cache_ps = op->get_input_partial_shape(3);
+ auto query_ps = op->get_input_partial_shape(0);
+ auto head_size = key_cache_ps[2].get_length();
+ auto kv_heads_num = key_cache_ps[1].get_length();
+ auto heads_num = query_ps[1].get_length() / head_size;
+
+ prim.head_size = head_size;
+ prim.kv_heads_num = kv_heads_num;
+ prim.heads_num = heads_num;
+
+ const size_t scale_idx = 9;
+ const size_t alibi_idx = 11;
+
+ std::shared_ptr<ov::op::v0::Constant> scale_const = std::dynamic_pointer_cast<ov::op::v0::Constant>(op->get_input_node_shared_ptr(scale_idx));
+ OPENVINO_ASSERT(scale_const != nullptr);
+ OPENVINO_ASSERT(ov::shape_size(scale_const->get_output_shape(0)) == 1);
+ prim.scale_val = scale_const->cast_vector<float>()[0];
+
+ std::shared_ptr<ov::op::v0::Constant> alibi_const = std::dynamic_pointer_cast<ov::op::v0::Constant>(op->get_input_node_shared_ptr(alibi_idx));
+ OPENVINO_ASSERT(alibi_const != nullptr);
+ prim.has_alibi = ov::shape_size(alibi_const->get_output_shape(0)) > 0;
+
+ if (op->get_output_size() > 1) {
+ const auto scores_output_idx = 1;
+ const auto& users = op->get_output_target_inputs(scores_output_idx);
+ OPENVINO_ASSERT(users.size() == 0, "[GPU] PagedAttention implementation doesn't support scores output yet");
+ }
+
+ p.add_primitive(*op, prim);
+}
+
+REGISTER_FACTORY_IMPL(internal, PagedAttentionExtension)
+
+} // namespace intel_gpu
+} // namespace ov
diff --git a/src/plugins/intel_gpu/src/plugin/sync_infer_request.cpp b/src/plugins/intel_gpu/src/plugin/sync_infer_request.cpp
index 5e0c6e8c884..346b4471779 100644
--- a/src/plugins/intel_gpu/src/plugin/sync_infer_request.cpp
+++ b/src/plugins/intel_gpu/src/plugin/sync_infer_request.cpp
@@ -737,6 +737,8 @@ std::vector<cldnn::event::ptr> SyncInferRequest::prepare_input(const std::string
auto& engine = m_graph->get_engine();
auto& stream = network->get_stream();
+ auto need_lockable_mem = network->does_node_need_lockable_output(internal_name);
+
OPENVINO_ASSERT(pshape.compatible(ov::PartialShape(user_tensor->get_shape())) || is_batched_input(port),
"[GPU] The input tensor size is not equal to model port shape, can't handle input tensor with name: ",
internal_name,
@@ -749,7 +751,7 @@ std::vector<cldnn::event::ptr> SyncInferRequest::prepare_input(const std::string
auto device_tensor_et = convert_to_supported_device_type(element_type);
bool convert_needed = is_convert_required(element_type, device_tensor_et);
- if (is_remote_tensor_impl) {
+ if (is_remote_tensor_impl && !need_lockable_mem) {
if (convert_needed) {
m_plugin_inputs[input_idx] = { create_device_tensor(pshape,
cldnn::element_type_to_data_type(element_type),
@@ -788,10 +790,10 @@ std::vector<cldnn::event::ptr> SyncInferRequest::prepare_input(const std::string
bool update_device_tensor = (m_plugin_inputs.count(input_idx) == 0) ||
(m_plugin_inputs[input_idx].owner == TensorOwner::USER && !is_remote_tensor_impl) ||
(plugin_tensor_mem_type != cldnn::allocation_type::usm_host && usm_host_raw_ptr);
-
if (update_device_tensor) {
// If device input hasn't been created, then try to use user memory if it's usm_host, or allocate new device buffer
- m_plugin_inputs[input_idx] = create_or_share_device_tensor(user_tensor_wrapper, internal_name, pshape, device_tensor_et, convert_needed);
+ m_plugin_inputs[input_idx] =
+ create_or_share_device_tensor(user_tensor_wrapper, internal_name, pshape, device_tensor_et, convert_needed || need_lockable_mem);
} else if (!is_remote_tensor_impl) {
// Device memory has been created on previous iterations. Try to reuse whenever it's possible
auto device_tensor_wrapper = m_plugin_inputs.at(input_idx);
@@ -803,7 +805,7 @@ std::vector<cldnn::event::ptr> SyncInferRequest::prepare_input(const std::string
cldnn::format::get_default_format(user_tensor->get_shape().size())),
*m_shape_predictor);
GPU_DEBUG_TRACE_DETAIL << " actual memory shape: " << actual_shape.to_string() << std::endl;
- auto new_tensor = create_device_tensor(actual_shape, device_tensor_et, false);
+ auto new_tensor = create_device_tensor(actual_shape, device_tensor_et, need_lockable_mem);
new_tensor->set_shape(user_tensor->get_shape());
m_plugin_inputs[input_idx] = { new_tensor, TensorOwner::PLUGIN };
}
@@ -839,6 +841,16 @@ std::vector<cldnn::event::ptr> SyncInferRequest::prepare_input(const std::string
}
cldnn::event::ptr ret_event = nullptr;
+ if (!is_remote_tensor_impl && !is_generic_remote && !convert_needed) {
+ auto src_ptr = static_cast<uint8_t*>(user_tensor->data());
+ if (!same_host_mem(memory, src_ptr)) {
+ // WA: Set need_lockable_mem as a blocking argument
+ // The current input_layout (wait_for_events) does not provide proper synchronization for subsequent CPU implementations
+ // For IOQ, it creates an already set user event, leading to accessing memory that hasn't completed copying
+ // For OOOQ, it enqueues a barrier that is ignored by the memory_lock functions, also causing access to not ready memory
+ ret_event = memory->copy_from(stream, src_ptr, need_lockable_mem);
+ }
+ }
if (convert_needed) {
if (is_remote_tensor_impl) {
convert_and_copy(remote_tensor_impl_ptr->get_memory(), device_tensor->get_memory(), stream);
@@ -904,14 +916,14 @@ std::vector<cldnn::event::ptr> SyncInferRequest::prepare_output(size_t output_id
}
if (!is_dynamic) {
- auto is_cpu_impl = network->is_cpu_impl(internal_name);
+ bool need_lockable_mem = network->does_node_need_lockable_output(internal_name);
bool has_device_buffer = m_plugin_outputs.count(output_idx) > 0;
bool update_device_tensor = !has_device_buffer ||
is_generic_remote ||
(m_plugin_outputs[output_idx].owner == TensorOwner::USER && !is_remote_tensor_impl);
if (update_device_tensor) {
m_plugin_outputs[output_idx] =
- create_or_share_device_tensor(user_tensor_wrapper, internal_name, pshape, device_tensor_et, is_cpu_impl || convert_needed);
+ create_or_share_device_tensor(user_tensor_wrapper, internal_name, pshape, device_tensor_et, need_lockable_mem || convert_needed);
}
}