OpenVINO C# API

repository·csharp3.3·Indexed 42 days ago

https://github.com/guojin-yan/openvino-csharp-api

A .NET wrapper for Intel OpenVINO that enables high-performance deep learning inference for models like YOLO, ResNet, BERT, and LLMs across Windows, Linux, and macOS. It features zero-copy memory operations via Span<T>, async/await support, and multi-device targeting (CPU, iGPU, GPU, NPU). Includes the OpenVinoSharp.GenAI wrapper for Generative AI tasks such as LLM text generation, Whisper speech recognition, and Visual Language Models (VLM).

Tokens
32.4K
Snippets
85
Records
135
Agent score
51%

What's inside OpenVINO C# API

  1. Overview of OpenVINO C# API

    csharp3.3

    OpenVINO C# API provides managed .NET wrappers for two primary C-based interfaces:

    1. OpenVINO C API: Used for standard inference tasks.
    2. OpenVINO GenAI C API: An optional set of APIs specifically for Generative AI workloads.

    Depending on your use case, you will interact with different runtime packages.

  2. Overview of OpenVINO GenAI C# Samples

    csharp3.3

    The samples/GenAI directory contains C# projects that replicate OpenVINO GenAI C API scenarios. These samples provide practical implementations for various generative AI tasks using managed wrappers.

    Supported Scenarios:

    • Text Generation: Includes Greedy (deterministic), Beam Search, Multinomial (sampling with top-k/top-p/temperature), Streaming (callback-based), Chat (multi-turn), and Benchmarking (performance metrics).
    • Speech Recognition: Whisper-based automatic speech recognition.
    • Visual Language (VLM): Image + text chat using Vision-Language Models.

    Note: Image generation, RAG, speech generation, and video generation are currently not included as C# samples because their managed pipeline wrappers are incomplete.

  3. Overview of OpenVINO C# API features

    csharp3.3

    The OpenVINO C# API is a .NET wrapper for Intel OpenVINO, enabling high-performance deep learning inference on Windows, Linux, and macOS.

    Key Capabilities:

    • High Performance: Uses Span<T> and Memory<T> for zero-copy memory operations (requires .NET Core 2.1+ or .NET 4.7.2+).
    • Cross-Platform: Supports Windows, Linux, and macOS on x64 and ARM64 architectures.
    • Asynchronous Inference: Full async/await support for high-concurrency scenarios (requires .NET Core 3.0+).
    • Multi-Device Support: Targets Intel CPU, iGPU, GPU, NPU, and partial support for AMD CPUs.
    • Generative AI: Optional OpenVinoSharp.GenAI wrapper for LLM, Whisper, and VLM models.
    • Optimizations: Includes automatic model caching and inference request object pooling.
  4. Explore OpenVINO C# API sample applications

    csharp3.3

    The OpenVINO C# API provides two main tracks of sample applications:

    1. Traditional Vision Inference: YOLO-based detection examples demonstrating how to implement inference across different .NET versions (from .NET Framework 4.6 to modern .NET 10.0).
    2. OpenVINO GenAI: Examples for Generative AI capabilities including Large Language Models (LLM), Speech Recognition (Whisper), and Vision-Language Models (VLM).

    GenAI Capabilities

    GenAI features are located in the OpenVinoSharp.GenAI namespace and include:

    • LLMPipeline: Text generation (Greedy, Beam Search, Sampling, Streaming).
    • WhisperPipeline: Automatic Speech Recognition (ASR) with timestamp support.
    • VLMPipeline: Visual Language Models for image understanding and interactive Q&A.

    Note: The GenAI runtime is an optional dependency. If you only use traditional APIs like Core, Model, Tensor, CompiledModel, or InferRequest, the openvino_genai_c library will not be loaded.

  5. Explore OpenVINO C# API documentation categories

    csharp3.3

    The OpenVINO C# API documentation is organized into several key areas to help you install, use, and troubleshoot the library:

    • Installation: Instructions for NuGet runtime installation and native runtime requirements on Windows, Linux, and macOS.
    • Sample Applications: Examples ranging from traditional YOLO inference to modern GenAI tasks like text generation, Whisper (speech), and Vision-Language Models (VLM).
    • Upgrade Guides: Specific instructions for migrating between versions (e.g., from 3.2 to 3.3).
    • Troubleshooting: Solutions for common issues such as native library loading, model path errors, and platform-specific differences.
  6. License and Legal Disclaimers

    csharp3.3

    Open Source License

    All open-source code in this project follows the Apache License 2.0.

    Note on Third-Party Libraries: This project integrates several third-party libraries. If any third-party library's license conflicts with Apache 2.0, the original license of that third-party library takes precedence. Users are responsible for reading and complying with the licenses of all third-party components used.

    Usage Risks and Disclaimer

    • AI-Assisted Development: Code was generated and optimized using AI assistance.
    • Technical Limitations: Due to technical constraints, the code may contain issues such as memory leaks, occasional crashes, or unreleased resources. It has not undergone exhaustive testing for all edge cases.
    • Mandatory Testing: Users must perform thorough and rigorous testing and verification before applying this code to any real-world projects (especially commercial, industrial, or mission-critical environments).
    • Liability: The author is not responsible for any direct or indirect losses (including device failure, data loss, system paralysis, or loss of profit) resulting from the use of this code. By using this code, you acknowledge these risks and agree to assume all consequences.
  7. Native Runtime Compatibility and Resolution

    csharp3.3

    The native runtime package handles binary resolution differently depending on your target framework:

    • .NET 5+: Binaries are automatically resolved at build time using the standard runtimes/{RID}/native/ layout.
    • .NET Framework 4.x: The package uses a .props file (build/net46/{NUGET_ID}.props) to explicitly copy the native libraries to your output directory.
    • SDK-style projects: Includes build/netstandard2.0 and empty lib placeholders to ensure compatibility and prevent legacy .NET Framework fallback warnings during restoration.
  8. Implementation details for GenAI Chat and VLM

    csharp3.3

    Chat Implementation

    • The TextGeneration/Chat sample supports the --turn argument, allowing you to pass multiple scripted turns for testing multi-turn conversations.
    • C# strings are passed to the native GenAI layer via UTF-8, ensuring support for Chinese and English prompts.

    Whisper Implementation

    • WhisperSpeechRecognition accepts standard language codes (e.g., --language en). The sample converts these to the required native format (e.g., <|en|>) before calling the native C API.

    Visual Language Model (VLM) Implementation

    • VisualLanguageChat uses ChatHistory combined with GenerateWithHistory() to implement interactive flows. This approach is compatible with the VLM history export features in OpenVINO GenAI 2026.3.
    • The VLM sample supports Chinese prompts and can return Chinese image descriptions.
    • Note: The VLM sample treats empty outputs as failures by default. Use --allow-empty true only for ABI smoke testing.
  9. Binary resolution for .NET Framework and .NET 5+

    csharp3.3

    The runtime binaries are handled differently depending on your target framework:

    • .NET 5+: Binaries are automatically resolved by the .NET runtime.
    • .NET Framework 4.x: The package includes a build property file (build/net/{NUGET_ID}.props) that automatically copies the required runtime files to your output directory during the build process.
  10. Understand OpenVINO GenAI C# API Coverage

    csharp3.3

    The OpenVINO C# API provides managed wrappers for the OpenVINO GenAI C API. The coverage includes several key pipelines and configuration objects. When using these wrappers, note the following ownership and data handling rules:

    Supported Pipelines and Configs

    • LLM: LLMPipeline, GenerationConfig, DecodedResults.
    • Whisper (Speech-to-Text): WhisperPipeline, WhisperGenerationConfig, WhisperDecodedResults, WhisperDecodedResultChunk.
    • VLM (Vision-Language Models): VLMPipeline, VLMDecodedResults.
    • Utilities: ChatHistory, JsonContainer, PerformanceMetrics.

    Data Handling and Memory Management

    • Ownership: Most pipeline and result objects (like LLMPipeline or DecodedResults) own their native pointers and must be managed via the IDisposable pattern. Metrics returned by result objects are owned by the managed wrappers and released using the corresponding native free function.
    • Strings: UTF-8 strings are explicitly allocated and freed. JsonContainer uses a two-call UTF-8 buffer pattern.
    • Whisper: Raw audio buffers are pinned during the generate call. Optional native strings that are NOT_FOUND map to null in C#.
    • VLM: Image tensors are borrowed from the caller; the caller retains ownership of the tensor data, while the pointer array is pinned during the native call.
  11. Avoid architecture mismatches on Apple Silicon

    csharp3.3

    On Apple Silicon, you must ensure that the .NET SDK architecture matches the native runtime architecture.

    Critical Rules:

    • Use the ARM64 runtime with an ARM64 .NET SDK.
    • Do not load an x64 native runtime in an ARM64 process.
    • Do not load an ARM64 runtime in a Rosetta x64 process.

    Architecture mismatches will cause native library loading failures.

    To verify your current architecture, use:

    dotnet --info
    uname -m
    dotnet --info
    uname -m
  12. How VLMPipeline works for visual-textual tasks

    csharp3.3

    The VLMPipeline is the primary abstraction for multi-modal inference in OpenVinoSharp.GenAI. It orchestrates the interaction between visual inputs and text prompts.

    Key Components

    • VLMPipeline: The main engine that manages the model and device context. It requires a model directory containing OpenVINO IR, tokenizer, detokenizer, and configuration files.
    • ImageTensorLoader: A utility to convert raw image data into the Tensor format required by the pipeline. Note that the current implementation specifically supports RGB BMP and binary PPM/PNM formats. For JPG or PNG, you must convert them to RGB BMP first.
    • GenerationConfig: Controls the text generation process (e.g., maximum tokens, streaming, and stopping conditions).
    • VLMDecodedResults: The output object containing the generated text and performance metrics (like token generation speed).

    Lifecycle Note

    The imageTensor must remain in scope and must not be disposed of while pipeline.Generate is executing, as the pipeline borrows the tensor during the inference call.