OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[GPU] Sample ze (#39323)
Michal Miotkc6347a2a40f9
diff --git a/.github/dockerfiles/docker_tag b/.github/dockerfiles/docker_tagindex c0411b737f8..64079a9b566 100644--- a/.github/dockerfiles/docker_tag+++ b/.github/dockerfiles/docker_tag@@ -1 +1 @@-pr-40010+pr-39323diff --git a/.github/dockerfiles/ov_build/ubuntu_24_04_x64/Dockerfile b/.github/dockerfiles/ov_build/ubuntu_24_04_x64/Dockerfileindex 52ded951c06..e5c4df4cbc8 100644--- a/.github/dockerfiles/ov_build/ubuntu_24_04_x64/Dockerfile+++ b/.github/dockerfiles/ov_build/ubuntu_24_04_x64/Dockerfile@@ -19,8 +19,11 @@ RUN apt-get update && \apt-get install software-properties-common && \add-apt-repository --yes --no-update ppa:git-core/ppa && \add-apt-repository --yes --no-update ppa:deadsnakes/ppa && \+ add-apt-repository --yes --no-update ppa:kobuk-team/intel-graphics && \apt-get update && \apt-get install \+ libze-dev \+ libze1 \curl \git \gpg-agent \@@ -85,4 +88,3 @@ RUN curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py && \# Install newer ninja (apt ships 1.10.1 on 22.04 / 1.11.1 on 24.04; pin for consistency)RUN python3 -m pip install --no-cache-dir ninja==1.13.0-diff --git a/.github/workflows/dev_gpu_linux_level_zero.yml b/.github/workflows/dev_gpu_linux_level_zero.ymlindex 591c6adf609..03fba72543f 100644--- a/.github/workflows/dev_gpu_linux_level_zero.yml+++ b/.github/workflows/dev_gpu_linux_level_zero.yml@@ -90,7 +90,7 @@ jobs:Build:needs: [Docker, Smart_CI]- if: "!needs.smart_ci.outputs.skip_workflow && fromJSON(needs.smart_ci.outputs.affected_components).GPU"+ if: "!needs.smart_ci.outputs.skip_workflow && (fromJSON(needs.smart_ci.outputs.affected_components).GPU || fromJSON(needs.smart_ci.outputs.affected_components).samples)"uses: ./.github/workflows/job_build_linux.ymlwith:runner: 'aks-linux-16-cores-32gb'@@ -147,9 +147,78 @@ jobs:options: "--group-add 44 --group-add 993 --device /dev/dri/renderD129:/dev/dri/renderD129"test_filter: 'smoke_MatMulCompressedWeights_corner_cases*'+ Arc_BMG_dGPU_remote_tensor_sample:+ name: Arc BMG dGPU hello_remote_tensor Sample Level Zero+ needs: [ Build, Docker, Smart_CI ]+ if: fromJSON(needs.smart_ci.outputs.affected_components).GPU.test || fromJSON(needs.smart_ci.outputs.affected_components).samples.test+ timeout-minutes: 30+ runs-on:+ group: 'Intel-GPU'+ labels: [ 'self-hosted', 'dgpu', 'BMG-precommit', 'Linux' ]+ container:+ image: ${{ fromJSON(needs.docker.outputs.images).ov_test.ubuntu_24_04_x64_dgpu }}+ volumes:+ - /usr/local/share/ca-certificates:/usr/local/share/ca-certificates:ro+ - ${{ github.workspace }}:${{ github.workspace }}+ options: "--group-add 44 --group-add 993 --device /dev/dri/renderD129:/dev/dri/renderD129"+ defaults:+ run:+ shell: bash+ env:+ DEBIAN_FRONTEND: noninteractive+ INSTALL_DIR: ${{ github.workspace }}/install+ INSTALL_TEST_DIR: ${{ github.workspace }}/install/tests+ NODE_EXTRA_CA_CERTS: /usr/local/share/ca-certificates/IntelProxyRootCA-Base64.crt # Needed by Node.js actions behind the proxy+ REQUESTS_CA_BUNDLE: /etc/ssl/certs/ca-certificates.crt # Needed by the test's model download (requests) behind the proxy+ steps:+ - name: Download OpenVINO artifacts (package)+ uses: akashchi/download-artifact@d59a9c15fec3fdb7c9adf09464124d00f9c11415 # main+ with:+ name: openvino_package+ path: ${{ env.INSTALL_DIR }}++ - name: Download OpenVINO artifacts (tests)+ uses: akashchi/download-artifact@d59a9c15fec3fdb7c9adf09464124d00f9c11415 # main+ with:+ name: openvino_tests+ path: ${{ env.INSTALL_DIR }}++ - name: Extract OpenVINO packages+ run: |+ pigz -dc openvino_package.tar.gz | tar -xf -+ pigz -dc openvino_tests.tar.gz | tar -xf -+ working-directory: ${{ env.INSTALL_DIR }}++ - name: Verify devices+ timeout-minutes: 5+ run: clinfo++ - name: Add proxy CA certificate to system trust store+ run: update-ca-certificates++ - name: hello_remote_tensor sample tests+ env:+ TEST_DEVICE: 'GPU;GPU.0'+ OV_REQUIRE_REMOTE_TENSOR_SAMPLE: '1'+ run: |+ export IE_APP_PATH=$INSTALL_DIR/samples_bin+ python3 -m pip install -r $INSTALL_TEST_DIR/smoke_tests/requirements.txt pytest-timeout==2.4.0+ source ${INSTALL_DIR}/setupvars.sh+ python3 -m pytest $INSTALL_TEST_DIR/smoke_tests/test_hello_remote_tensor.py \+ -v -ra --timeout=180 \+ --junitxml=$INSTALL_TEST_DIR/TEST-hello_remote_tensor.xml++ - name: Upload Test Results+ uses: ababushk/upload-artifact@ebc7d74ace101c08868aed05dba2aaf274b9a2c7 # main+ if: always()+ with:+ name: test-results-hello_remote_tensor-dgpu+ path: ${{ env.INSTALL_TEST_DIR }}/TEST-hello_remote_tensor.xml+ if-no-files-found: 'warn'+Overall_Status:name: ci/gha_overall_status_dev_gpu_linux_level_zero- needs: [ Smart_CI, Docker, Build, Arc_BMG_dGPU_unit, Arc_BMG_dGPU_func ]+ needs: [ Smart_CI, Docker, Build, Arc_BMG_dGPU_unit, Arc_BMG_dGPU_func, Arc_BMG_dGPU_remote_tensor_sample ]if: ${{ always() }}runs-on: ubuntu-lateststeps:diff --git a/docs/articles_en/get-started/learn-openvino/openvino-samples.rst b/docs/articles_en/get-started/learn-openvino/openvino-samples.rstindex fdb14fe635a..5c43b5f262c 100644--- a/docs/articles_en/get-started/learn-openvino/openvino-samples.rst+++ b/docs/articles_en/get-started/learn-openvino/openvino-samples.rst@@ -16,6 +16,7 @@ OpenVINO™ SamplesGet Started with C++ Samples <openvino-samples/get-started-demos>openvino-samples/hello-classification+ openvino-samples/hello-remote-tensoropenvino-samples/hello-nv12-input-classificationopenvino-samples/hello-query-deviceopenvino-samples/hello-reshape-ssd@@ -37,14 +38,23 @@ The applications include:.. important::All C++ samples support input paths containing only ASCII characters, except- for the Hello Classification Sample, which supports Unicode.+ for the Hello Classification Sample and the Hello Remote Tensor Sample, which+ support Unicode paths on Linux. On Windows, use ASCII-only paths.- :doc:`Hello Classification Sample <openvino-samples/hello-classification>` -Inference of image classification networks like AlexNet and GoogLeNet usingSynchronous Inference Request API. Input of any size and layout can be set toan infer request which will be pre-processed automatically during inference.- The sample supports only images as input and supports input paths containing- only Unicode characters.+ The sample supports only images as input. Input paths may contain Unicode+ characters on Linux; on Windows, they must contain only ASCII characters.++- :doc:`Hello Remote Tensor Sample <openvino-samples/hello-remote-tensor>` -+ Inference of image classification networks on an Intel GPU, with input and+ output tensors allocated in Level Zero device memory. The sample supports+ only images as input. Input paths may contain Unicode characters on Linux;+ on Windows, they must contain only ASCII characters. With the OpenCL GPU+ runtime, it requires a driver with Level Zero - OpenCL interoperability (LEO)+ enabled; the experimental Level Zero GPU runtime is also supported.- :doc:`Hello NV12 Input Classification Sample <openvino-samples/hello-nv12-input-classification>` -Input of any size and layout can be provided to an infer request. The samplediff --git a/docs/articles_en/get-started/learn-openvino/openvino-samples/hello-remote-tensor.rst b/docs/articles_en/get-started/learn-openvino/openvino-samples/hello-remote-tensor.rstnew file mode 100644index 00000000000..6915534740d--- /dev/null+++ b/docs/articles_en/get-started/learn-openvino/openvino-samples/hello-remote-tensor.rst@@ -0,0 +1,96 @@+Hello Remote Tensor Sample+==========================+++.. meta::+ :description: Learn how to run image classification on an Intel GPU+ using Level Zero remote tensors (C++).+++This sample demonstrates how to integrate OpenVINO into an existing Level Zero+application. It runs image classification on an Intel GPU with input and output+tensors allocated in Level Zero device memory. OpenVINO does not provide a+dedicated Level Zero remote context, so the sample uses Level Zero - OpenCL+interoperability (LEO) of the GPU driver to convert the GPU plugin's OpenCL+context to its Level Zero context. Requirements:++- An Intel GPU with a driver that supports LEO.+- OpenVINO with the GPU plugin, built with any runtime (``GPU_RT_TYPE=OCL``,+ ``ZE`` or ``COMBINED``). With the OpenCL runtime (``GPU_RT_TYPE=OCL``) LEO is+ a hard requirement: without it the sample always fails, because the plugin+ has no Level Zero context to offer. The Level Zero runtime (``ZE`` or+ ``COMBINED``) falls back to a native Level Zero context on a driver without LEO.+- Level Zero headers and loader library (``ze_loader``), and OpenCL development+ files (headers and the ICD loader library), to build the sample. On Ubuntu,+ install the Level Zero development files with ``sudo apt install libze-dev``.+ OpenCL is used for a single call, ``clGetContextInfo(..., CL_L0_CONTEXT_HANDLE, ...)``.+ The OpenCL ICD loader is linked, so it is also required at run time, even when the+ plugin provides a Level Zero context directly. On Ubuntu, install the OpenCL+ development files with ``sudo apt install ocl-icd-opencl-dev``; the runtime loader+ is provided by ``ocl-icd-libopencl1``, and the Intel GPU OpenCL driver by+ ``intel-opencl-icd``.+ CMake skips this sample with a status message if any of them is missing,+ unless the sample was selected explicitly with ``BUILD_SAMPLE_NAME``, in which+ case the configuration fails with an error. At run time, the Level Zero+ loader is provided by the GPU driver (on Ubuntu, the ``libze1`` package).+- A model with one input and one output, in any format supported by+ ``ov::Core::read_model``.+- A directly selected GPU device, for example ``GPU`` or ``GPU.0``.+ CPU, AUTO, MULTI, and HETERO are not supported.+- To build the sample, use instructions available at :ref:`Build the Sample Applications <build-samples>`+ section in "Get Started with Samples" guide.++How It Works+####################++The sample is a Level Zero variant of :doc:`Hello Classification <hello-classification>`.+It takes the GPU plugin's default remote context, which is an OpenCL context,+and converts it to the underlying Level Zero context with the LEO query+``clGetContextInfo(..., CL_L0_CONTEXT_HANDLE, ...)``. Then it compiles the model+in that context, creates ``USM_DEVICE_BUFFER`` remote tensors for the input and+output, and moves data between host and device memory with a Level Zero command+list. USM device pointers of the remote tensors are shared by OpenCL and Level+Zero, so they need no conversion. Only when the Level Zero GPU plugin runs on a+driver without LEO, the default context is already a Level Zero context+(``ov::intel_gpu::ContextType::ZE``) and is used directly.++.. tab-set::++ .. tab-item:: C+++ :sync: cpp++ .. scrollbox::++ .. doxygensnippet:: samples/cpp/hello_remote_tensor/main.cpp+ :language: cpp+++Running+####################++.. code-block:: console++ hello_remote_tensor <path_to_model> <path_to_image> <device_name>++For example:++.. code-block:: console++ hello_remote_tensor ./models/squeezenet1.1.xml ./images/dog.png GPU` model or the ``squeezenet1.1`` IR model that is used by the smoke tests.++.. note::++ - The sample expects input with BGR channel order and the NCHW layout for+ the model input, as described in :doc:`Hello Classification <hello-classification>`.+ - Paths may contain Unicode characters on Linux. On Windows, use ASCII-only paths.++The application logs model information and prints the top 10 classification+results.++Additional Resources+####################++- :doc:`Integrate the OpenVINO™ Runtime with Your Application <../../../openvino-workflow/running-inference>`+- :doc:`Get Started with Samples <get-started-demos>`+- :doc:`Using OpenVINO Samples <../openvino-samples>`+- `Hello Remote Tensor C++ Sample on Github <https://github.com/openvinotoolkit/openvino/blob/master/samples/cpp/hello_remote_tensor/README.md>`__diff --git a/samples/cpp/CMakeLists.txt b/samples/cpp/CMakeLists.txtindex f7942fa8fcc..a8ba91d4149 100644--- a/samples/cpp/CMakeLists.txt+++ b/samples/cpp/CMakeLists.txt@@ -291,6 +291,7 @@ set(samples_dirshello_classificationhello_nv12_input_classificationhello_query_device+ hello_remote_tensorhello_reshape_ssdmodel_creation_sample)diff --git a/samples/cpp/hello_remote_tensor/CMakeLists.txt b/samples/cpp/hello_remote_tensor/CMakeLists.txtnew file mode 100644index 00000000000..7a78dcc5cf8--- /dev/null+++ b/samples/cpp/hello_remote_tensor/CMakeLists.txt@@ -0,0 +1,88 @@+# Copyright (C) 2018-2026 Intel Corporation+# SPDX-License-Identifier: Apache-2.0+#++# A status message is easy to miss, so fail when the sample was explicitly requested via BUILD_SAMPLE_NAME.+function(hello_remote_tensor_unavailable reason)+ if(BUILD_SAMPLE_NAME AND "hello_remote_tensor" IN_LIST BUILD_SAMPLE_NAME)+ message(FATAL_ERROR "hello_remote_tensor was requested via BUILD_SAMPLE_NAME but cannot be built: ${reason}")+ endif()+ message(STATUS "hello_remote_tensor SKIPPED: ${reason}")+endfunction()++# Level Zero headers and the loader library are build dependencies; the sample calls Level Zero directly.+set(LEVEL_ZERO_MIN_API_VERSION_MAJOR 1)+set(LEVEL_ZERO_MIN_API_VERSION_MINOR 11)++# The loader is always the system one (the Level Zero SDK or a distribution package), in-tree and standalone alike.+# It is provided by the GPU driver at run time, so no ze_loader library is built or copied next to the sample:+# a bundled loader could be older or newer than the driver and shadow the installed one.+# Standard CMake search (CMAKE_PREFIX_PATH, system paths) plus the location published by the Level Zero SDK+# installer in LEVEL_ZERO_V1_SDK_PATH. No hardcoded locations.+find_library(LEVEL_ZERO_LOADER_LIBRARY NAMES ze_loader+ HINTS ENV LEVEL_ZERO_V1_SDK_PATH+ PATH_SUFFIXES lib lib64)++if(TARGET LevelZero::Headers)+ # In-tree OpenVINO build, the same way as the GPU and NPU plugins consume Level Zero headers: they are staged+ # into the build tree by 'prepare_ze_headers' (after configure), so only the target carries their location.+ set(LEVEL_ZERO_HEADER_TARGET LevelZero::Headers)+ # ze_api.h to check the version in: the bundled submodule or the system package (pkg-config).+ find_file(LEVEL_ZERO_API_HEADER ze_api.h+ HINTS "${level_zero_INCLUDEDIR}"+ "${OpenVINO_SOURCE_DIR}/thirdparty/level_zero/level-zero/include"+ PATH_SUFFIXES level_zero+ NO_DEFAULT_PATH)+else()+ find_path(LEVEL_ZERO_INCLUDE_DIR NAMES level_zero/ze_api.h+ HINTS ENV LEVEL_ZERO_V1_SDK_PATH+ PATH_SUFFIXES include)+ if(LEVEL_ZERO_INCLUDE_DIR)+ set(LEVEL_ZERO_API_HEADER "${LEVEL_ZERO_INCLUDE_DIR}/level_zero/ze_api.h")+ endif()+endif()++if(NOT LEVEL_ZERO_API_HEADER)+ hello_remote_tensor_unavailable("Level Zero headers are required")+ return()+endif()+if(NOT LEVEL_ZERO_LOADER_LIBRARY)+ hello_remote_tensor_unavailable("the system Level Zero loader library (ze_loader) is required")+ return()+endif()++# Always verify the API version of the headers, whatever their source is.+file(STRINGS "${LEVEL_ZERO_API_HEADER}" _ze_version_line+ REGEX "#define[ \t]+ZE_API_VERSION_CURRENT_M[ \t]" LIMIT_COUNT 1)+string(REGEX MATCH "ZE_MAKE_VERSION\\([ \t]*([0-9]+)[ \t]*,[ \t]*([0-9]+)[ \t]*\\)" _ze_version "${_ze_version_line}")+if(NOT _ze_version)+ hello_remote_tensor_unavailable("cannot read Level Zero API version from ${LEVEL_ZERO_API_HEADER}")+ return()+endif()+set(_ze_major ${CMAKE_MATCH_1})+set(_ze_minor ${CMAKE_MATCH_2})+if(_ze_major LESS LEVEL_ZERO_MIN_API_VERSION_MAJOR OR+ (_ze_major EQUAL LEVEL_ZERO_MIN_API_VERSION_MAJOR AND _ze_minor LESS LEVEL_ZERO_MIN_API_VERSION_MINOR))+ hello_remote_tensor_unavailable("Level Zero API v${LEVEL_ZERO_MIN_API_VERSION_MAJOR}.${LEVEL_ZERO_MIN_API_VERSION_MINOR} "+ "or newer is required, found v${_ze_major}.${_ze_minor} in ${LEVEL_ZERO_API_HEADER}")+ return()+endif()+message(STATUS "hello_remote_tensor: Level Zero API v${_ze_major}.${_ze_minor} (${LEVEL_ZERO_API_HEADER})")++# OpenCL is a build dependency used for a single call, clGetContextInfo(CL_L0_CONTEXT_HANDLE), which converts the+# GPU plugin's OpenCL context to its Level Zero context on drivers with Level Zero - OpenCL interoperability (LEO).+# The cl_context comes from the GPU plugin, which links the same OpenCL::OpenCL in-tree, so the query goes through+# the same ICD loader that created the context.+if(NOT TARGET OpenCL::OpenCL)+ find_package(OpenCL QUIET)+ if(NOT TARGET OpenCL::OpenCL)+ hello_remote_tensor_unavailable("OpenCL headers and library are required")+ return()+ endif()+endif()++ov_add_sample(NAME hello_remote_tensor+ SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/main.cpp"+ INCLUDE_DIRECTORIES ${LEVEL_ZERO_INCLUDE_DIR}+ DEPENDENCIES format_reader ie_samples_utils ${LEVEL_ZERO_HEADER_TARGET} ${LEVEL_ZERO_LOADER_LIBRARY}+ OpenCL::OpenCL ${CMAKE_DL_LIBS})diff --git a/samples/cpp/hello_remote_tensor/README.md b/samples/cpp/hello_remote_tensor/README.mdnew file mode 100644index 00000000000..99f69e35382--- /dev/null+++ b/samples/cpp/hello_remote_tensor/README.md@@ -0,0 +1,120 @@+# Hello Remote Tensor C++ Sample++This sample demonstrates how to integrate OpenVINO into an existing Level Zero application.+It runs image classification on an Intel GPU with input and output tensors allocated in+Level Zero device memory, and all GPU memory operations of the application use the+Level Zero API. OpenVINO does not provide a dedicated Level Zero remote context; the sample+relies on Level Zero - OpenCL interoperability (LEO) of the GPU driver: it takes the GPU+plugin's default OpenCL context and converts it to the underlying Level Zero context with a+single `clGetContextInfo(..., CL_L0_CONTEXT_HANDLE, ...)` query. USM device pointers of the+remote tensors are valid in both APIs, so no further conversion is needed. The sample works+with any GPU plugin runtime (`GPU_RT_TYPE=OCL`, `ZE` or `COMBINED`).+It follows the structure of the+[Hello Classification C++ sample](../hello_classification/README.md), but the input+and output of the infer request are remote tensors allocated in GPU device memory.+Data are moved between the host and the device with a Level Zero command list.++Models with only one input and one output are supported.++For more detailed information on how this sample works, check the dedicated [article](https://docs.openvino.ai/2026/get-started/learn-openvino/openvino-samples/hello-remote-tensor.html)++## Requirements++| Options | Values |+| ----------------------------| -------------------------------------------------------------------------------------------------|+| Model Format | OpenVINO™ toolkit Intermediate Representation (\*.xml + \*.bin), ONNX (\*.onnx) |+| Supported devices | GPU (`GPU`, `GPU.0`, ...) |++- An Intel GPU with a driver that provides Level Zero - OpenCL interoperability (LEO), that+ is, a driver where an OpenCL context can be queried for its Level Zero context with+ `clGetContextInfo(..., CL_L0_CONTEXT_HANDLE, ...)`. If the query fails, the sample+ reports an error.+- OpenVINO with the GPU plugin, built with any runtime. The default remote context is an+ OpenCL context (`ov::intel_gpu::ContextType::OCL`), which the sample converts through LEO.+ With the OpenCL runtime (`GPU_RT_TYPE=OCL`) LEO is a hard requirement: without it the+ sample always fails, because the plugin has no Level Zero context to offer.+ Only in the edge case of the Level Zero plugin (`GPU_RT_TYPE=ZE` or `COMBINED`) running on+ a driver without LEO, the default context is already a Level Zero context+ (`ov::intel_gpu::ContextType::ZE`) and its handle is used directly.+- OpenCL headers and the OpenCL ICD loader library to build the sample, which links the loader for the+ single `clGetContextInfo` call (see above). The loader is also required at run time, even when the+ plugin provides a Level Zero context directly. On Ubuntu, install the development files with+ `sudo apt install ocl-icd-opencl-dev`; the runtime loader is provided by `ocl-icd-libopencl1`,+ and the Intel GPU OpenCL driver by `intel-opencl-icd`.+- Level Zero headers and the Level Zero loader library (`ze_loader`) to build the sample, which links+ the loader. On Ubuntu, install the development files with `sudo apt install libze-dev`. At run time+ the loader is provided by the GPU driver (or the `libze1` package on Ubuntu).++The following C++ API is used in the application:++| Feature | API | Description |+| --------------------------| ---------------------------------------------------------------|---------------------------------------------------------------------|+| Remote Context | ``ov::Core::get_default_context``, | Get the plugin's context and its native handle |+| | ``ov::RemoteContext::get_params`` | |+| Remote Tensor | ``ov::RemoteContext::create_tensor``, | Allocate USM device memory and get its Level Zero pointer |+| | ``ov::RemoteTensor::get_params`` | |+| Basic Infer Flow | ``ov::Core::read_model``, | Read a model, compile it in the remote context, create an infer |+| | ``ov::Core::compile_model``, | request, and bind remote input and output tensors |+| | ``ov::CompiledModel::create_infer_request``, | |+| | ``ov::InferRequest::set_input_tensor``, | |+| | ``ov::InferRequest::set_output_tensor`` | |+| Synchronous Infer | ``ov::InferRequest::infer`` | Do synchronous inference |+| Preprocessing | ``ov::preprocess::PrePostProcessor`` | Resize and layout conversion of the original image on the device |+| Level Zero | ``zeInitDrivers``, ``zeMemGetAllocProperties``, | Initialize Level Zero, find the allocation's device, and copy data |+| | ``zeCommandListCreateImmediate``, | between host memory and device memory |+| | ``zeCommandListAppendMemoryCopy``, | |+| | ``zeCommandListHostSynchronize`` | |+| OpenCL (LEO) | ``clGetContextInfo`` with ``CL_L0_CONTEXT_HANDLE`` | Convert the plugin's OpenCL context to its Level Zero context |++## Build and run++Build the C++ samples using the usual OpenVINO sample build procedure. The target+is `hello_remote_tensor`. For a standalone samples build, select it with+`BUILD_SAMPLE_NAME=hello_remote_tensor`. If Level Zero or OpenCL development files are+unavailable, CMake skips this target with a status message, unless the sample was selected+explicitly with `BUILD_SAMPLE_NAME`, in which case the configuration fails with an error.+For nonstandard system installations, set `LEVEL_ZERO_INCLUDE_DIR` to the directory containing+`level_zero/ze_api.h` and `LEVEL_ZERO_LOADER_LIBRARY` to the `ze_loader` library.++After setting up the OpenVINO runtime environment, run:++```sh+./hello_remote_tensor <path_to_model> <path_to_image> <device_name>+./hello_remote_tensor squeezenet1.1.xml dog-224x224.bmp GPU+```++The device must be a GPU selected directly, for example `GPU`, `GPU.0` or a tile such+as `GPU.0.0`. CPU, AUTO, MULTI and HETERO are not supported. The sample prints the+top 10 classification results and returns a nonzero exit code on failure.++## What the sample demonstrates++1. Create `ov::Core` and obtain the plugin's default remote context.+2. Initialize Level Zero with `zeInitDrivers` and convert the context to a Level Zero context. The+ default context is an `OCL` context whose `cl_context` is exposed under the+ `ov::intel_gpu::ocl_context` property; the sample converts it with the LEO query+ `clGetContextInfo(..., CL_L0_CONTEXT_HANDLE, ...)`. In the edge case of a `ZE` context+ (Level Zero plugin on a driver without LEO), the same property already holds the native+ `ze_context_handle_t`.+3. Read the model and the image, and configure preprocessing as in Hello Classification.+4. Compile the model using default OpenVINO context.+5. Allocate input and output remote tensors using `USM_DEVICE_BUFFER` and obtain+ their USM pointers through `ov::intel_gpu::mem_handle`.+6. Query the input allocation's device with `zeMemGetAllocProperties` so the+ application's command list uses the same device as OpenVINO.+7. Copy the image from host memory to the input tensor through a Level Zero immediate+ command list, run synchronous inference, and copy the output tensor back to a host+ `ov::Tensor` through Level Zero. Each copy waits with `zeCommandListHostSynchronize`+ before the data are used.++## Smoke tests++The sample tests check invalid arguments without requiring a GPU. Set+`IE_APP_PATH` to the directory containing the executable. The classification tests run+on the GPU devices listed in `TEST_DEVICE` (the default device list contains no GPU, so+they are skipped); run them on a machine with an Intel GPU and a LEO-capable driver:++```sh+cd tests/samples_tests/smoke_tests+TEST_DEVICE="GPU;GPU.0" python -m pytest test_hello_remote_tensor.py+```diff --git a/samples/cpp/hello_remote_tensor/main.cpp b/samples/cpp/hello_remote_tensor/main.cppnew file mode 100644index 00000000000..89381d6a941--- /dev/null+++ b/samples/cpp/hello_remote_tensor/main.cpp@@ -0,0 +1,275 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <cstdint>+#include <functional>+#include <iostream>+#include <limits>+#include <memory>+#include <sstream>+#include <string>+#include <string_view>+#include <type_traits>+#include <vector>++// clang-format off+#ifndef CL_TARGET_OPENCL_VERSION+# define CL_TARGET_OPENCL_VERSION 300+#endif+#include <CL/cl.h>+#include <level_zero/ze_api.h>++#include "openvino/openvino.hpp"+#include "openvino/runtime/intel_gpu/remote_properties.hpp"++#include "samples/args_helper.hpp"+#include "samples/common.hpp"+#include "samples/classification_results.h"+#include "samples/slog.hpp"+#include "format_reader_ptr.h"+// clang-format on++#define ZE_CHECK(fn_call) check_ze_call((fn_call), #fn_call)++namespace {++void check_ze_call(ze_result_t result, std::string_view fn_call) {+ if (result != ZE_RESULT_SUCCESS) {+ std::string_view fn_name = fn_call.substr(0, fn_call.find('('));+ OPENVINO_THROW("Level Zero function failed, ", fn_name, " returned ", result);+ }+}++// Only the OpenVINO Level Zero backend initializes the driver itself; this sample also uses Level Zero directly.+void initialize_level_zero() {+ ze_init_driver_type_desc_t desc = {};+ desc.stype = ZE_STRUCTURE_TYPE_INIT_DRIVER_TYPE_DESC;+ desc.flags = ZE_INIT_DRIVER_TYPE_FLAG_GPU;+ uint32_t driver_count = 0;+ ZE_CHECK(zeInitDrivers(&driver_count, nullptr, &desc));+ OPENVINO_ASSERT(driver_count > 0, "No Level Zero GPU driver found");+}++struct CommandListDeleter {+ void operator()(ze_command_list_handle_t command_list) const {+ const auto result = zeCommandListDestroy(command_list);+ if (result != ZE_RESULT_SUCCESS) {+ std::cerr << "zeCommandListDestroy failed with Level Zero error " << result << std::endl;+ }+ }+};++using CommandList = std::unique_ptr<std::remove_pointer_t<ze_command_list_handle_t>, CommandListDeleter>;++CommandList create_command_list(ze_context_handle_t context, ze_device_handle_t device) {+ uint32_t count = 0;+ ZE_CHECK(zeDeviceGetCommandQueueGroupProperties(device, &count, nullptr));+ std::vector<ze_command_queue_group_properties_t> groups(count);+ for (auto& group : groups) {+ group.stype = ZE_STRUCTURE_TYPE_COMMAND_QUEUE_GROUP_PROPERTIES;+ }+ ZE_CHECK(zeDeviceGetCommandQueueGroupProperties(device, &count, groups.data()));++ for (uint32_t ordinal = 0; ordinal < count; ++ordinal) {+ if (groups[ordinal].numQueues > 0 && (groups[ordinal].flags & ZE_COMMAND_QUEUE_GROUP_PROPERTY_FLAG_COPY)) {+ ze_command_queue_desc_t desc = {};+ desc.stype = ZE_STRUCTURE_TYPE_COMMAND_QUEUE_DESC;+ desc.ordinal = ordinal;+ desc.mode = ZE_COMMAND_QUEUE_MODE_SYNCHRONOUS;+ ze_command_list_handle_t handle = nullptr;+ ZE_CHECK(zeCommandListCreateImmediate(context, device, &desc, &handle));+ return CommandList(handle);+ }+ }+ OPENVINO_THROW("The GPU has no command queue group supporting memory copies");+}++void copy_memory(ze_command_list_handle_t command_list, void* destination, const void* source, size_t bytes) {+ ZE_CHECK(zeCommandListAppendMemoryCopy(command_list, destination, source, bytes, nullptr, 0, nullptr));+ // Wait explicitly so the data is complete before OpenVINO or the host uses it.+ ZE_CHECK(zeCommandListHostSynchronize(command_list, std::numeric_limits<uint64_t>::max()));+}++void* get_usm_pointer(const ov::RemoteTensor& tensor) {+ const auto params = tensor.get_params();+ const auto it = params.find(ov::intel_gpu::mem_handle.name());+ OPENVINO_ASSERT(it != params.end(), "The GPU plugin did not report the USM pointer of the remote tensor");+ void* pointer = it->second.as<void*>();+ OPENVINO_ASSERT(pointer != nullptr, "The GPU plugin returned a null USM pointer");+ return pointer;+}++// Intel Compute Runtime LEO driver extension; 0x42B0 is CL_CONTEXT_L0_HANDLE_INTEL:+// https://github.com/intel/compute-runtime/blob/710ede9ddfec3779cbd847b916a37d72e988ad9c/level_zero/api/opencl/extensions/public/cl_ext_private.h#L164+constexpr cl_context_info cl_l0_context_handle = 0x42B0;++ze_context_handle_t get_level_zero_context(const ov::AnyMap& context_params) {+ const auto type_it = context_params.find(ov::intel_gpu::context_type.name());+ OPENVINO_ASSERT(type_it != context_params.end(), "The GPU plugin did not report the context type");+ const auto type = type_it->second.as<ov::intel_gpu::ContextType>();+ // The current GPU API uses the OCL_CONTEXT key also for the native handle of a ZE context.+ const auto handle_it = context_params.find(ov::intel_gpu::ocl_context.name());+ OPENVINO_ASSERT(handle_it != context_params.end(), "The GPU plugin did not report the context handle");+ void* handle = handle_it->second.as<void*>();+ OPENVINO_ASSERT(handle != nullptr, "The GPU plugin returned a null context handle");++ if (type == ov::intel_gpu::ContextType::ZE) {+ return static_cast<ze_context_handle_t>(handle);+ }+ OPENVINO_ASSERT(type == ov::intel_gpu::ContextType::OCL, "Unsupported GPU context type: ", type);++ // Without a dedicated Level Zero remote context in OpenVINO, the plugin's default context is an OpenCL+ // context. Level Zero - OpenCL interoperability (LEO) of the driver converts it to the underlying Level Zero+ // context. This is the only OpenCL call in the sample.+ // The returned ze_context is borrowed from the OpenCL context: it must not outlive it or be destroyed.+ ze_context_handle_t ze_context = nullptr;+ const cl_int result = clGetContextInfo(static_cast<cl_context>(handle),+ cl_l0_context_handle,+ sizeof(ze_context),+ &ze_context,+ nullptr);+ OPENVINO_ASSERT(result == CL_SUCCESS && ze_context != nullptr,+ "Cannot convert the GPU plugin's OpenCL context to a Level Zero context (OpenCL error ",+ result,+ "). The GPU driver does not support Level Zero - OpenCL interoperability (LEO).");+ return ze_context;+}++} // namespace++/**+ * @brief Main with support Unicode paths, wide strings.+ * Unicode paths work on non-Windows systems only: on Windows the samples' wstring2string() helper truncates wide+ * characters, so paths must be ASCII.+ */+int tmain(int argc, tchar* argv[]) {+ try {+ // -------- Set OpenVINO log message capturing callback --------+ const std::function<void(std::string_view)> log_callback{[](std::string_view msg) {+ slog::info << msg;+ }};+ ov::util::set_log_callback(log_callback);++ // -------- Get OpenVINO runtime version --------+ slog::info << ov::get_openvino_version() << slog::endl;++ // -------- Parsing and validation of input arguments --------+ if (argc != 4) {+ slog::info << "Usage : " << TSTRING2STRING(argv[0]) << " <path_to_model> <path_to_image> <device_name>"+ << slog::endl;+ return EXIT_FAILURE;+ }++ const std::string model_path = TSTRING2STRING(argv[1]);+ const std::string image_path = TSTRING2STRING(argv[2]);+ const std::string device_name = TSTRING2STRING(argv[3]);++ // -------- Step 1. Initialize OpenVINO Runtime Core and get the default context of the GPU plugin --------+ // This is done before loading Level Zero, so a missing GPU plugin is reported by the usual OpenVINO+ // exception instead of a Level Zero loader error.+ ov::Core core;+ auto context = core.get_default_context(device_name);++ // -------- Step 2. Initialize Level Zero and get the Level Zero context of the GPU plugin --------+ // The default context is an OpenCL context converted through LEO; a ZE context is the edge case of the+ // Level Zero plugin on a driver without LEO.+ initialize_level_zero();+ const auto ze_context = get_level_zero_context(context.get_params());++ // -------- Step 3. Read a model --------+ slog::info << "Loading model files: " << model_path << slog::endl;+ std::shared_ptr<ov::Model> model = core.read_model(model_path);+ printInputAndOutputsInfo(*model);++ OPENVINO_ASSERT(model->inputs().size() == 1, "Sample supports models with 1 input only");+ OPENVINO_ASSERT(model->outputs().size() == 1, "Sample supports models with 1 output only");++ // -------- Step 4. Read input image --------+ FormatReader::ReaderPtr reader(image_path.c_str());+ if (reader.get() == nullptr) {+ std::stringstream ss;+ ss << "Image " + image_path + " cannot be read!";+ throw std::logic_error(ss.str());+ }++ ov::element::Type input_type = ov::element::u8;+ ov::Shape input_shape = {1, reader->height(), reader->width(), 3};+ std::shared_ptr<unsigned char> input_data = reader->getData();+ OPENVINO_ASSERT(input_data != nullptr && reader->size() == ov::shape_size(input_shape),+ "Image must have 3 channels of 8 bit data: expected ",+ ov::shape_size(input_shape),+ " bytes, got ",+ reader->size());++ const ov::Layout tensor_layout{"NHWC"};++ // -------- Step 5. Configure preprocessing --------+ ov::preprocess::PrePostProcessor ppp(model);++ // 1) Set input tensor information: shape and precision of the image, layout 'NHWC'+ ppp.input().tensor().set_shape(input_shape).set_element_type(input_type).set_layout(tensor_layout);+ // 2) Apply linear resize from tensor spatial dims to model spatial dims+ ppp.input().preprocess().resize(ov::preprocess::ResizeAlgorithm::RESIZE_LINEAR);+ // 3) Suppose model has 'NCHW' layout for input+ ppp.input().model().set_layout("NCHW");+ // 4) Set output tensor precision to 'f32'+ ppp.output().tensor().set_element_type(ov::element::f32);++ // 5) Apply preprocessing modifying the original 'model'+ model = ppp.build();++ // -------- Step 6. Compile the model using the GPU plugin's default context --------+ ov::CompiledModel compiled_model = core.compile_model(model, context);+ OPENVINO_ASSERT(compiled_model.output().get_partial_shape().is_static(),+ "Sample supports models with static output shape only");++ // -------- Step 7. Create an infer request --------+ ov::InferRequest infer_request = compiled_model.create_infer_request();++ // -------- Step 8. Prepare Level Zero remote tensors --------+ // OpenVINO owns the device allocations; the tensors must outlive all Level Zero accesses to them.+ const ov::AnyMap device_memory{ov::intel_gpu::shared_mem_type(ov::intel_gpu::SharedMemType::USM_DEVICE_BUFFER)};+ auto remote_input = context.create_tensor(input_type, input_shape, device_memory);+ auto remote_output =+ context.create_tensor(ov::element::f32, compiled_model.output().get_shape(), device_memory);+ void* input_pointer = get_usm_pointer(remote_input);+ void* output_pointer = get_usm_pointer(remote_output);++ // Query the allocation's device rather than assuming that GPU.0 is the first Level Zero device.+ ze_memory_allocation_properties_t allocation = {};+ allocation.stype = ZE_STRUCTURE_TYPE_MEMORY_ALLOCATION_PROPERTIES;+ ze_device_handle_t ze_device = nullptr;+ ZE_CHECK(zeMemGetAllocProperties(ze_context, input_pointer, &allocation, &ze_device));+ OPENVINO_ASSERT(allocation.type == ZE_MEMORY_TYPE_DEVICE && ze_device != nullptr,+ "Expected a Level Zero device allocation");++ // Upload the image from host memory to device memory through a Level Zero command list+ auto command_list = create_command_list(ze_context, ze_device);+ copy_memory(command_list.get(), input_pointer, input_data.get(), remote_input.get_byte_size());++ infer_request.set_input_tensor(remote_input);+ infer_request.set_output_tensor(remote_output);++ // -------- Step 9. Do inference synchronously --------+ infer_request.infer();++ // -------- Step 10. Download and process output --------+ ov::Tensor output_tensor(ov::element::f32, remote_output.get_shape());+ copy_memory(command_list.get(), output_tensor.data(), output_pointer, remote_output.get_byte_size());++ // Print classification results+ const auto& output_shape = output_tensor.get_shape();+ OPENVINO_ASSERT(output_shape.size() >= 2 && output_shape[0] == 1 && output_tensor.get_size() > 0,+ "Sample requires a nonempty classification output with rank >= 2 and batch dimension 1");+ const size_t num_of_top = output_tensor.get_size() < 10 ? output_tensor.get_size() : 10;+ ClassificationResult classification_result(output_tensor, {image_path}, 1, num_of_top);+ classification_result.show();+ // -----------------------------------------------------------------------------------------------------+ } catch (const std::exception& ex) {+ std::cerr << ex.what() << std::endl;+ return EXIT_FAILURE;+ }++ return EXIT_SUCCESS;+}diff --git a/src/plugins/intel_gpu/docs/gpu_plugin_with_level_zero.md b/src/plugins/intel_gpu/docs/gpu_plugin_with_level_zero.mdindex a8591adce34..2f842baff76 100644--- a/src/plugins/intel_gpu/docs/gpu_plugin_with_level_zero.md+++ b/src/plugins/intel_gpu/docs/gpu_plugin_with_level_zero.md@@ -1,9 +1,10 @@# GPU plugin Level Zero supportOpenVINO GPU plugin can be compiled with **experimental** Level Zero support. When enabled, plugin will use Level Zero as GPU compute API instead of OpenCL.-Level Zero is the better-performing runtime on Xe2 and newer Intel GPU architectures; on pre-Xe2 GPUs, it is not supported.+For an example of integrating OpenVINO into a Level Zero application, see the [Hello Remote Tensor C++ sample](../../../../samples/cpp/hello_remote_tensor/README.md).+## How to build with Level Zero support1. Configure cmake with the following additional option:diff --git a/tests/samples_tests/smoke_tests/test_hello_remote_tensor.py b/tests/samples_tests/smoke_tests/test_hello_remote_tensor.pynew file mode 100644index 00000000000..c1320168a64--- /dev/null+++ b/tests/samples_tests/smoke_tests/test_hello_remote_tensor.py@@ -0,0 +1,97 @@+# Copyright (C) 2018-2026 Intel Corporation+# SPDX-License-Identifier: Apache-2.0++import os+import pathlib+import re+import shutil+import subprocess+import sys++import pytest++from common.samples_common_test_class import download, get_cmd_output, get_devices++MODEL = 'samples_smoke_tests_data_2021.4/models/public/squeezenet1.1/FP16/squeezenet1.1.xml'+IMAGE = 'dog-224x224.bmp'++# The sample runs on directly selected GPU devices only; take them from TEST_DEVICE like the other sample tests.+GPU_DEVICES = [device for device in get_devices() if device.startswith('GPU')]+++def get_executable():+ return pathlib.Path(os.environ['IE_APP_PATH'], 'hello_remote_tensor').with_suffix('.exe' if os.name == 'nt' else '')+++def executable():+ # The sample needs a GPU with the Level Zero driver at run time, so only a job with such a machine opts in.+ if os.environ.get('OV_REQUIRE_REMOTE_TENSOR_SAMPLE') != '1':+ pytest.skip('Set OV_REQUIRE_REMOTE_TENSOR_SAMPLE=1 to run the Level Zero remote tensor sample tests')+ path = get_executable()+ if not path.is_file():+ pytest.fail(f'The optional Level Zero remote tensor sample was not built: {path}')+ return path+++def test_hello_remote_tensor_missing_arguments(executable):+ result = subprocess.run([executable, 'model.xml', 'image.bmp'], capture_output=True, text=True, timeout=60)+ assert result.returncode != 0+ assert 'Usage' in result.stdout + result.stderr, result.stdout + result.stderr+++def test_hello_remote_tensor_non_gpu_device(executable):+ # OpenVINO itself rejects devices without a default remote context.+ result = subprocess.run([executable, 'model.xml', 'image.bmp', 'CPU'], capture_output=True, text=True, timeout=60)+ assert result.returncode != 0+ assert (result.stdout + result.stderr).strip()+++def get_top1(output):+ for line in output.split('\n'):+ line = line.replace('[ INFO ]', '').strip()+ if re.match(r'\d+ +\d+.\d+$', line):+ return line.split(' ')[0]+ return None++[email protected](not GPU_DEVICES, reason='No GPU device in TEST_DEVICE')[email protected]('device', GPU_DEVICES)+def test_hello_remote_tensor_classification(executable, device, cache):+ test_data_dir = cache.mkdir('test_data')+ model = download(test_data_dir, test_data_dir / MODEL)+ image = download(test_data_dir, test_data_dir / IMAGE)++ output = get_cmd_output(executable, model, image, device)++ top1 = get_top1(output)+ assert top1 == '215', f'Expected top1 class 215, got {top1}\n{output}'+++# Russian, Hebrew, Czech, Chinese, Korean, Japanese and all of them combined.+UNICODE_NAMES = ['русский', 'עברית', 'česky', '中国人', '한국인', '日本人',+ 'русский_עברית_česky_中国人_한국인_日本人']++[email protected](not GPU_DEVICES, reason='No GPU device in TEST_DEVICE')[email protected](sys.platform.startswith('win'),+ reason='The samples\' wstring2string helper truncates wide characters, '+ 'so Unicode paths do not work on Windows (see test_hello_classification)')[email protected]('name', UNICODE_NAMES)+def test_hello_remote_tensor_unicode_paths(executable, cache, tmp_path, name):+ test_data_dir = cache.mkdir('test_data')+ model = download(test_data_dir, test_data_dir / MODEL)+ image = download(test_data_dir, test_data_dir / IMAGE)++ unicode_dir = tmp_path / name+ unicode_dir.mkdir()+ unicode_model = unicode_dir / (name + pathlib.Path(model).suffix)+ unicode_image = unicode_dir / (name + pathlib.Path(image).suffix)+ shutil.copy(model, unicode_model)+ shutil.copy(pathlib.Path(model).with_suffix('.bin'), unicode_model.with_suffix('.bin'))+ shutil.copy(image, unicode_image)++ output = get_cmd_output(executable, unicode_model, unicode_image, GPU_DEVICES[0])++ top1 = get_top1(output)+ assert top1 == '215', f'Expected top1 class 215, got {top1}\n{output}'