oneAPI Level Zero

repository·master·Indexed 43 days ago

https://github.com/oneapi-src/level-zero

A low-level hardware abstraction layer for high-performance access to accelerators such as GPUs and NPUs. It provides an API specification, loader, validation layer, and tracing layer. Includes pyzes, Python bindings for the Intel Level-Zero Driver Library (Sysman API) version 0.1.2.

Tokens
14.8K
Snippets
33
Records
60
Agent score
56%

What's inside oneAPI Level Zero

  1. Overview of XLA GraphCycles source location

    master

    The graphcycles component within this repository is a modified version of the OpenXLA XLA project. The original source can be found at the following location:

    https://github.com/openxla/xla/tree/18d21413942e140f923da9eefe7a5b7c7206157f/xla/service/graphcycles

    Important Compatibility Notes: This implementation includes specific modifications to ensure compatibility and reduce external dependencies:

    • Dependency Removal: The external abseil library has been completely removed and replaced with equivalent std:: containers.
    • C++ Standard: Certain C++17 features have been substituted with equivalent code to maintain compatibility with C++14.
  2. Analyze memory leaks and resource usage with System Resource Tracker

    master

    The System Resource Tracker is a validation layer checker designed to detect memory leaks and monitor resource lifecycle in oneAPI Level Zero applications. It provides both real-time validation warnings and post-execution analysis via CSV data that can be visualized.

    Key Capabilities

    • Memory Leak Detection: Identifies resources (contexts, queues, modules, kernels, etc.) that are not properly destroyed by matching create/destroy API pairs. It flags destroy operations where memory increased by more than 100KB.
    • Resource Tracking: Monitors 11 resource types: contexts, queues, modules, kernels, event pools, command lists, events, fences, images, samplers, and memory allocations.
    • Performance & Optimization: Tracks system-level metrics (VmSize, VmRSS, VmData) and API call frequency to identify excessive allocations or memory usage patterns.

    Use Cases

    • Debugging: Correlate application behavior with resource usage patterns and leak events.
    • Benchmarking: Compare resource usage and leak counts across different code versions.
    • CI/CD Integration: Automated tracking of resource usage in test pipelines.
    • Capacity Planning: Understand peak resource requirements for production workloads.
  3. Understand Driver and Device sorting in Level Zero

    master

    As of v1.20.3, the Loader sorts Drivers and Devices so that the first device reported is the best available device. The sorting is based on the zel_driver_type_t enumerator.

    Default Sorting Order

    1. Drivers with Discrete GPUs only
    2. Drivers with Discrete and Integrated GPUs
    3. Drivers with Integrated GPUs
    4. Drivers with Mixed Device Types (e.g., GPU + NPU)
    5. Drivers with Non-GPU Devices Only

    Alternative Sorting Order

    If you set the environment variable ZE_ENABLE_PCI_ID_DEVICE_ORDER, the order changes to:

    1. Drivers with Integrated GPUs
    2. Drivers with Discrete and Integrated GPUs
    3. Drivers with Discrete GPUs only
    4. Drivers with Mixed Device Types (e.g., GPU + NPU)
    5. Drivers with Non-GPU Devices Only

    Note: Driver sorting is disabled in the loader when ZET_ENABLE_PROGRAM_INSTRUMENTATION is enabled due to known issues with Program Instrumentation use cases.

  4. Validate API version compatibility with the Certification Checker

    master
    Enable ZEL_ENABLE_CERTIFICATION_CHECKER to validate API usage against the version supported by the driver or an explicitly specified version. If an application uses an API introduced in a version higher than the supported version, the checker returns ZE_RESULT_ERROR_UNSUPPORTED_VERSION.
  5. Use Parameter Validation to catch invalid API inputs

    master

    Enable ZE_ENABLE_PARAMETER_VALIDATION to perform stateless checks on API calls before they reach the driver. This mode checks for:

    • Non-optional input pointers that are nullptr.
    • Non-optional input handles that are 0.
    • Invalid flag values in input flags.
    • Input enum values exceeding the maximum defined value.

    If a check fails, the layer returns an appropriate error code and prevents the driver API from being called.

  6. Detect resource leaks with the Basic Leak Checker

    master

    Enable ZEL_ENABLE_BASIC_LEAK_CHECKER to track Create and Destroy calls for specific handle types. The layer will report if a Create call is missing a corresponding Destroy call.

    ----------------------------------------------------------------------
                   zeContextCreate = 1     \--->        zeContextDestroy = 1
              zeCommandQueueCreate = 1     \--->   zeCommandQueueDestroy = 1
                    zeModuleCreate = 1     \--->         zeModuleDestroy = 1
                    zeKernelCreate = 1     \--->         zeKernelDestroy = 1
                  zeEventPoolCreate = 1     \--->      zeEventPoolDestroy = 1
       zeCommandListCreateImmediate = 1     |
                 zeCommandListCreate = 1     \--->    zeCommandListDestroy = 1  ---> LEAK = 1
                       zeEventCreate = 2     \--->          zeEventDestroy = 2
                       zeFenceCreate = 1     \--->          zeFenceDestroy = 1
                             zeImageCreate = 0     \--->          zeImageDestroy = 0
                             zeSamplerCreate = 0     \--->        zeSamplerDestroy = 0
                           zeMemAllocDevice = 0     |
                             zeMemAllocHost = 1     |
                           zeMemAllocShared = 0     \--->               zeMemFree = 1
  7. Understand the structure of L0 callback handlers

    master

    Callback handlers (both for core APIs and driver extensions) are functions implemented by the application to intercept API calls. They generally receive the following parameters:

    • params: A structure capturing pointers to the input and output parameters of the current instance (e.g., Xcb_t structures).
    • result: The current value of the return value (provided in epilogue callbacks).
    • pTracerUserData: A pointer to user-defined data associated with the tracer (provided during zelTracerCreate).
    • ppTracerInstanceUserData: A per-tracer, per-instance, per-thread storage location. This is typically used to pass data from a prologue (enter) callback to an epilogue (exit) callback for the same API call.
  8. Use Handle Lifetime Validation to track object states

    master

    Enable ZE_ENABLE_HANDLE_LIFETIME to maintain an internal mapping of handle types to state structures. This mode:

    • Adds handles to a map upon creation.
    • Removes handles from the map upon destruction.
    • Validates that handles provided as input are valid.
    • Ensures handles are properly destroyed.
    • Performs per-handle state checks (e.g., checking if a ze_cmdlist_handle_t is open or closed).
  9. How the Events Deadlock Checker works

    master

    The Events Checker is a validation layer designed to detect potential deadlocks and improper event usage in the Level Zero API.

    Key Capabilities:

    • Deadlock Detection: It identifies improper event usage patterns that could lead to deadlocks and prints warning messages to assist developers in resolution.
    • Event Reuse Validation: It detects if an event is being used more than once without being reset (e.g., attempting to signal the same event twice without a reset).

    Internal Mechanism: The checker maintains an internal Directed Acyclic Graph (DAG) where:

    • Nodes represent API calls (actions).
    • Edges represent events.

    It maintains a topological sort of these dependencies. If an API call attempts to insert an edge that would create a cycle in the graph, the checker identifies this as a potential deadlock, issues a warning, and prevents the edge from being inserted to maintain the DAG structure.

  10. How the System Resource Tracker identifies memory leaks

    master

    The tracker uses a post-analysis approach (via plotting scripts) and a real-time approach (via the validation layer) to identify leaks.

    Leak Detection Algorithm

    1. Pair Matching: The tracker matches creation and destruction API pairs (e.g., zeContextCreate ↔ zeContextDestroy).
    2. Threshold Check: It flags destroy operations where memory increased by more than 100KB.
    3. Cumulative Calculation: It calculates the total leaked memory across the entire program execution.
    4. Visual Indicators: In generated plots, leak events are highlighted with red visual indicators and scatter markers.

    Example Leak Detection Output

    === MEMORY LEAK DETECTION ===
    ⚠️  LEAKS DETECTED!
    Total leaked memory: 0.19 MB (192.00 KB)
    Number of leak events: 1
    
    Leak events by API:
      zeEventPoolDestroy: 1 events, 0.19 MB total, 0.19 MB avg

    Note: Small memory increases (< 100KB) during destroy operations may be false positives caused by internal driver caching or memory allocation granularity.

  11. Identify performance issues with the Performance Checker

    master

    Enable ZEL_ENABLE_PERFORMANCE_CHECKER to validate API usage against known performance best practices. It identifies potential issues and provides recommendations.

    Currently checked items include:

    • Whether created immediate command lists are synchronous.
    • Whether created immediate command lists are using in-order queues.
    • Whether in-order command lists are using copy offload.

    To use this mode, you must also enable logging.

    export ZEL_ENABLE_PERFORMANCE_CHECKER=1
    export ZEL_ENABLE_LOADER_LOGGING=1
    export ZE_ENABLE_VALIDATION_LAYER=1
    export ZEL_LOADER_LOG_CONSOLE=1 # Optional: enable console logging for immediate feedback