Skip to content

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

Enable CM kernels for GPU (#27857)

Jakub Kasprzakaf7a0916f8d7
diff --git a/src/plugins/intel_gpu/include/intel_gpu/primitives/implementation_desc.hpp b/src/plugins/intel_gpu/include/intel_gpu/primitives/implementation_desc.hpp
index e84311a9cfb..c83b1127e2d 100644
--- a/src/plugins/intel_gpu/include/intel_gpu/primitives/implementation_desc.hpp
+++ b/src/plugins/intel_gpu/include/intel_gpu/primitives/implementation_desc.hpp
@@ -19,6 +19,7 @@ enum class impl_types : uint8_t {
ocl = 1 << 2,
onednn = 1 << 3,
sycl = 1 << 4,
+ cm = 1 << 5,
any = 0xFF,
};
@@ -43,6 +44,7 @@ inline std::ostream& operator<<(std::ostream& out, const impl_types& impl_type)
case impl_types::common: out << "common"; break;
case impl_types::ocl: out << "ocl"; break;
case impl_types::onednn: out << "onednn"; break;
+ case impl_types::cm: out << "cm"; break;
case impl_types::any: out << "any"; break;
default: out << "unknown"; break;
}
@@ -61,6 +63,8 @@ inline std::istream& operator>>(std::istream& is, impl_types& impl_type) {
impl_type = impl_types::ocl;
} else if (str == "onednn") {
impl_type = impl_types::onednn;
+ } else if (str == "cm") {
+ impl_type = impl_types::cm;
} else if (str == "any") {
impl_type = impl_types::any;
} else {
diff --git a/src/plugins/intel_gpu/include/intel_gpu/runtime/kernel_args.hpp b/src/plugins/intel_gpu/include/intel_gpu/runtime/kernel_args.hpp
index 09dfcf68f05..9a26768d0fc 100644
--- a/src/plugins/intel_gpu/include/intel_gpu/runtime/kernel_args.hpp
+++ b/src/plugins/intel_gpu/include/intel_gpu/runtime/kernel_args.hpp
@@ -16,6 +16,11 @@ struct work_group_sizes {
std::vector<size_t> local;
};
+enum class kernel_language {
+ OCLC,
+ CM,
+};
+
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Scalar
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@@ -122,8 +127,10 @@ struct kernel_string {
std::string entry_point;
bool batch_compilation;
bool has_microkernels;
+ kernel_language language;
- kernel_string() : str(""), jit(""), undefs(""), options(""), entry_point(""), batch_compilation(false), has_microkernels(false) {}
+ kernel_string() : str(""), jit(""), undefs(""), options(""), entry_point(""),
+ batch_compilation(false), has_microkernels(false), language(kernel_language::OCLC) {}
std::string get_str() const { return str + jit + undefs + options + entry_point; }
size_t get_hash() const { return std::hash<std::string>()(get_str()); }
diff --git a/src/plugins/intel_gpu/src/graph/impls/cm/impl_example.cpp b/src/plugins/intel_gpu/src/graph/impls/cm/impl_example.cpp
new file mode 100644
index 00000000000..c4ec8da18c7
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/cm/impl_example.cpp
@@ -0,0 +1,66 @@
+// Copyright (C) 2018-2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "impls/cm/impl_example.hpp"
+
+#include "fully_connected/cm/fully_connected_cm_kernel_selector.h"
+#include "fully_connected/fully_connected_params.h"
+#include "fully_connected_inst.h"
+#include "impls/ocl/primitive_base.hpp"
+
+namespace cldnn {
+namespace cm {
+
+struct example_impl : ocl::typed_primitive_impl_ocl<fully_connected> {
+ using parent = typed_primitive_impl_ocl<fully_connected>;
+ using parent::parent;
+ using kernel_selector_t = kernel_selector::fully_connected_cm_kernel_selector;
+ using kernel_params_t = kernel_selector::fully_connected_params;
+
+ DECLARE_OBJECT_TYPE_SERIALIZATION(cldnn::cm::example_impl)
+
+ example_impl() = default;
+
+ std::unique_ptr<primitive_impl> clone() const override {
+ return make_deep_copy<example_impl, kernel_params_t>(*this);
+ }
+
+protected:
+ kernel_arguments_data get_arguments(const typed_primitive_inst<fully_connected>& instance) const override {
+ kernel_arguments_data args = parent::get_arguments(instance);
+ const auto& desc = instance.get_typed_desc<fully_connected>();
+
+ args.weights = instance.weights_memory();
+ args.bias = instance.bias_term() ? instance.bias_memory() : nullptr;
+
+ args.inputs = {instance.input_memory_ptr(0)};
+ size_t in_id = instance.bias_term() ? 3 : 2;
+ if (!desc->decompression_scale.empty())
+ args.inputs.push_back(instance.dep_memory_ptr(in_id++));
+
+ if (!desc->decompression_zero_point.empty())
+ args.inputs.push_back(instance.dep_memory_ptr(in_id));
+
+ return args;
+ }
+
+public:
+ static kernel_params_t get_kernel_params(const kernel_impl_params& impl_param, bool is_shape_agnostic = false) {
+ auto params = get_weights_bias_default_params<kernel_selector::fully_connected_params>(impl_param,
+ false,
+ is_shape_agnostic);
+ return params;
+ }
+};
+std::unique_ptr<primitive_impl> ExampleImplementationManager::create_impl(const program_node& node,
+ const kernel_impl_params& params) const {
+ OPENVINO_ASSERT(node.is_type<fully_connected>());
+ return ocl::typed_primitive_impl_ocl<fully_connected>::create<example_impl>(
+ static_cast<const fully_connected_node&>(node),
+ params);
+}
+} // namespace cm
+} // namespace cldnn
+
+BIND_BINARY_BUFFER_WITH_TYPE(cldnn::cm::example_impl)
diff --git a/src/plugins/intel_gpu/src/graph/impls/cm/impl_example.hpp b/src/plugins/intel_gpu/src/graph/impls/cm/impl_example.hpp
new file mode 100644
index 00000000000..0208da12a2f
--- /dev/null
+++ b/src/plugins/intel_gpu/src/graph/impls/cm/impl_example.hpp
@@ -0,0 +1,36 @@
+// Copyright (C) 2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <memory>
+
+#include "fully_connected_inst.h"
+#include "impls/registry/implementation_manager.hpp"
+
+namespace cldnn {
+namespace cm {
+
+struct ExampleImplementationManager : public ImplementationManager {
+ OV_GPU_PRIMITIVE_IMPL("cm::example")
+ ExampleImplementationManager(shape_types shape_type, ValidateFunc vf = nullptr)
+ : ImplementationManager(impl_types::cm, shape_type, vf) {}
+
+ std::unique_ptr<primitive_impl> create_impl(const program_node& node,
+ const kernel_impl_params& params) const override;
+
+ bool validate_impl(const program_node& node) const override {
+ assert(node.is_type<fully_connected>());
+
+ auto &engine = node.get_program().get_engine();
+ auto &config = node.get_program().get_config();
+ if (!check_cm_jit_support(engine, config)) {
+ return false;
+ }
+
+ // Example impl should not be chosen unless forced
+ return false;
+ }
+};
+
+} // namespace cm
+} // namespace cldnn
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl/kernel_selector_helper.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl/kernel_selector_helper.cpp
index 42d83a0265d..7d54129195c 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl/kernel_selector_helper.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl/kernel_selector_helper.cpp
@@ -121,6 +121,46 @@ bool query_local_block_io_supported(engine& e, const ExecutionConfig& config) {
namespace cldnn {
+bool check_cm_jit_support(cldnn::engine& e, const cldnn::ExecutionConfig& config) {
+ auto device = e.get_device().get();
+
+ static std::mutex m;
+ std::lock_guard<std::mutex> lock(m);
+
+ static std::map<cldnn::device*, bool> cache;
+ if (cache.find(device) != cache.end()) {
+ return cache.at(device);
+ }
+
+ std::shared_ptr<kernel_selector::KernelString> kernel_string = std::make_shared<kernel_selector::KernelString>();
+ // This program checks if cm sources can be jitted by current IGC version
+ const char* kernel_code = R""""(
+ #include <cm/cm.h>
+ #include <cm/cmtl.h>
+
+ extern "C" _GENX_MAIN_ void cm_check() {
+ unsigned int id = cm_linear_global_id();
+ }
+ )"""";
+
+ kernel_string->str = kernel_code;
+ kernel_string->options = " -cmc ";
+ kernel_string->entry_point = "cm_check";
+ kernel_string->batch_compilation = true;
+
+ try {
+ cldnn::kernel_impl_params dummy_params;
+ auto _kernels_cache_device_query = std::unique_ptr<cldnn::kernels_cache>(new cldnn::kernels_cache(e, config, 0));
+ _kernels_cache_device_query->add_kernels_source(dummy_params, {kernel_string}, false);
+ _kernels_cache_device_query->build_all();
+ cache[device] = true;
+ } catch (std::exception&) {
+ cache[device] = false;
+ }
+
+ return cache.at(device);
+}
+
bool query_microkernels_supported(cldnn::engine& e, const cldnn::ExecutionConfig& config) {
auto device = e.get_device().get();
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl/kernel_selector_helper.h b/src/plugins/intel_gpu/src/graph/impls/ocl/kernel_selector_helper.h
index a8c715af98f..bf8968fd4b2 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl/kernel_selector_helper.h
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl/kernel_selector_helper.h
@@ -306,6 +306,7 @@ inline void update_shapes(kernel_selector::Params& p, const kernel_impl_params&
}
}
+bool check_cm_jit_support(cldnn::engine& e, const cldnn::ExecutionConfig& config);
bool query_microkernels_supported(cldnn::engine& e, const cldnn::ExecutionConfig& config);
} // namespace cldnn
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl/kernels_cache.cpp b/src/plugins/intel_gpu/src/graph/impls/ocl/kernels_cache.cpp
index 5db452dcda2..b122195c8e1 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl/kernels_cache.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl/kernels_cache.cpp
@@ -153,8 +153,12 @@ void kernels_cache::get_program_source(const kernels_code& kernels_source_code,
std::string entry_point = kernel_string->entry_point;
std::string options = kernel_string->options;
bool batch_compilation = kernel_string->batch_compilation;
+ bool is_cm = kernel_string->language == kernel_language::CM;
- if (batch_compilation) {
+ auto& headers = is_cm ? cm_batch_headers : batch_headers;
+
+ // Order matters for cm options
+ if (batch_compilation && !is_cm) {
options = reorder_options(options);
}
@@ -174,7 +178,7 @@ void kernels_cache::get_program_source(const kernels_code& kernels_source_code,
const auto& batch_id = 0;
// increase bucket id if and only if new bucket comes
bucket_id = static_cast<int32_t>(program_buckets.size() - 1);
- current_bucket.push_back(batch_program(bucket_id, batch_id, options, batch_headers));
+ current_bucket.push_back(batch_program(bucket_id, batch_id, options, headers, is_cm));
}
// This is a temporary walk-around to avoid severe performance drop.
@@ -205,7 +209,7 @@ void kernels_cache::get_program_source(const kernels_code& kernels_source_code,
|| current_bucket.back().entry_point_to_id.find(entry_point) != current_bucket.back().entry_point_to_id.end()
|| need_separate_batch(entry_point)) {
const auto& batch_id = static_cast<int32_t>(current_bucket.size());
- current_bucket.push_back(batch_program(bucket_id, batch_id, options, batch_headers));
+ current_bucket.push_back(batch_program(bucket_id, batch_id, options, headers, is_cm));
}
auto& current_batch = current_bucket.back();
@@ -270,12 +274,14 @@ kernels_cache::kernels_cache(engine& engine,
const ExecutionConfig& config,
uint32_t prog_id,
std::shared_ptr<ov::threading::ITaskExecutor> task_executor,
- const std::map<std::string, std::string>& batch_headers)
+ const std::map<std::string, std::string>& batch_headers,
+ const std::map<std::string, std::string>& cm_batch_headers)
: _device(get_target_device(engine))
, _task_executor(task_executor)
, _config(config)
, _prog_id(prog_id)
- , batch_headers(std::move(batch_headers)) { }
+ , batch_headers(std::move(batch_headers))
+ , cm_batch_headers(std::move(cm_batch_headers)) { }
static std::vector<unsigned char> getProgramBinaries(cl::Program program) {
// Get the size of the program binary in bytes.
diff --git a/src/plugins/intel_gpu/src/graph/impls/ocl/kernels_cache.hpp b/src/plugins/intel_gpu/src/graph/impls/ocl/kernels_cache.hpp
index b08b087c558..1bb0ffbd206 100644
--- a/src/plugins/intel_gpu/src/graph/impls/ocl/kernels_cache.hpp
+++ b/src/plugins/intel_gpu/src/graph/impls/ocl/kernels_cache.hpp
@@ -58,7 +58,11 @@ public:
bool has_microkernels;
std::map<std::string, std::pair<kernel_impl_params, size_t>> entry_point_to_id;
- explicit batch_program(int32_t _bucket_id, int32_t _batch_id, std::string _options, const std::map<std::string, std::string>& batch_headers)
+ explicit batch_program(int32_t _bucket_id,
+ int32_t _batch_id,
+ std::string _options,
+ const std::map<std::string, std::string>& batch_headers,
+ bool is_cm = false)
: bucket_id(_bucket_id),
batch_id(_batch_id),
hash_value(0),
@@ -68,17 +72,22 @@ public:
dump_custom_program(false),
has_microkernels(false),
entry_point_to_id({}) {
- static const std::vector<std::string> micro_kernel_include_names {
- "generic_vector_ops",
- "tile_ops",
- "sdpa_utils"
- };
- for (const auto& kv : batch_headers) {
- if (std::find(micro_kernel_include_names.begin(), micro_kernel_include_names.end(), kv.first) == micro_kernel_include_names.end()) {
- source.push_back(kv.second);
- } else {
- micro_headers.push_back(kv.second);
+ if (!is_cm) {
+ static const std::vector<std::string> micro_kernel_include_names {
+ "generic_vector_ops",
+ "tile_ops",
+ "sdpa_utils"
+ };
+ for (const auto& kv : batch_headers) {
+ if (std::find(micro_kernel_include_names.begin(), micro_kernel_include_names.end(), kv.first) == micro_kernel_include_names.end()) {
+ source.push_back(kv.second);
+ } else {
+ micro_headers.push_back(kv.second);
+ }
}
+ } else {
+ for (const auto& kv : batch_headers)
+ source.push_back(kv.second);
}
}
};
@@ -97,6 +106,7 @@ private:
std::map<std::vector<unsigned char>, uint32_t> _cached_binaries;
std::unordered_map<std::string, kernel::ptr> _cached_kernels;
std::map<std::string, std::string> batch_headers;
+ std::map<std::string, std::string> cm_batch_headers;
std::unordered_map<kernel_impl_params, size_t, impl_hasher> _kernel_batch_hash;
void get_program_source(const kernels_code& kernels_source_code, std::vector<batch_program>*) const;
void build_batch(const batch_program& batch, compiled_kernels& compiled_kernels);
@@ -112,7 +122,8 @@ public:
const ExecutionConfig& config,
uint32_t prog_id,
std::shared_ptr<ov::threading::ITaskExecutor> task_executor = nullptr,
- const std::map<std::string, std::string>& batch_headers = {});
+ const std::map<std::string, std::string>& batch_headers = {},
+ const std::map<std::string, std::string>& cm_batch_headers = {});
kernel::ptr get_kernel_from_cached_kernels(std::string id) const;
std::vector<kernel::ptr> get_kernels(const kernel_impl_params& params) const;
diff --git a/src/plugins/intel_gpu/src/graph/impls/registry/fully_connected_impls.cpp b/src/plugins/intel_gpu/src/graph/impls/registry/fully_connected_impls.cpp
index 6f725150794..6ea9eb33c74 100644
--- a/src/plugins/intel_gpu/src/graph/impls/registry/fully_connected_impls.cpp
+++ b/src/plugins/intel_gpu/src/graph/impls/registry/fully_connected_impls.cpp
@@ -11,6 +11,10 @@
#include "impls/onednn/fully_connected_onednn.hpp"
#endif
+#if OV_GPU_WITH_CM
+ #include "impls/cm/impl_example.hpp"
+#endif
+
namespace ov {
namespace intel_gpu {
@@ -26,6 +30,7 @@ const std::vector<std::shared_ptr<cldnn::ImplementationManager>>& Registry<fully
return false;
return node.get_output_pshape().size() <= 3;
})
+ OV_GPU_CREATE_INSTANCE_CM(cm::ExampleImplementationManager, shape_types::static_shape)
};
return impls;
diff --git a/src/plugins/intel_gpu/src/graph/impls/registry/registry.hpp b/src/plugins/intel_gpu/src/graph/impls/registry/registry.hpp
index b2778233f41..3d57a76e60d 100644
--- a/src/plugins/intel_gpu/src/graph/impls/registry/registry.hpp
+++ b/src/plugins/intel_gpu/src/graph/impls/registry/registry.hpp
@@ -19,6 +19,7 @@
#define OV_GPU_WITH_OCL 1
#define OV_GPU_WITH_COMMON 1
#define OV_GPU_WITH_CPU 1
+#define OV_GPU_WITH_CM 1
#define COUNT_N(_1, _2, _3, _4, _5, N, ...) N
#define COUNT(...) EXPAND(COUNT_N(__VA_ARGS__, 5, 4, 3, 2, 1))
@@ -63,6 +64,12 @@
# define OV_GPU_CREATE_INSTANCE_SYCL(...)
#endif
+#if OV_GPU_WITH_CM
+# define OV_GPU_CREATE_INSTANCE_CM(...) EXPAND(CREATE_INSTANCE(__VA_ARGS__))
+#else
+# define OV_GPU_CREATE_INSTANCE_CM(...)
+#endif
+
#if OV_GPU_WITH_OCL
# define OV_GPU_CREATE_INSTANCE_OCL(...) EXPAND(CREATE_INSTANCE(__VA_ARGS__))
# define OV_GPU_GET_INSTANCE_OCL(prim, ...) EXPAND(SELECT(COUNT(__VA_ARGS__), prim, impl_types::ocl, __VA_ARGS__))
diff --git a/src/plugins/intel_gpu/src/graph/program.cpp b/src/plugins/intel_gpu/src/graph/program.cpp
index b71b0cdc77e..c938be22b81 100644
--- a/src/plugins/intel_gpu/src/graph/program.cpp
+++ b/src/plugins/intel_gpu/src/graph/program.cpp
@@ -228,7 +228,8 @@ void program::init_program() {
if (_task_executor == nullptr)
_task_executor = program::make_task_executor(_config);
_kernels_cache = std::unique_ptr<kernels_cache>(new kernels_cache(_engine, _config, prog_id, _task_executor,
- kernel_selector::KernelBase::get_db().get_batch_headers()));
+ kernel_selector::KernelBase::get_db().get_batch_headers(),
+ kernel_selector::KernelBase::get_db().get_cm_batch_headers()));
_kernels_cache->set_kernels_reuse(get_config().get_property(ov::intel_gpu::hint::enable_kernels_reuse));
diff --git a/src/plugins/intel_gpu/src/kernel_selector/CMakeLists.txt b/src/plugins/intel_gpu/src/kernel_selector/CMakeLists.txt
index 2b32423f9ce..0c29c8afb9f 100644
--- a/src/plugins/intel_gpu/src/kernel_selector/CMakeLists.txt
+++ b/src/plugins/intel_gpu/src/kernel_selector/CMakeLists.txt
@@ -11,11 +11,16 @@ file(GLOB_RECURSE LIBRARY_SRC
"${CMAKE_CURRENT_SOURCE_DIR}/*.hpp"
"${CMAKE_CURRENT_SOURCE_DIR}/*.cpp"
)
+list(FILTER LIBRARY_SRC EXCLUDE REGEX "${CMAKE_CURRENT_SOURCE_DIR}/cm_kernels/.*" )
file(GLOB_RECURSE KERNELS
"${CMAKE_CURRENT_SOURCE_DIR}/cl_kernels/*.cl"
)
+file(GLOB_RECURSE CM_KERNELS
+ "${CMAKE_CURRENT_SOURCE_DIR}/cm_kernels/*"
+)
+
# Path which points to root directory where code generated elements are created
# (specific to build configuration).
set(CODEGEN_DIR "${CMAKE_CURRENT_BINARY_DIR}/codegen")
@@ -28,8 +33,12 @@ set(CODEGEN_INCDIR "${CODEGEN_DIR}/include")
set(PRIM_DB "ks_primitive_db.inc")
set(PRIM_DB_BATCH_HEADERS "ks_primitive_db_batch_headers.inc")
+set(CM_PRIM_DB "ks_cm_primitive_db.inc")
+set(CM_PRIM_DB_BATCH_HEADERS "ks_cm_primitive_db_batch_headers.inc")
set(CODEGEN_CACHE_SOURCES "${CODEGEN_INCDIR}/${PRIM_DB}"
- "${CODEGEN_INCDIR}/${PRIM_DB_BATCH_HEADERS}")
+ "${CODEGEN_INCDIR}/${PRIM_DB_BATCH_HEADERS}"
+ "${CODEGEN_INCDIR}/${CM_PRIM_DB}"
+ "${CODEGEN_INCDIR}/${CM_PRIM_DB_BATCH_HEADERS}")
set(CODEGEN_SCRIPT "${CMAKE_CURRENT_SOURCE_DIR}/primitive_db_gen.py")
# Helping with some generators.
@@ -52,6 +61,22 @@ add_custom_command(OUTPUT "${CODEGEN_INCDIR}/${PRIM_DB}"
COMMENT "Updating file if the file changed (${PRIM_DB}) ..."
)
+add_custom_command(OUTPUT "${CODEGEN_CACHE_DIR}/${CM_PRIM_DB}"
+ COMMAND "${Python3_EXECUTABLE}" "${CODEGEN_SCRIPT}" -out_path "${CODEGEN_CACHE_DIR}"
+ -out_file_name_prim_db "${CM_PRIM_DB}"
+ -out_file_name_batch_headers "${CM_PRIM_DB_BATCH_HEADERS}"
+ -kernels "${CMAKE_CURRENT_SOURCE_DIR}/cm_kernels" -cm
+ DEPENDS ${CM_KERNELS} "${CODEGEN_SCRIPT}" "${CODEGEN_INCDIR}/${PRIM_DB}"
+ COMMENT "Generating ${CODEGEN_CACHE_DIR}/${CM_PRIM_DB} ..."
+)
+
+add_custom_command(OUTPUT "${CODEGEN_INCDIR}/${CM_PRIM_DB}"
+ COMMAND "${CMAKE_COMMAND}" -E copy_if_different "${CODEGEN_CACHE_DIR}/${CM_PRIM_DB}" "${CODEGEN_INCDIR}/${CM_PRIM_DB}"
+ COMMAND "${CMAKE_COMMAND}" -E copy_if_different "${CODEGEN_CACHE_DIR}/${CM_PRIM_DB_BATCH_HEADERS}" "${CODEGEN_INCDIR}/${CM_PRIM_DB_BATCH_HEADERS}"
+ DEPENDS "${CODEGEN_CACHE_DIR}/${CM_PRIM_DB}" "${CM_KERNELS}" "${CODEGEN_SCRIPT}" "${CODEGEN_INCDIR}/${PRIM_DB}"
+ COMMENT "Updating file if the file changed (${CM_PRIM_DB}) ..."
+)
+
add_library(${TARGET_NAME} STATIC ${LIBRARY_SRC} ${CODEGEN_CACHE_SOURCES})
if(NOT BUILD_SHARED_LIBS)
diff --git a/src/plugins/intel_gpu/src/kernel_selector/cm_kernels/example.cpp b/src/plugins/intel_gpu/src/kernel_selector/cm_kernels/example.cpp
new file mode 100644
index 00000000000..abee70f6483
--- /dev/null
+++ b/src/plugins/intel_gpu/src/kernel_selector/cm_kernels/example.cpp
@@ -0,0 +1,26 @@
+// Copyright (C) 2018-2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+namespace KERNEL_NAME {
+
+#include "include/example_header.h"
+
+extern "C" _GENX_MAIN_ void KERNEL_NAME(svmptr_t x [[type("svmptr_t")]]) {
+ // This kernel prints and exits
+ if (cm_linear_global_id() == 0) {
+ printf("Example CM kernel\n");
+ printf("Pointer address: %p\n", (void*)x);
+
+ // Call function from header
+ print_lws_gws();
+
+ // Check macro from batch header
+#ifdef EXAMPLE_CM_MACRO
+ printf("Batch header included\n");
+#else
+ printf("Batch header not included\n");
+#endif
+ }
+}
+} // namespace KERNEL_NAME
diff --git a/src/plugins/intel_gpu/src/kernel_selector/cm_kernels/include/batch_headers/exmaple_batch_header.h b/src/plugins/intel_gpu/src/kernel_selector/cm_kernels/include/batch_headers/exmaple_batch_header.h
new file mode 100644
index 00000000000..f3f2aa183e8
--- /dev/null
+++ b/src/plugins/intel_gpu/src/kernel_selector/cm_kernels/include/batch_headers/exmaple_batch_header.h
@@ -0,0 +1,5 @@
+// Copyright (C) 2018-2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#define EXAMPLE_CM_MACRO
diff --git a/src/plugins/intel_gpu/src/kernel_selector/cm_kernels/include/example_header.h b/src/plugins/intel_gpu/src/kernel_selector/cm_kernels/include/example_header.h
new file mode 100644
index 00000000000..3ce3a33188d
--- /dev/null
+++ b/src/plugins/intel_gpu/src/kernel_selector/cm_kernels/include/example_header.h
@@ -0,0 +1,8 @@
+// Copyright (C) 2018-2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+inline void print_lws_gws() {
+ printf("lws: %d, %d, %d\n", cm_local_size(0), cm_local_size(1), cm_local_size(2));
+ printf("gws: %d, %d, %d\n", cm_group_count(0), cm_group_count(1), cm_group_count(2));
+}
diff --git a/src/plugins/intel_gpu/src/kernel_selector/kernel_base_cm.h b/src/plugins/intel_gpu/src/kernel_selector/kernel_base_cm.h
new file mode 100644
index 00000000000..32744f65bee
--- /dev/null
+++ b/src/plugins/intel_gpu/src/kernel_selector/kernel_base_cm.h
@@ -0,0 +1,43 @@
+// Copyright (C) 2018-2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "kernel_base.h"
+
+namespace kernel_selector {
+
+class KernelBaseCM : public KernelBase {
+public:
+ using KernelBase::KernelBase;
+ virtual ~KernelBaseCM() {}
+
+protected:
+ virtual bool Validate(const Params&) const {
+ return true;
+ }
+ std::shared_ptr<KernelString> GetKernelString(const std::string& kernel_name,
+ const std::pair<std::string, std::string>& jit,
+ const std::string& entry_point) const {
+ std::shared_ptr<KernelString> kernel_string = std::make_shared<KernelString>();
+
+ bool is_cm = true;
+ auto codes = db.get(kernel_name, is_cm);
+
+ if (codes.size()) {
+ kernel_string->str = codes[0];
+ kernel_string->jit = "#include <cm/cm.h>\n#include <cm/cmtl.h>\n";
+ kernel_string->jit += jit.first;
+ kernel_string->undefs = jit.second;
+ kernel_string->options = " -cmc ";
+
+ kernel_string->entry_point = entry_point;
+ kernel_string->batch_compilation = true;
+ kernel_string->language = KernelLanguage::CM;
+ }
+
+ return kernel_string;
+ }
+};
+} // namespace kernel_selector
diff --git a/src/plugins/intel_gpu/src/kernel_selector/kernel_selector_common.h b/src/plugins/intel_gpu/src/kernel_selector/kernel_selector_common.h
index d9b132ac1dc..b55740110b2 100644
--- a/src/plugins/intel_gpu/src/kernel_selector/kernel_selector_common.h
+++ b/src/plugins/intel_gpu/src/kernel_selector/kernel_selector_common.h
@@ -46,6 +46,7 @@ namespace kernel_selector {
std::string GetStringEnv(const char* varName);
+using KernelLanguage = cldnn::kernel_language;
using KernelString = cldnn::kernel_string;
using WorkGroupSizes = cldnn::work_group_sizes;
using ScalarDescriptor = cldnn::scalar_desc;
diff --git a/src/plugins/intel_gpu/src/kernel_selector/kernels/fully_connected/cm/fully_connected_cm_example.cpp b/src/plugins/intel_gpu/src/kernel_selector/kernels/fully_connected/cm/fully_connected_cm_example.cpp
new file mode 100644
index 00000000000..32719501d93
--- /dev/null
+++ b/src/plugins/intel_gpu/src/kernel_selector/kernels/fully_connected/cm/fully_connected_cm_example.cpp
@@ -0,0 +1,54 @@
+// Copyright (C) 2018-2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "fully_connected_cm_example.h"
+
+namespace kernel_selector {
+KernelsData FullyConnected_cm_example::GetKernelsData(const Params& params) const {
+ if (!Validate(params)) {
+ return {};
+ }
+ auto options = std::string(" -Qxcm_jit_option=-DPASTokenReduction ");
+
+ KernelData kd = KernelData::Default<fully_connected_params>(params, 1);
+ auto& kernel = kd.kernels[0];
+
+ kernel.params.arguments.push_back({ArgumentDescriptor::Types::INPUT, 0});
+ kernel.params.workGroups.local = {1, 2, 4};
+ kernel.params.workGroups.global = {1, 4, 8};
+
+ std::string kernel_name = "fully_connected_cm_example";
+ auto jit = std::pair<std::string, std::string>("\n#define KERNEL_NAME " + kernel_name, "#undef KERNEL_NAME");
+ kernel.code.kernelString = GetKernelString("example", jit, kernel_name);
+ kernel.code.kernelString->options += options;
+ kernel.code.kernelString->batch_compilation = true;
+ return {kd};
+}
+KernelsPriority FullyConnected_cm_example::GetKernelsPriority(const Params& params) const {
+ return TUTORIAL_PRIORITY;
+}
+ParamsKey FullyConnected_cm_example::GetSupportedKey() const {
+ ParamsKey k;
+ k.EnableInputDataType(Datatype::F16);
+ k.EnableOutputDataType(Datatype::F16);
+ k.EnableInputWeightsType(WeightsType::F16);
+ k.EnableInputWeightsType(WeightsType::UINT8);
+ k.EnableAllInputLayout();
+ k.EnableAllOutputLayout();
+ k.EnableDifferentInputWeightsTypes();
+ k.EnableDifferentTypes();
+ k.EnableBiasPerOutput();
+ k.EnableBiasPerFeature();
+ k.EnableNonBiasTerm();
+ k.EnableTensorOffset();
+ k.EnableTensorPitches();
+ k.EnableBatching();
+ k.EnableQuantization(QuantizationType::SYMMETRIC);
+ k.EnableWeightsCompression();
+ return k;
+}
+bool FullyConnected_cm_example::Validate(const Params& p) const {
+ return true;
+}
+} // namespace kernel_selector
diff --git a/src/plugins/intel_gpu/src/kernel_selector/kernels/fully_connected/cm/fully_connected_cm_example.h b/src/plugins/intel_gpu/src/kernel_selector/kernels/fully_connected/cm/fully_connected_cm_example.h
new file mode 100644
index 00000000000..844f3395bd8
--- /dev/null
+++ b/src/plugins/intel_gpu/src/kernel_selector/kernels/fully_connected/cm/fully_connected_cm_example.h
@@ -0,0 +1,21 @@
+// Copyright (C) 2018-2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "../fully_connected_params.h"
+#include "kernel_base_cm.h"
+
+namespace kernel_selector {
+class FullyConnected_cm_example : public KernelBaseCM {
+public:
+ FullyConnected_cm_example() : KernelBaseCM("fully_connected_example") {}
+ virtual ~FullyConnected_cm_example() {}
+
+ KernelsData GetKernelsData(const Params& params) const override;
+ KernelsPriority GetKernelsPriority(const Params& params) const override;
+ ParamsKey GetSupportedKey() const override;
+ bool Validate(const Params& p) const override;
+};
+} // namespace kernel_selector
diff --git a/src/plugins/intel_gpu/src/kernel_selector/kernels/fully_connected/cm/fully_connected_cm_kernel_selector.cpp b/src/plugins/intel_gpu/src/kernel_selector/kernels/fully_connected/cm/fully_connected_cm_kernel_selector.cpp
new file mode 100644
index 00000000000..dfc6d4342b1
--- /dev/null
+++ b/src/plugins/intel_gpu/src/kernel_selector/kernels/fully_connected/cm/fully_connected_cm_kernel_selector.cpp
@@ -0,0 +1,17 @@
+// Copyright (C) 2018-2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "fully_connected_cm_kernel_selector.h"
+
+#include "fully_connected_cm_example.h"
+
+namespace kernel_selector {
+fully_connected_cm_kernel_selector::fully_connected_cm_kernel_selector() {
+ Attach<FullyConnected_cm_example>();
+}
+
+KernelsData fully_connected_cm_kernel_selector::GetBestKernels(const Params& params) const {
+ return GetAutoTuneBestKernel(params, KernelType::FULLY_CONNECTED);
+}
+} // namespace kernel_selector
diff --git a/src/plugins/intel_gpu/src/kernel_selector/kernels/fully_connected/cm/fully_connected_cm_kernel_selector.h b/src/plugins/intel_gpu/src/kernel_selector/kernels/fully_connected/cm/fully_connected_cm_kernel_selector.h
new file mode 100644
index 00000000000..937d605f9eb
--- /dev/null
+++ b/src/plugins/intel_gpu/src/kernel_selector/kernels/fully_connected/cm/fully_connected_cm_kernel_selector.h
@@ -0,0 +1,24 @@
+// Copyright (C) 2018-2024 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "kernel_selector.h"
+
+namespace kernel_selector {
+
+class fully_connected_cm_kernel_selector : public kernel_selector_base {
+public:
+ static fully_connected_cm_kernel_selector& Instance() {
+ static fully_connected_cm_kernel_selector instance_;
+ return instance_;
+ }
+
+ fully_connected_cm_kernel_selector();
+
+ virtual ~fully_connected_cm_kernel_selector() {}
+
+ KernelsData GetBestKernels(const Params& params) const override;
+};
+} // namespace kernel_selector
diff --git a/src/plugins/intel_gpu/src/kernel_selector/primitive_db.cpp b/src/plugins/intel_gpu/src/kernel_selector/primitive_db.cpp
index cd8128baff3..e9fa5dd6756 100644
--- a/src/plugins/intel_gpu/src/kernel_selector/primitive_db.cpp
+++ b/src/plugins/intel_gpu/src/kernel_selector/primitive_db.cpp
@@ -21,16 +21,28 @@ namespace cache {
primitive_db::primitive_db()
: primitives({
#include "ks_primitive_db.inc"
+ }),
+ cm_primitives({
+#include "ks_cm_primitive_db.inc"
}),
batch_headers({
#include "ks_primitive_db_batch_headers.inc"
+ }),
+ cm_batch_headers({
+#include "ks_cm_primitive_db_batch_headers.inc"
}) {
}
-std::vector<code> primitive_db::get(const primitive_id& id) const {
+std::vector<code> primitive_db::get(const primitive_id& id, bool is_cm) const {
#ifndef NDEBUG
{
- std::ifstream kernel_file{id + ".cl", std::ios::in | std::ios::binary};
+ std::string filename = id;
+ if (!is_cm) {
+ filename += ".cl";
+ } else {
+ filename += ".cpp";
+ }
+ std::ifstream kernel_file{filename, std::ios::in | std::ios::binary};
if (kernel_file.is_open()) {
code ret;
auto beg = kernel_file.tellg();
@@ -46,7 +58,11 @@ std::vector<code> primitive_db::get(const primitive_id& id) const {
}
#endif
try {
- const auto codes = primitives.equal_range(id);
+ auto* primitives_ptr = &primitives;
+ if (is_cm) {
+ primitives_ptr = &cm_primitives;
+ }
+ const auto codes = primitives_ptr->equal_range(id);
std::vector<code> temp;
std::for_each(codes.first, codes.second, [&](const std::pair<const std::string, std::string>& c) {
temp.push_back(c.second);
diff --git a/src/plugins/intel_gpu/src/kernel_selector/primitive_db.h b/src/plugins/intel_gpu/src/kernel_selector/primitive_db.h
index e384f6c9879..5c6987246ce 100644
--- a/src/plugins/intel_gpu/src/kernel_selector/primitive_db.h
+++ b/src/plugins/intel_gpu/src/kernel_selector/primitive_db.h
@@ -21,8 +21,9 @@ using primitive_id = std::string;
struct primitive_db {
primitive_db();
- std::vector<code> get(const primitive_id& id) const;
+ std::vector<code> get(const primitive_id& id, bool is_cm = false) const;
std::map<std::string, code> get_batch_headers() const { return std::move(batch_headers); }
+ std::map<std::string, code> get_cm_batch_headers() const { return std::move(cm_batch_headers); }
private:
struct case_insensitive_compare {
@@ -35,7 +36,9 @@ private:
}
};
std::multimap<primitive_id, code, case_insensitive_compare> primitives;
+ std::multimap<primitive_id, code, case_insensitive_compare> cm_primitives;
std::map<std::string, code> batch_headers;
+ std::map<std::string, code> cm_batch_headers;
};
} // namespace cache
diff --git a/src/plugins/intel_gpu/src/kernel_selector/primitive_db_gen.py b/src/plugins/intel_gpu/src/kernel_selector/primitive_db_gen.py
index 116844f3bcc..393e67f3bdb 100644
--- a/src/plugins/intel_gpu/src/kernel_selector/primitive_db_gen.py
+++ b/src/plugins/intel_gpu/src/kernel_selector/primitive_db_gen.py
@@ -6,21 +6,30 @@
# the trailing characters are a tag to allow multiple primitive implementations
from __future__ import print_function
+from enum import Enum
import os
import argparse
import glob
import ntpath
import re
-class OpenCL2CHeaders(object):
+class KernelLang(Enum):
+ OCLC = 0
+ CM = 1
+ def header_extension(self):
+ return (".cl", ".h")[self.value]
+ def source_extension(self):
+ return (".cl", ".cpp")[self.value]
+class Kernels2CHeaders(object):
- def __init__(self, kernels_folder, out_path, out_file_name_prim_db, out_file_name_batch_headers):
+ def __init__(self, kernels_folder, out_path, out_file_name_prim_db, out_file_name_batch_headers, kernel_lang):
self.kernels_folder = os.path.abspath(kernels_folder)
self.out_path = os.path.abspath(out_path)
self.out_file_name_prim_db = out_file_name_prim_db
self.out_file_name_batch_headers = out_file_name_batch_headers
self.include_files = {}
self.batch_headers = []
+ self.kernel_lang = kernel_lang
self.find_and_set_batch_headers()
# NOTE: batch_headers are headers with macros on which the runtime jitter might depend on.
@@ -29,7 +38,7 @@ class OpenCL2CHeaders(object):
# specially for improving the jit compilation performance, i.e.,
# they are not to be included in each kernel, but to be included only once at the beginning of each batch.
def find_and_set_batch_headers(self):
- batch_headers_list = [ntpath.basename(h) for h in glob.glob(os.path.join(self.kernels_folder, "include/batch_headers/*.cl"))]
+ batch_headers_list = [ntpath.basename(h) for h in glob.glob(os.path.join(self.kernels_folder, "include/batch_headers/*" + self.kernel_lang.header_extension()))]
deps = {}
for h in batch_headers_list:
header_file = os.path.abspath(os.path.join(self.kernels_folder, "include/batch_headers", h))
@@ -56,11 +65,11 @@ class OpenCL2CHeaders(object):
def convert(self):
res = '// This file is autogenerated by primitive_db_gen.py, all changes to this file will be undone\n\n'
- filelist = glob.glob(os.path.join(self.kernels_folder, "*.cl"))
+ filelist = glob.glob(os.path.join(self.kernels_folder, "*" + self.kernel_lang.source_extension()))
for filename in filelist:
#try:
print('processing {}'.format(filename))
- res += self.cl_file_to_str(filename)
+ res += self.kernel_file_to_str(filename)
#except:
# pass
out_file_name_prim_db = os.path.join(self.out_path, self.out_file_name_prim_db)
@@ -198,8 +207,8 @@ class OpenCL2CHeaders(object):
characters = 1 # Newline character above
res = ""
for h in self.batch_headers:
- header_name = h[:h.find('.cl')]
- res += '{{"{}",\n(std::string) R"(\n'.format(header_name)
+ header_name = h[:h.rfind('.')]
+ res += '{{"{}",\n(std::string) R"-(\n'.format(header_name)
header_file = os.path.abspath(os.path.join(os.path.dirname(self.kernels_folder + "/include/batch_headers"), "batch_headers/" + h))
content = []
with open(header_file) as f:
@@ -208,11 +217,11 @@ class OpenCL2CHeaders(object):
if line.startswith('#include'):
continue
if (i + 1) % max_lines == 0 or characters + len(line) + 1 > max_characters:
- res += ')"\n + (std::string) R"('
+ res += ')-"\n + (std::string) R"-('
characters = 0
res += '{}\n'.format(line.rstrip())
characters += len(line) + 1
- res += ')"},\n\n'
+ res += ')-"},\n\n'
return self.post_process_sources(res)
def post_process_sources(self, content):
@@ -241,10 +250,10 @@ class OpenCL2CHeaders(object):
return content
- def cl_file_to_str(self, filename):
+ def kernel_file_to_str(self, filename):
name = ntpath.basename(filename)
self.include_files[filename] = {}
- kernel_name = name[:name.find('.cl')]
+ kernel_name = name[:name.rfind('.')]
res = '{{"{}",\n(std::string) R"__krnl(\n'.format(kernel_name)
content = self.append_file_content(filename, filename)
content += self.append_undefs(filename)
@@ -265,16 +274,17 @@ class OpenCL2CHeaders(object):
return res
-
def main():
ap = argparse.ArgumentParser()
ap.add_argument('-kernels', required=True, metavar='PATH', help='The absolute path to OpenCL kernels folder')
ap.add_argument('-out_path', required=True, metavar='PATH', help='The absolute path to dump file')
ap.add_argument('-out_file_name_prim_db', required=True, metavar='PATH', help='dump file name')
ap.add_argument('-out_file_name_batch_headers', required=True, metavar='PATH', help='dump file name')
+ ap.add_argument('-cm', required=False, action='store_true', help='Process CM kernel sources instead of ocl c')
args = ap.parse_args()
- converter = OpenCL2CHeaders(args.kernels, args.out_path, args.out_file_name_prim_db, args.out_file_name_batch_headers)
+ kernel_lang = KernelLang.CM if args.cm else KernelLang.OCLC
+ converter = Kernels2CHeaders(args.kernels, args.out_path, args.out_file_name_prim_db, args.out_file_name_batch_headers, kernel_lang)
converter.convert()
if __name__ == '__main__':
diff --git a/src/plugins/intel_gpu/tests/unit/test_cases/fully_connected_gpu_test.cpp b/src/plugins/intel_gpu/tests/unit/test_cases/fully_connected_gpu_test.cpp
index c3caebe9d0b..5bc7e403d3b 100644
--- a/src/plugins/intel_gpu/tests/unit/test_cases/fully_connected_gpu_test.cpp
+++ b/src/plugins/intel_gpu/tests/unit/test_cases/fully_connected_gpu_test.cpp
@@ -4831,3 +4831,52 @@ TEST_F(fully_connected_gpu_tests, weights_reorder_shapes_update) {
TEST_F(fully_connected_gpu_tests, weights_reorder_shapes_update_cached) {
this->test_weights_reorder_shapes_update(true);
}
+
+TEST(fully_connected_gpu, cm) {
+ int min_random = -2, max_random = 2;
+ auto& engine = get_test_engine();
+ ExecutionConfig config = get_test_default_config(engine);
+
+ if (!cldnn::check_cm_jit_support(engine, config)) {
+ GTEST_SKIP();
+ }
+
+ // Test parameters
+ const int batch_num = 2;
+ const int output_f = 4;
+ const int input_x = 1;
+ const int input_y = 1;
+ const int input_f = 3;
+
+ // Allocate memory
+ auto input_prim = engine.allocate_memory({ data_types::f16, format::bfyx, { batch_num, input_f, input_y, input_x } });
+ auto weights_prim = engine.allocate_memory({ data_types::f16, format::oiyx, { output_f, input_f, input_y, input_x } });
+ auto bias_prim = engine.allocate_memory({ data_types::f16, format::bfyx, { 1, 1, output_f, 1 } });
+
+ // Generate random input data and set values
+ tests::random_generator rg(GET_SUITE_NAME);
+ auto input_data = rg.generate_random_4d<ov::float16>(batch_num, input_f, input_y, input_x, min_random, max_random);
+ auto weights_data = rg.generate_random_4d<ov::float16>(output_f, input_f, input_y, input_x, min_random, max_random);
+ auto bias_data = rg.generate_random_1d<ov::float16>(output_f, min_random, max_random);
+
+ auto input_data_bfyx = flatten_4d(format::bfyx, input_data);
+ auto weights_data_bfyx = flatten_4d(format::bfyx, weights_data);
+ set_values(input_prim, input_data_bfyx);
+ set_values(weights_prim, weights_data_bfyx);
+ set_values(bias_prim, bias_data);
+ topology topology(
+ input_layout("input", input_prim->get_layout()),
+ data("weights", weights_prim),
+ data("bias", bias_prim),
+ fully_connected("fc_prim", input_info("input"), "weights", "bias")
+ );
+ ov::intel_gpu::ImplementationDesc fc_impl_desc = { format::bfyx, "", impl_types::cm };
+ config.set_property(ov::intel_gpu::force_implementations(ov::intel_gpu::ImplForcingMap{ {"fc_prim", fc_impl_desc} }));
+ network network(engine, topology, config);
+ network.set_input_data("input", input_prim);
+ auto outputs = network.execute();
+ ASSERT_EQ(outputs.size(), size_t(1));
+ ASSERT_EQ(outputs.begin()->first, "fc_prim");
+
+ // Do not validate output for CM
+}