An AI model inference middleware, an AI model inference method, and an electronic device

By decoupling the design of the AI ​​model inference middleware and implementing an asynchronous pipeline architecture, the problems of high coupling and insufficient multi-task concurrency in existing AI inference modules are solved, achieving efficient and stable AI inference capabilities and improving the smoothness of application interface response and resource utilization efficiency.

CN123180340APending Publication Date: 2026-11-27SHENZHEN OCEANS KING LIGHTING ENG CO LTD +12
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611310006.8
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-08-27
Publication Date
2026-11-27

AI Technical Summary

Technical Problem

The existing AI inference module architecture has high coupling, insufficient multi-task concurrency capability, and low data transmission efficiency, resulting in difficulties in module reuse, high development costs, slow application interface response, and poor resource utilization efficiency.

Method used

By adopting an AI model inference middleware, and through the decoupling design of the upper-layer interaction module and the lower-layer adaptation module, the inference capability is encapsulated as an independent and reusable library module. Combined with the pipeline scheduling module and the channel buffer management module, it realizes an asynchronous pipeline architecture and data queue management, shields the differences of the underlying heterogeneous AI inference backend, and supports multi-task concurrency and efficient resource utilization.

Benefits of technology

It reduces architectural coupling and cross-platform adaptation costs, improves multi-task concurrent processing capabilities and system throughput, avoids main thread blocking, reduces memory fragmentation, improves development efficiency and resource utilization efficiency, and enhances system stability and scalability.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN123180340A_ABST
    Figure CN123180340A_ABST
Patent Text Reader

Abstract

The application discloses an AI model inference middleware, an AI model inference method and electronic equipment. The middleware comprises: an upper-layer interaction module configured to receive an inference task instruction and feedback inference result issued by an upper-layer application; a bottom-layer adaptation module configured to encapsulate multiple heterogeneous AI inference backends and provide a unified inference calling interface; a model management module configured to maintain AI model instances; a pipeline scheduling module configured to construct a pipeline according to the inference task instruction to execute the inference task; a processing pipeline at least comprising an input node, an inference node and an output node; and a channel buffer management module configured between adjacent processing nodes and configured to provide a data queue and an object buffer pool, wherein the data queue is configured to temporarily store data objects transmitted between adjacent processing nodes, and the object buffer pool is configured to cache idle data objects for reuse by the processing nodes. The middleware can realize cross-platform reuse of AI inference capabilities, multi-model parallel scheduling and efficient pipeline processing.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of artificial intelligence technology, and in particular to an AI model inference middleware, an AI model inference method, and an electronic device. Background Technology

[0002] Existing Artificial Intelligence (AI) inference modules typically employ an integrated design, tightly coupling inference functionality with application code. This leads to difficulties in module reuse, high development costs, and challenges in porting across different projects. Furthermore, existing solutions generally use a single-model management mechanism, loading only one model at a time, which fails to meet the needs of scenarios requiring simultaneous processing of multiple inference tasks. In terms of data processing, existing solutions often employ a synchronous blocking mode, causing the inference process to occupy the main thread for extended periods, resulting in slow application interface response and a poor user experience. In addition, existing solutions lack robust thread safety design, making them prone to data races and deadlocks in multi-threaded environments, leading to poor inference performance and resource utilization efficiency. Summary of the Invention

[0003] This invention provides an AI model inference middleware, an AI model inference method, and an electronic device to solve the technical problems of high coupling, insufficient multi-task concurrency, and low data transmission efficiency in existing AI inference module architectures.

[0004] According to another aspect of the present invention, an AI model inference middleware is provided, the middleware comprising: The upper-layer interaction module is used to receive inference task instructions issued by the upper-layer application and to feed back the inference results to the upper-layer application. The underlying adaptation module is used to encapsulate various heterogeneous AI inference backends and provide a unified inference call interface; The model management module communicates and connects with the underlying adaptation module to maintain AI model instances; The pipeline scheduling module communicates with the upper-layer interaction module and the model management module respectively. It is used to construct the corresponding processing pipeline according to the inference task instructions to execute the inference task indicated by the inference task instructions. The processing pipeline includes at least an input node, an inference node, and an output node. The channel buffer management module is configured between adjacent processing nodes to provide a data queue and an object buffer pool. The data queue is used to temporarily store data objects transferred between adjacent processing nodes, and the object buffer pool is used to cache idle data objects for reuse by processing nodes.

[0005] According to another aspect of the present invention, an AI model inference method is provided, applied to AI model inference middleware, the method comprising: Receive inference task instructions from the upper-layer application through the upper-layer interaction module; The model management module loads the corresponding target AI model instance based on the inference task instruction; The pipeline scheduling module constructs the corresponding processing pipeline according to the inference task instructions, and configures the channel buffer management module between adjacent processing nodes; the processing pipeline includes at least an input node, an inference node, and an output node; The input node receives input data from the inference task instructions and sends the input data to the inference node. The inference node performs inference calculations based on the target AI model instance and the inference call interface provided by the underlying adaptation module, and sends the obtained inference results to the output node. The inference results are fed back to the upper-layer application via the upper-layer interaction module through the output node.

[0006] According to another aspect of the present invention, an AI model inference apparatus is provided, applied to AI model inference middleware, the apparatus comprising: The instruction receiving module is used to receive inference task instructions issued by the upper-layer application through the upper-layer interaction module; The model loading module is used to load the corresponding target AI model instance based on the inference task instructions through the model management module. The pipeline construction module is used to construct the corresponding processing pipeline according to the inference task instructions through the pipeline scheduling module, and to configure the channel buffer management module between adjacent processing nodes; the processing pipeline includes at least an input node, an inference node, and an output node; The data input module is used to receive input data from the inference task instructions through the input node and send the input data to the inference node. The inference execution module is used to perform inference calculations based on the target AI model instance and the inference call interface provided by the underlying adaptation module through the inference node, and send the obtained inference results to the output node. The results feedback module is used to feed back the inference results to the upper-layer application via the upper-layer interaction module through the output node.

[0007] According to another aspect of the present invention, an electronic device is provided, the electronic device comprising: At least one processor; and A memory communicatively connected to the at least one processor; wherein, The memory stores a computer program that can be executed by the at least one processor, which enables the at least one processor to perform the AI ​​model inference method according to any embodiment of the present invention.

[0008] According to another aspect of the present invention, a computer-readable storage medium is provided, the computer-readable storage medium storing computer instructions for causing a processor to execute and implement the AI ​​model inference method according to any embodiment of the present invention.

[0009] According to another aspect of the present invention, a computer program product is provided, the computer program product comprising a computer program that, when executed by a processor, implements the AI ​​model inference method described in any embodiment of the present invention.

[0010] The AI ​​model inference middleware provided in this invention, through a bidirectional decoupling design of the upper-layer interaction module and the lower-layer adaptation module, encapsulates inference capabilities into independent and reusable library modules, while shielding the differences in the underlying heterogeneous AI inference backend. This achieves complete isolation between the application layer and the hardware layer, significantly reducing architectural coupling and cross-platform adaptation costs. The model management module maintains AI model instances, and the pipeline scheduling module, based on a node-based asynchronous pipeline architecture, splits inference tasks into multiple independent processing stages. Each node executes in parallel under the drive of an independent worker thread, and the inference process does not block the main thread, effectively improving multi-task concurrent processing capabilities and system throughput. The channel buffer management module provides a data queue for temporary storage of transferred data objects between adjacent nodes, and utilizes an object buffer pool for cyclical reuse of idle data objects, separating data transfer from object management. This significantly reduces frequent memory allocation and release operations, lowers memory fragmentation, and thus achieves efficient, stable, and scalable operation of the AI ​​inference module overall, significantly improving development efficiency and resource utilization efficiency.

[0011] It should be understood that the description in this section is not intended to identify key or essential features of the embodiments of the present invention, nor is it intended to limit the scope of the invention. Other features of the invention will become readily apparent from the following description. Attached Figure Description

[0012] To more clearly illustrate the technical solutions in the embodiments of the present invention, the accompanying drawings used in the description of the embodiments will be briefly introduced below. Obviously, the accompanying drawings described below are only some embodiments of the present invention. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort.

[0013] Figure 1 This is a schematic diagram of the structure of an AI model inference middleware provided in Embodiment 1 of the present invention; Figure 2 This is a schematic diagram of the model state transition mechanism provided in Embodiment 1 of the present invention; Figure 3This is a schematic diagram of the model loading and unloading process provided in Embodiment 1 of the present invention; Figure 4 This is a schematic diagram of the producer-consumer model based on Channel provided in Embodiment 1 of the present invention; Figure 5 This is a schematic diagram of the buffer pool management mechanism provided in Embodiment 1 of the present invention; Figure 6 This is a flowchart of an AI model inference method provided in Embodiment 2 of the present invention; Figure 7 This is a flowchart of another AI model inference method provided in Embodiment 2 of the present invention; Figure 8 This is a schematic diagram of the structure of an AI model inference device according to Embodiment 3 of the present invention; Figure 9 This is a schematic diagram of the structure of an electronic device that implements the AI ​​model inference method of this invention. Detailed Implementation

[0014] To enable those skilled in the art to better understand the present invention, the technical solutions of the present invention will be clearly and completely described below with reference to the accompanying drawings of the embodiments of the present invention. Obviously, the described embodiments are only some embodiments of the present invention, and not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort should fall within the scope of protection of the present invention.

[0015] It should be noted that the terms "first," "second," etc., in the specification, claims, and accompanying drawings of this invention are used to distinguish similar objects and are not necessarily used to describe a specific order or sequence. It should be understood that such data can be interchanged where appropriate so that the embodiments of the invention described herein can be implemented in orders other than those illustrated or described herein. Furthermore, the terms "comprising" and "having," and any variations thereof, are intended to cover non-exclusive inclusion; for example, a process, method, system, product, or apparatus that comprises a series of steps or units is not necessarily limited to those steps or units explicitly listed, but may include other steps or units not explicitly listed or inherent to such processes, methods, products, or apparatus.

[0016] Example 1 Figure 1 This is a schematic diagram of the structure of an AI model inference middleware provided in Embodiment 1 of the present invention. Figure 1As shown, the AI ​​model inference middleware includes: an upper-layer interaction module 11, a lower-layer adaptation module 12, a model management module 13, a pipeline scheduling module 14, and a channel buffer management module 15. The functions of each module are described below: The upper-layer interaction module 11 is used to receive inference task instructions issued by the upper-layer application and to feed back the inference results to the upper-layer application.

[0017] The upper-layer interaction module refers to the communication interface component configured at the front end of the AI ​​model inference middleware, facing the business application layer, responsible for establishing a data path between the middleware and the upper-layer application. The upper-layer application refers to a business application running on the AI ​​model inference middleware, such as an object detection application, a face recognition application, or an image classification client on the Android platform. The inference task instruction refers to the control instruction issued by the upper-layer application to initiate the AI ​​inference process. This instruction may include the input data to be processed (such as image data, file paths, etc.) and information such as the model identifier of the specified AI model. The inference result refers to the data output by the AI ​​model after completing the inference calculation, such as the coordinate information of the object detection box, the label ID of the classification task, and the confidence score.

[0018] In this embodiment of the invention, the upper-layer interaction module 11 provides standardized Java interfaces for upper-layer applications to call via JNI (Java Native Interface) technology, including interfaces such as model loading (loadModel()), data push (sendFrame()), and result callback registration (setCallback()). The application layer can integrate the AI ​​model inference middleware provided in this embodiment into any Android project via Gradle dependency. By calling the aforementioned interfaces, AI inference capabilities can be used without needing to concern themselves with details such as underlying locking mechanisms, memory allocation, and thread scheduling. Simultaneously, the upper-layer interaction module 11 is also responsible for optimizing the performance of JNI cross-language calls. This is achieved by merging multiple independent JNI calls into batch calls to reduce the number of cross-language calls, and by using direct buffers to transfer data to reduce the number of data copies between the Java layer and the Native layer, thereby effectively reducing the performance overhead of cross-language calls.

[0019] When the upper-layer application issues an inference task instruction, the upper-layer interaction module 11 can capture and parse the instruction data packet, extracting information such as input data (e.g., camera preview frames) and target AI model identifiers. Simultaneously, it verifies the integrity and format validity of the data (e.g., checking if image data is empty and if model identifiers are compliant) to ensure the input meets the requirements of downstream processing modules. After successful verification, the upper-layer interaction module 11 encapsulates the parsed parameters into a unified data transmission format within the middleware, such as a standardized NodeData object. Subsequently, the upper-layer interaction module 11 inputs the encapsulated data object to the pipeline scheduling module 14 to trigger the subsequent asynchronous inference process. Next, the upper-layer interaction module 11 can use a non-blocking asynchronous callback mechanism to wait for the underlying processing to complete, avoiding blocking the main thread. After the pipeline scheduling module 14 completes the entire inference computation, it can actively trigger the receiving method of the upper-layer interaction module 11 through a pre-registered callback function. After receiving the inference result from the pipeline scheduling module 14, the upper-layer interaction module 11 converts it into a data type that the upper-layer application can recognize (such as a Java layer POJO object or a JSON string), and asynchronously pushes the converted inference result to the main thread or UI thread of the upper-layer application through a callback interface for interface rendering or subsequent business logic processing.

[0020] This embodiment, by setting up an independent and standardized upper-layer interaction module, completely isolates the complex underlying implementation of AI inference (such as locking mechanisms, thread scheduling, and memory allocation) from the upper-layer business code. This allows application developers to quickly integrate AI capabilities simply by calling a minimal API interface, significantly reducing the integration threshold and learning cost of AI functions. Simultaneously, this module employs a callback-based asynchronous non-blocking feedback mechanism, avoiding the main thread lag caused by synchronously waiting for inference results, significantly improving application responsiveness and user experience. Furthermore, a unified data encapsulation and conversion interface enables the middleware to adapt to different application-layer data formats, enhancing its versatility and portability, and facilitating horizontal reuse across different projects.

[0021] The underlying adaptation module 12 is used to encapsulate various heterogeneous AI inference backends and provide a unified inference call interface.

[0022] The underlying adaptation module can be a software abstraction layer located in the AI ​​model inference middleware, between the upper model management module and the various heterogeneous AI inference backends. Its core function is to encapsulate the interface differences of different AI software development kits (SDKs), and convert the specific interfaces of each inference backend into a unified standardized interface, thereby decoupling the inference framework from the specific hardware platform.

[0023] Heterogeneous AI inference backends can refer to AI SDKs provided by different chip manufacturers or AI framework providers that run on specific hardware platforms. Examples include, but are not limited to, Unisoc UniAI SDK (supporting NPU and CPU), Google TensorFlow Lite (supporting CPU, GPU and NNAPI), Qualcomm SNPE (supporting DSP, GPU and CPU), Huawei HiAI, MediaTek NeuroPilot, etc. Different backends have significant differences in interface definition, calling method, data type, memory management, etc.

[0024] A unified inference call interface can refer to a set of standardized and consistent APIs provided to the outside world after abstracting and encapsulating the differentiated interfaces of various heterogeneous AI inference backends. This interface may include, but is not limited to, model loading interface, model compilation interface, inference execution interface, resource release interface, and backend management interface, so that the upper-layer caller does not need to care about the specific AI SDK and hardware platform used at the bottom layer to complete the entire process of loading, compiling, inference, and releasing the AI ​​model.

[0025] In this embodiment of the invention, the underlying adaptation module 12 serves as the hardware abstraction layer of the AI ​​model inference middleware. Its core function is to establish a standardized bridge between the model management module 13 and various heterogeneous AI inference backends. The underlying adaptation module 12 first defines a unified inference call interface covering the entire process of model loading, compilation, inference, and release. Then, for each AI SDK that needs to be supported (such as Unisoc UniAI SDK, Qualcomm SNPE, Huawei HiAI, etc.), it implements corresponding adapter classes. Each adapter internally converts the unified interface calls into API calls and data formats specific to that SDK. During middleware initialization, the underlying adaptation module 12 can automatically identify the actual computing backends (NPU, GPU, CPU, etc.) supported by the current device through the hardware detection interface of each SDK, and summarize the detection results into a device capability list. When an upper-layer application initiates a model loading request, the underlying adaptation module 12 can call the corresponding SDK's loading and compilation interfaces according to the preferred backend configuration to compile the model into a hardware-executable format. When an upper-layer application initiates an inference request, the underlying adaptation module 12 calls the SDK's inference interface to perform computation after completing the data format conversion. When the AI ​​model needs to be unloaded, the underlying adaptation module 12 can call the SDK's resource release interface to clean up all resources. The entire process is completely transparent to the upper layer; the upper-layer application and model management module 13 only need to call standardized interfaces and do not need to care about which AI SDK and hardware platform is used at the bottom layer.

[0026] In one embodiment, the inference call interface may include: a model loading interface LoadNetwork(), used to load model files from storage space into memory; a model compilation interface NetworkCompile(), used to compile the loaded model into an instruction format executable by a specific hardware backend; an inference execution interface Inference(), used to receive input tensor data and call the underlying hardware to perform forward inference computation to produce output results; a resource release interface DestroyNetwork(), used to release memory and hardware resources occupied during model operation in response to a model unloading instruction; and a backend management interface GetSupportBackendId(), used to query the types of computing backends supported by the current device, wherein the computing backend types may include NPU, GPU, CPU, etc.

[0027] This embodiment achieves several beneficial effects by building a unified hardware abstraction layer in the AI ​​inference middleware: First, it achieves complete decoupling between the inference framework and the hardware platform. Upper-layer applications and model management modules only need to call the standardized inference interface without needing to care about the specific implementation of the underlying AI SDK, and application code can be seamlessly migrated between different hardware devices. Second, it significantly reduces the adaptation cost of AI inference functions. When it is necessary to support new AI SDKs or hardware platforms, only the corresponding adapter class needs to be added to implement the unified interface, without modifying the upper-layer business code, greatly reducing the workload of development and maintenance. Third, it supports flexible switching of the inference backend. The underlying AISDK backend used can be dynamically switched through configuration files or runtime parameters (such as prioritizing NPU acceleration and automatically downgrading to CPU on devices that do not support NPU), without recompiling or modifying the application code. Fourth, it automatically identifies the available computing backends of the device through hardware detection and automatically selects the optimal hardware to perform inference based on the priority backend list during model compilation, ensuring the best inference performance on different hardware platforms. Fifth, it has good future compatibility. Adding new AI SDKs or hardware types only requires adding adapter implementations, without affecting the existing system, ensuring the long-term scalability and maintainability of the middleware.

[0028] The model management module 13 communicates with the underlying adaptation module 12 and is used to maintain AI model instances.

[0029] The model management module refers to the functional unit within the AI ​​model inference middleware responsible for managing the entire lifecycle of AI models. This may include operations such as adding and registering model instances, monitoring their status, finding references, and destroying and recycling them. An AI model instance can refer to a model object entity that has been loaded from storage media (such as a disk or firmware partition) into system memory and has been parsed and compiled into an executable format specific to hardware (such as an NPU / GPU), allowing the middleware to directly call it to perform inference calculations.

[0030] In this embodiment of the invention, the model management module 13 can maintain a hash mapping table with model identifiers as keys and AI model instance objects as values, supporting the simultaneous loading and management of multiple models. This model mapping table can be bound to a mutex. Any operation involving adding, deleting, querying, or modifying the mapping table must first attempt to acquire the mutex, and the lock must be released immediately after the operation is completed. This ensures that in a multi-threaded environment (multiple nodes or pipelines simultaneously requesting different models), the internal pointers and state of the model mapping table will not be concurrently corrupted, fundamentally eliminating data contention and memory crashes, and guaranteeing the long-term stable operation of the system.

[0031] When the upper-layer application issues an inference task instruction, the model management module 13 first acquires a mutex lock, then searches for the corresponding model instance in the model mapping table based on the target AI model identifier carried in the instruction. If no match is found, the underlying adaptation module 12 is called to load and compile the corresponding model file, create a new instance, and then mark its state as ready through atomic operations and register it in the mapping table, before releasing the lock. If a match is found, the model instance is retrieved directly under lock protection, its state is read, and after confirming that the state is ready, the instance handle is returned to the caller to execute inference. When the underlying adaptation module 12 returns an exception, the model management module 13 switches the instance state to error through atomic operations to prevent subsequent misuse. When the system initiates an unload instruction, the model management module 13 traverses the entire model mapping table, calls the destruction interface of the underlying adaptation module 12 one by one to release hardware resources, atomically updates the state to unloaded, clears the table entries, and destructs the instance object, completing the full resource reclamation.

[0032] In one embodiment, the model management module 13 can use std::mutex mutex in conjunction with std::lock_guard to protect concurrent access to the model mapping table, thereby ensuring thread safety in a multi-threaded environment.

[0033] This embodiment establishes a model management module that internally maintains the mapping relationship between model identifiers and AI model instances, as well as the atomic lifecycle state of each instance. This enables the AI ​​model inference middleware to perform parallel registration, real-time state tracking, and secure lookup of multiple heterogeneous AI model instances, completely resolving the functional limitations of traditional solutions, such as "only one model can be loaded at a time," and the transparency issues of "unknown state during loading." Simultaneously, by combining a hybrid concurrency control strategy of mutex locks and atomic operations, data consistency in a multi-threaded environment is ensured while minimizing lock contention overhead, achieving constant-time efficiency for model lookup. Furthermore, the explicit error state marking mechanism allows the system to quickly detect and isolate abnormal models. Combined with a unified resource destruction process, this effectively avoids memory leaks and GPU memory residue, significantly improving the stability, reliability, and resource utilization efficiency of terminal devices in scenarios involving dynamic loading and frequent switching of multiple models.

[0034] The pipeline scheduling module 14 is communicatively connected to the upper-layer interaction module 11 and the model management module 13, respectively, and is used to construct the corresponding processing pipeline according to the inference task instruction to execute the inference task indicated by the inference task instruction; the processing pipeline includes at least an input node, an inference node and an output node.

[0035] The pipeline scheduling module can refer to the functional unit in the AI ​​model inference middleware that is responsible for dynamically building, configuring and scheduling a data flow processing link (i.e., processing pipeline) composed of multiple processing nodes according to the inference task instructions. It is responsible for the creation, connection, thread allocation, lifecycle management and scheduling control of each processing node during execution. It is used to connect the inference request initiated by the upper-layer interaction module with the model instance provided by the model management module, and coordinate the execution of the complete AI inference process.

[0036] A processing pipeline can refer to an asynchronous data processing link composed of multiple nodes with independent processing functions connected in an orderly manner according to the data flow. It fully covers all processing steps from raw data input to inference result output. Each node is responsible for specific processing functions, such as data reception, preprocessing, inference, postprocessing, and result output.

[0037] The input node is the entry point of the processing pipeline. It is responsible for receiving raw input data (such as image frames, text, etc.) pushed by the upper-layer application, converting it into a unified data format within the pipeline, and then passing it to the downstream node.

[0038] The inference node is the core computing node in the processing pipeline. It is responsible for calling the inference interface of the underlying adaptation module to perform forward propagation calculations based on the loaded target AI model instance and outputting the inference results.

[0039] The output node is the exit node of the processing pipeline. It is responsible for receiving the upstream inference results, standardizing and encapsulating the results, and outputting them to the upper-layer interaction module.

[0040] In this embodiment of the invention, the pipeline scheduling module 14 can establish bidirectional communication connections with the upper-layer interaction module 11 and the model management module 13, respectively, opening up data transmission channels between the three types of modules. Specifically, the pipeline scheduling module 14 can receive inference task instructions from the upper-layer interaction module 11, and simultaneously initiate model queries and model invocation requests to the model management module 13, as well as receive information such as model readiness status and model instance handles returned by the model management module 13. The pipeline scheduling module 14 can adopt a node-based pipeline architecture, where each node acts as an independent processing unit, connected through the pipeline to form a complete data flow processing link. Specifically, the pipeline scheduling module 14 can receive inference task instructions issued by the upper-layer interaction module 11 through the communication link, parse the model identifier, input data type, inference business requirements, pipeline configuration parameters, and other information within the instructions, and determine the processing pipeline type and functional node combination required for the current inference task. Next, the pipeline scheduling module 14 first creates a Pipeline instance corresponding to the business type, and then instantiates the input nodes, inference nodes, output nodes, and other processing nodes in sequence. It then links these nodes in a chain according to the data processing order, forming a directed data flow link, such as [input node → inference node → output node]. Simultaneously, it configures data transmission channels between adjacent nodes to ensure orderly data flow between nodes. Then, the pipeline scheduling module 14 issues a start command to drive the completed processing pipeline: the input node receives external raw data and passes it down; the inference node calls the loaded AI model instance to complete inference calculations; and finally, the output node outputs the inference result, thus fully executing the AI ​​inference process corresponding to the inference task instruction.

[0041] This embodiment coordinates the entire inference process through an independent pipeline scheduling module. Relying on communication capabilities with upper and lower layer modules, it achieves task reception and model resource linkage management. Based on a dynamically buildable multi-node pipeline, the inference business logic is decomposed. This not only allows for flexible adaptation of the processing link according to different inference tasks, decoupling the inference function from the upper layer business and avoiding main thread blocking, but also reduces inference anomalies through pre-verification of model state. At the same time, the modular node architecture facilitates functional expansion and maintenance, greatly improving the operational stability, scenario adaptability, and maintainability of the AI ​​inference system.

[0042] The channel buffer management module 15 is configured between adjacent processing nodes to provide a data queue and an object buffer pool. The data queue is used to temporarily store data objects transferred between adjacent processing nodes, and the object buffer pool is used to cache idle data objects for reuse by processing nodes.

[0043] The channel buffer management module refers to the data transfer and memory management component configured between adjacent processing nodes in the AI ​​model inference middleware. This component integrates mutexes, condition variables, data queues, and object buffer pools to achieve thread-safe data transfer and object lifecycle management.

[0044] An object buffer pool can refer to a storage container that pre-allocates a certain number of idle data objects and manages them centrally. When the channel is constructed, the container creates data object instances according to a preset capacity, which are then used and returned cyclically by each processing node during data processing, avoiding the frequent creation and destruction of data objects.

[0045] A data object can refer to a data container in AI model inference middleware, which serves as the basic unit for data transmission between processing nodes. This container encapsulates business payload data to be processed or already processed, as well as its associated auxiliary management information (such as data type, timestamp, status marker, etc.).

[0046] In this embodiment of the invention, after the pipeline is created, a channel buffer management module 15 can be deployed between two adjacent processing nodes, and corresponding channel instances can be created to isolate the execution sequence of upstream and downstream nodes and achieve asynchronous decoupling of nodes. Furthermore, the channel buffer management module 15 adopts a dual-channel (data queue + object buffer pool) design, separating data transmission and object management. The data queue, as a data transmission channel, can use a first-in-first-out (FIFO) structure to temporarily store data objects transmitted between nodes. An internal synchronization mechanism controls the blocking and waking of producers and consumers, blocking the sender when the queue is full and blocking the receiver when the queue is empty, thus achieving safe data transmission between threads. The object buffer pool, as an object management channel, can pre-create idle data objects with a fixed capacity and store them in the pool during construction. When an upstream node needs a data object, if there is an idle object in the buffer pool, it directly returns the object; if the buffer pool is empty, it does not block and wait, but instead creates a new data object in real time and returns it, ensuring that the caller (producer) can always obtain available objects and is never blocked due to a lack of idle objects. When a downstream node finishes processing a data object and needs to return it, it checks whether the number of free objects in the current cache pool has reached the preset capacity limit. If the limit has not been reached, the reset object is stored in the pool for later reuse. If the limit has been reached, the object is rejected. The buffer pool capacity is fixed and cannot be dynamically expanded, aiming to strictly control memory usage within a preset threshold and avoid memory overflow caused by the infinite growth of the buffer pool on resource-constrained mobile devices.

[0047] This embodiment adds a dual-channel buffer structure (i.e., a channel buffer management module) between adjacent processing nodes. It balances the processing rate differences between upstream and downstream nodes using data queues, achieving asynchronous parallelism. By reusing data objects through an object buffer pool, it significantly reduces frequent memory allocation and release operations during runtime, effectively reducing memory fragmentation and controlling peak memory usage. Simultaneously, it eliminates invalid CPU polling through a blocking and waiting mechanism, significantly reducing terminal device resource consumption while improving the overall throughput of the AI ​​inference pipeline, ensuring stable system operation without lag or memory leaks during long-term real-time inference scenarios.

[0048] The AI ​​model inference middleware provided in this invention, through the decoupling design of the upper-layer interaction module and the lower-layer adaptation module, encapsulates AI inference capabilities into independent and reusable components. This allows the application layer to quickly integrate AI capabilities without needing to concern itself with underlying hardware differences and implementation details, significantly reducing architectural coupling and development and maintenance costs. The model management module centrally maintains AI model instances, providing a stable foundation for instance acquisition and invocation for inference nodes, avoiding repeated model loading, and effectively improving the system's control over model resources and operational stability. The pipeline scheduling module dynamically constructs a processing pipeline containing input nodes, inference nodes, and output nodes based on inference task instructions. It adopts a node-based asynchronous architecture to split the inference task into multiple independent stages, with each stage executing in parallel without blocking the main thread, significantly improving system throughput and application responsiveness. The channel buffer management module, configured between adjacent processing nodes, provides a data queue to temporarily store data objects transferred between nodes, and caches idle data objects in an object buffer pool for cyclic reuse by processing nodes. This separates data transfer from object management, significantly reducing frequent memory allocation and release operations, effectively reducing memory fragmentation and resource consumption. The entire middleware architecture is clear and hierarchical, with each module performing its own function while cooperating with each other, comprehensively improving the portability, operational stability, and resource utilization efficiency of the AI ​​inference system.

[0049] Furthermore, based on the above embodiments of the invention, the model management module 13 is also used for: In response to preset state change conditions, the AI ​​model instance is switched between multiple lifecycle states, including unloaded, loading, ready, error, and unloading.

[0050] Among them, the preset state change conditions can refer to events that trigger the transfer of AI model instances between different lifecycle states, such as including but not limited to: model loading requests initiated by upper-layer applications, model loading and compilation completion events, exceptions occurring during inference, model unloading requests initiated by upper-layer applications, and model resource release completion events.

[0051] The unloaded state can refer to the initial state where model resources have not yet been loaded into memory, model instances have not been created, and no inference operations can be performed.

[0052] The loading state can refer to a transitional intermediate state where the model file is being read from storage into memory, the network structure is being loaded, or it is being compiled into a hardware executable format.

[0053] The READY state can refer to a state where the model has completed all loading and compilation processes, the relevant resources are ready, and it can normally receive inference requests and perform inference calculations.

[0054] An error state (ERROR) can refer to an unavailable state in which an abnormal situation occurs during the loading, compilation, or inference execution of the model, causing the model to be temporarily unable to provide inference services normally.

[0055] The unloading state can refer to a model performing resource release operations, including releasing hardware resources such as video memory, memory, and network structures, and is in an intermediate state transitioning from an available or faulty state to a complete unloading state.

[0056] In this embodiment of the invention, the model management module 13 can continuously monitor various operation commands and inference operation feedback information issued externally. When any preset state change condition is detected, it can execute the corresponding state switching operation according to the preset state transition rules. For example... Figure 2 As shown, the state transition rules specifically include: ① When it is detected that the upper-layer application calls the model loading interface (loadModel()) and the model does not exist or its state is not ready, the AI ​​model instance is switched from the unloaded state (UNLOADED) to the loading state (LOADING).

[0057] ② When the model is detected to be loaded and compiled successfully, the AI ​​model instance is switched from the loading state to the ready state.

[0058] ③ When a model loading or compilation failure is detected, the AI ​​model instance is switched from the loading state to the error state.

[0059] ④ When it is detected that the upper-layer application calls the model unloading interface and the model is currently in the ready state, the AI ​​model instance is switched from the ready state (READY) to the unloading state (UNLOADING).

[0060] ⑤ When an anomaly is detected during model inference, the AI ​​model instance is switched from the READY state to the ERROR state.

[0061] ⑥ When it is detected that the upper-layer application calls the uninstallation interface and the model is currently in an error state, the AI ​​model instance is switched from the error state (ERROR) to the unloaded state (UNLOADED).

[0062] ⑦ When the release of model resources is detected to be complete, switch the AI ​​model instance from the unloading state (UNLOADING) to the unloaded state (UNLOADED).

[0063] This embodiment categorizes AI model instances into multiple lifecycle states and automatically switches between them based on business triggering conditions. This accurately distinguishes different stages of model operation and constrains illegal operations, preventing inference requests from uninitialized, unloading, or faulty models in multi-threaded scenarios. This effectively prevents program crashes, memory access anomalies, and other issues. Simultaneously, it allows real-time monitoring of model health, facilitating rapid identification of abnormal scenarios such as model loading failures and operational malfunctions by the upper layer. This significantly improves system stability and fault detection capabilities in multi-model parallel inference scenarios.

[0064] Furthermore, based on the above embodiments of the invention, the model management module 13 is also used for: Load the corresponding target AI model instance based on the model identifier in the inference task instruction, and batch uninstall the loaded AI model instances in response to the uninstallation instruction.

[0065] In embodiments of the present invention, such as Figure 3 As shown, the dynamic model loading process can be triggered by the upper-layer application by calling the loadModel() interface of the model management module 13 (ModelManager). The specific process is as follows: S1. The upper-layer application constructs a model identifier (modelKey) and the corresponding model configuration information (config, including model file path, model type, preferred backend list, etc.), and calls the model loading loadModel interface of the model management module 13 through the upper-layer interaction module 11, passing in the above parameters to initiate a loading request.

[0066] S2. After receiving the loading request, the model management module 13 first acquires the mutex lock associated with the model mapping table. After successfully acquiring the lock, it performs a lookup operation in the internal model mapping table using the model identifier as the key. If the identifier already exists in the model mapping table and the corresponding model instance is in the READY state, it directly returns success and does not perform duplicate loading; if it does not exist or the state is not READY, it enters the loading process.

[0067] S3. The model management module 13 retrieves complete model configuration information from the global configuration mapping table based on the model identifier, including the absolute path of the model file (modelPath), the network identifier (networkId), and the model type (modelType). Then, it calls the LoadNetwork(modelPath, networkId, modelType) interface of the underlying adaptation module 12 (AI SDK). This interface loads the model file at the specified path from storage space into system memory and returns a network identifier (networkId) upon successful loading, which is used for subsequent compilation, inference, and destruction operations on the model. If loading fails, an error is returned directly, and the process does not proceed further.

[0068] S4. After obtaining a valid network identifier (networkId), the model management module 13 calls the NetworkCompile(networkId, modelType, backends) interface of the underlying adaptation module 12, passing in the network identifier, model type, and a list of preferred backends (e.g., preferred NPU, fallback CPU). Based on the hardware capabilities of the current device, the AI ​​SDK selects the optimal computing backend from the list of preferred backends, compiles the model network loaded into memory into a hardware executable format, and prepares it for inference.

[0069] S5. When the NetworkCompile interface returns success, the model management module 13 creates a model instance structure containing a model object pointer, network identifier (networkId), current state (set to READY), and model configuration information, and stores the instance in the model mapping table using the model identifier as the key. Then, it releases the mutex lock and returns a success message to the upper-layer application. If the NetworkCompile interface returns failure (e.g., backend not supported or compilation timeout), the model management module 13 immediately calls the DestroyNetwork(networkId) interface of the underlying adaptation module 12 to release the network resources loaded into memory, preventing the residual and leakage of allocated resources. After the rollback is complete, the model management module 13 releases the mutex lock and returns a failure message and specific error code to the upper-layer application.

[0070] like Figure 3 As shown, the dynamic model unloading process can be triggered by the upper-layer application by calling the unloadAllModels() interface of the model management module 13 to achieve batch release of all loaded models. The specific process is as follows: S1. After receiving the uninstallation command, the model management module 13 first acquires the mutex lock of the model mapping table to ensure that no new inference requests or loading operations will concurrently access the mapping table during the uninstallation process.

[0071] S2. After successful locking, the model management module 13 begins traversing all model instance entries in the mapping table. For each model instance encountered, the model management module 13 extracts the network identifier (networkId) from the instance structure and calls the resource release DestroyNetwork(networkId) interface of the underlying adaptation module 12 to release all hardware and memory resources occupied by the model, including NPU / GPU memory, CPU memory, and network structure description data. Regardless of whether the destruction interface returns success or failure, the model management module 13 continues to traverse the next model, ensuring that the unloading of other models is not blocked due to the release failure of a single model.

[0072] S3. After all resource release operations for all loaded model instances have been completed (regardless of whether individual releases failed), the model management module 13 atomically updates the state of all model instances in the mapping table to the unloaded state (UNLOADED). Then, it calls the clear method of the mapping table to remove all associations between model identifiers and instances, releasing the memory occupied by the mapping table itself.

[0073] S4. After clearing the model mapping table, the model management module 13 releases the mutex lock and returns the unloading completion to the upper layer application. At this time, no loaded AI model instances are retained in the entire AI model inference middleware, and all related resources have been returned to the operating system.

[0074] This embodiment achieves unified management of multiple models through an on-demand loading mechanism based on model identifiers. Developers can complete loading simply by passing in the model identifier, eliminating the need to repeatedly develop loading logic for different models, effectively reducing coding and maintenance costs. Simultaneously, the middleware supports parallel resident status of multiple models; different model instances can coexist in the mapping table and provide services independently, meeting the needs of multi-task concurrent inference scenarios. Furthermore, the mutex lock protecting the mapping table access during loading ensures thread safety in a multi-threaded environment. In addition, the batch unloading mechanism can release all hardware computing power and memory resources occupied by loaded models in a single call, effectively preventing idle models from residing on the terminal for extended periods, reducing memory fragmentation probability, and minimizing unnecessary background computing power consumption, thereby helping to extend the battery life of terminal devices.

[0075] Furthermore, based on the above embodiments of the invention, the pipeline scheduling module 14 is also used for: Each processing node in the pipeline is given an independent worker thread, and each worker thread drives the corresponding processing node to perform data processing operations in parallel.

[0076] Among them, a worker thread can refer to an independent execution context scheduled by the operating system kernel. Each processing node is allocated a dedicated thread resource when it starts up. This thread only serves the corresponding node and is dedicated to executing the main data processing loop of that node. There is no mutual dependence or interference between threads of different nodes in terms of resource contention, task switching, or execution order.

[0077] In this embodiment of the invention, after receiving the pipeline start command from the upper-layer application, the pipeline scheduling module 14 first confirms that the current processing pipeline has completed the initialization of all nodes. Then, it iterates through all connected processing nodes in the pipeline. For each node, it creates an independent background worker thread by calling a thread creation interface (such as std::thread in the C++ standard library), and sets the entry function of this thread to the main data processing loop function implemented by each node itself. After starting, each worker thread immediately enters the main data processing loop implemented within its respective node. In this main loop, the worker thread first performs a blocking data reception operation: it calls the reception method of the upstream Channel of the current node. If the upstream has not yet sent data, the thread enters a blocked waiting state, completely releasing CPU resources. Once the upstream data arrives, the thread is awakened and retrieves the data object from the Channel. Subsequently, the thread calls the processing logic methods specific to the current node (such as image scaling and normalization in the preprocessing node, model forward computation in the inference node, and non-maximum suppression in the postprocessing node) to process the retrieved data object. After processing is complete, the thread sends the result data to the Channel of the downstream node and calls the buffer return method to return the used data objects to the buffer pool for reuse, and then enters the next round of loop.

[0078] As input data is continuously injected into the pipeline, the worker threads of each node automatically enter a parallel execution state driven by the data. Taking the sequential injection of three consecutive image frames (frame N, frame N+1, and frame N+2) as an example: while the input node is receiving frame N+2, the preprocessing node may be processing image scaling for frame N+1, the inference node may be performing model inference calculations on frame N, and the postprocessing node may be filtering the results of frame N-1. The worker threads of these four nodes are all running simultaneously, each processing different stages of different frames of data. This parallel state is a natural result of the data flow, requiring no explicit task allocation or load balancing intervention from the scheduling module.

[0079] After each worker thread starts up and enters the main loop, the pipeline enters a steady-state operation phase. In this phase, each worker thread independently and repeatedly executes the standard sequence of "data reception—data processing—data transmission—object return." As long as data continues to be injected upstream and the pipeline is not stopped, each thread continues to run, maintaining its own independent processing rhythm: faster-processing nodes immediately enter the next round of receive blocking wait after sending data, until they are awakened when space becomes available in the downstream channel; slower-processing nodes focus on processing the current data, and their processing time is determined by the specific computational logic they encapsulate (e.g., the model computation time of inference nodes is usually much longer than that of preprocessing nodes). There are no explicit synchronization points or waiting barriers between threads; speed matching and flow control are only achieved through the buffer queues of the channels between nodes.

[0080] This embodiment achieves multi-node parallel data processing by allocating a dedicated independent worker thread to each processing node through a pipeline scheduling module. On the one hand, it isolates the execution resources of each node, preventing processing anomalies in a single node from propagating to the entire inference pipeline, thus significantly improving system stability. On the other hand, it eliminates queuing delays caused by serial processing, and the asynchronous parallel processing of data by multiple nodes can significantly improve inference throughput, fully meeting the performance requirements of real-time AI inference on the terminal. Simultaneously, the scheduling mode, where each processing node is bound to a worker thread, ensures that the execution path of each node is fixed and predictable, and the scheduling logic is completely transparent to upper-layer business logic, enhancing the scalability and maintainability of the inference middleware.

[0081] Furthermore, based on the above embodiments of the invention, the pipeline scheduling module 14 is also used for: In response to a stop command, the stop signal is recursively propagated from the entry node of the processing pipeline to the downstream nodes, and each processing node is stopped in reverse order from the downstream node to the upstream node, waiting for the worker threads of each processing node to exit and release resources.

[0082] Among them, the stop instruction can refer to the control instruction issued by the upper-layer application, operating system, or AI model inference middleware to terminate the current operation of the entire processing pipeline.

[0083] In this embodiment of the invention, the pipeline scheduling module 14 can continuously monitor stop commands from the upper-layer application or system layer during operation. When a stop command for a specific processing pipeline is received, the pipeline scheduling module 14 can find the corresponding pipeline instance from the pipeline mapping table based on the pipeline identifier carried in the stop command, and thus locate the entry node of that pipeline. Next, the pipeline scheduling module 14 calls the synchronous stop method (stopSync) of the entry node. Inside this method, the node first acquires a mutex lock to protect the downstream node list, traverses all downstream node lists of the current node, and recursively calls its synchronous stop method for each downstream node in the list. This recursive call can adopt a depth-first strategy: that is, for each downstream node, it first recursively stops all its own downstream nodes, and then stops itself. When a downstream node has been stopped by another path, it returns directly through status flag detection to avoid circular dependencies or repeated stops. The entire recursive process is executed in reverse topological order from the end of the data flow to the beginning of the data flow, ensuring that all nodes stop in the correct order according to their dependencies. That is, downstream nodes release resources before upstream nodes, thereby eliminating the risk that downstream threads still hold resource references when upstream nodes stop.

[0084] Furthermore, when the recursive call reaches the stop method of each processing node, the node can set the atomic stop flag (m_isStopping) to true. This flag informs the worker thread currently executing the data processing loop that it "needs to exit." Then, it broadcasts wake-up calls to all blocked worker threads currently waiting to receive data due to an empty queue or waiting to send data due to a full queue. After broadcasting wake-up calls to all blocked threads, the main thread containing the node (i.e., the thread that called stopSync) calls the join method of the worker thread object. This method puts the main thread into a blocked waiting state until the worker thread execution body completely finishes and exits. After being awakened, the worker thread first checks the close flag (m_closed) or the stop flag (m_isStopping) in the loop condition check. If either flag is true, it exits the main processing loop, performs cleanup operations before thread exit (such as releasing the currently held data object reference), and then naturally exits the thread execution function. At this point, the join method unblocks and returns, indicating that the worker thread has safely terminated.

[0085] After all worker threads have safely exited, a node can call its resource cleanup method. This method performs the following operations in sequence: clears the weak reference list of downstream nodes to ensure that it no longer holds pointers to any downstream nodes; releases dynamically allocated caches and temporary data objects within the node; atomically sets the node's running status flag (m_isRunning) to false; and for Channels with buffer pools, releases data objects that are lingering but not consumed in the buffer pool. Because a bottom-up reverse stopping method is used, all downstream nodes have exited when an upstream node stops, thus preventing downstream threads from accessing buffer resources released upstream, ensuring the safety of resource reclamation from the root. After all cleanup actions are completed, the node marks its own state as "stopped" and recursively calls back to the upper layer. When the entry node's synchronization stop method (stopSync) finally returns, all nodes in the entire processing pipeline have safely stopped and completed cleanup.

[0086] This embodiment achieves a safe, orderly, and complete shutdown of the processing pipeline through the aforementioned recursive stopping mechanism. Regarding safety, the reverse topology of "stopping the downstream first, then the upstream" fundamentally avoids the deadlock or crash risk of accessing destroyed objects caused by upstream nodes prematurely releasing channels while downstream nodes are still blocked waiting for data. Simultaneously, it ensures that when each resource (including channel buffer pools, data objects, and thread contexts) is released, no other thread or node holds a reference to that resource, thus eliminating memory leaks caused by residual resource references. This fundamentally guarantees the determinism and safety of resource reclamation in long-running and frequently start-stop scenarios, completely eliminating the deadlock risk in multi-threaded stopping scenarios. Regarding determinism, the merging method forces each worker thread to completely exit, ensuring that resource cleanup operations do not execute concurrently with active threads, eliminating resource contention and data races, and giving the stopping process a clear and predictable completion time. In terms of integrity, each node performs a standardized cleanup process before exiting, releasing and resetting all real-time data objects that have been queued but not consumed, idle objects in the buffer pool, and upstream and downstream references. This ensures that the system memory state is clean after stopping, with no residual references or memory leaks, thus supporting repeated start-up and shutdown of the pipeline and hot switching of models. It has significant reliability gains for application scenarios that require frequent switching of inference tasks or dynamic loading and unloading of models.

[0087] Furthermore, based on the above embodiments of the invention, the channel buffer management module 15 is also used for: The first condition variable controls the blocking and waking of the sending thread, and the second condition variable controls the blocking and waking of the receiving thread. The first condition variable and the second condition variable are different condition variables.

[0088] The first condition variable can be a thread synchronization primitive associated with the sending thread, such as the `m_notFull` condition variable, which causes the sending thread to enter a blocked waiting state when the data queue in the channel buffer is full, and wakes the sending thread from the blocked state when available space in the queue. The second condition variable can be a thread synchronization primitive associated with the receiving thread, such as the `m_notEmpty` condition variable, which causes the receiving thread to enter a blocked waiting state when the data queue in the channel buffer is empty, and wakes the receiving thread from the blocked state when new data arrives in the queue.

[0089] The sending thread can refer to the worker thread of the processing node that performs the data sending operation. This operation pushes the processed data object into the data queue of the channel buffer management module of the downstream node. The receiving thread can refer to the worker thread of the processing node that performs the data receiving operation. This operation retrieves the data object from the data queue of the channel buffer management module of the upstream node and performs subsequent processing.

[0090] In embodiments of the present invention, such as Figure 4 As shown, this solution adopts a producer-consumer pattern based on Channel, and the specific logic is as follows: S1. When the sending thread writes data, blocking and waking control are achieved through the first condition variable. Specifically, before the sending thread prepares to write the data object to the data queue, it first acquires the mutex lock of the channel buffer management module 15; then it checks whether the current data queue is full: if there is no free storage space in the queue, it calls the first condition variable (such as m_notFull) to perform a blocking operation, the sending thread releases the mutex lock and enters a waiting state; when the downstream receiving thread reads data and the queue frees up a space, the receiving thread triggers the first condition variable to send a wake-up signal; after being woken up, the sending thread re-acquires the mutex lock, checks the queue space again, and if there is a free space, it writes the data object to the queue, and releases the mutex lock after completing the sending operation.

[0091] S2. When the receiving thread reads data, blocking and waking control are achieved through the second condition variable. Specifically, before attempting to read a data object from the data queue, the receiving thread first acquires the mutex lock of the channel buffer management module; then it checks whether the current data queue is empty: if there is no data to be read in the queue, it calls the second condition variable (such as m_notEmpty) to perform a blocking operation, the receiving thread releases the mutex lock and enters a waiting state; when the upstream sending thread writes a new data object and the queue produces readable data, the sending thread triggers the second condition variable to send a wake-up signal; the awakened receiving thread re-acquires the mutex lock, checks the queue data again, and if there is readable data, it retrieves the data object, completes the receiving operation, and releases the mutex lock.

[0092] Throughout the process, the first condition variable only responds to the queue idle event and only wakes up the blocked sending thread; the second condition variable only responds to the queue new data event and only wakes up the blocked receiving thread. The blocking and waking logic of the two types of threads are completely separated, achieving complete decoupling between the producer and consumer in terms of condition waiting and notification mechanisms.

[0093] This embodiment manages the blocking and waking logic of the sending and receiving threads separately by setting two independent condition variables. This allows for precise matching of two different scenarios—a full / empty data queue—to trigger the corresponding thread wake-up, eliminating the invalid wake-up and CPU busy-wait issues caused by a unified condition variable. Simultaneously, by isolating the synchronization control logic of upstream and downstream threads, it avoids data corruption, thread hangs, and other anomalies during concurrent data queue reads and writes. This adapts to multi-node asynchronous data transmission scenarios in AI inference pipelines, thereby reducing CPU resource consumption on terminal devices while ensuring thread safety, and effectively improving the overall inference throughput and system stability of the pipeline.

[0094] Furthermore, based on the above embodiments of the invention, the channel buffer management module 15 is also used for: In response to a close command, a close flag is set and the blocked thread is woken up by a first condition variable and a second condition variable, so that the woken thread exits the blocked state after detecting the close flag.

[0095] The closing instruction can be a control signal issued by an upper-layer application, pipeline scheduling module, or system when it needs to terminate the operation of the channel buffer management module, used to trigger the release of channel resources and the thread exit process. The closing flag can be a boolean status indicator bit (such as m_closed) maintained internally by the channel buffer management module, used to indicate whether the channel has been closed, serving as the basis for the thread to determine whether to continue blocking or exit immediately in the condition variable wait loop.

[0096] In this embodiment of the invention, the channel buffer management module 15 can continuously listen for close commands from the pipeline scheduling module 14 or upper-layer applications. After confirming receipt of the close command, the channel buffer management module 15 first acquires the mutex locks for accessing its internal protected data queue and buffer pool. After successfully acquiring the locks, it sets the internally maintained close flag (m_closed) to a valid value (such as true). This flag uses an atomic type (std::atomic). <bool>This ensures the atomicity and visibility of state changes. After the close flag is set, the channel buffer management module 15 calls the first and second condition variables to wake up all blocked sender and receiver threads. After the wake-up operation is completed, the channel buffer management module 15 releases the previously acquired mutex lock. Then, after all the woken-up threads reacquire the mutex lock, they enter the waiting loop condition check of the condition variables. Since the close flag is true, the waiting conditions of "the queue is not full and not closed" or "the queue is not empty and not closed" are no longer met. Therefore, each woken-up thread immediately exits the waiting loop, terminates the data transmission and reception related operations, and finally completes the thread join and the complete release of resources.

[0097] It's important to understand that for residual data already in the data queue but not yet consumed, the shutdown process prioritizes ensuring thread-safe exit, without forcibly consuming or migrating it; it's released directly along with the destruction of the Channel object. This is because this residual data is typically real-time data with time sensitivity, and processing it after it expires is meaningless.

[0098] This embodiment protects the entire process of modifying the shutdown flag and waking up the thread using a mutex lock. Combined with a mechanism that broadcasts notifications to both the sending and receiving threads using dual condition variables, it effectively avoids concurrency issues such as lost wake-up signals and shared state read / write contention. During the shutdown process, the channel buffer management module prioritizes ensuring the safe exit of threads, refraining from forcibly processing unconsumed real-time data in the channel. Through a cyclical check mechanism using the shutdown flag and condition variables, all blocked threads are able to exit the waiting state in an orderly manner upon detecting the shutdown signal, thus achieving a graceful exit of the channel buffer management module and its associated worker threads. This significantly reduces the risk of permanent thread hangs and unrecoverable resources, effectively avoiding memory leaks and program crashes caused by forced channel shutdown or improper shutdown order, and greatly improving the shutdown reliability and system stability of the AI ​​inference pipeline in long-term operation scenarios.

[0099] Furthermore, based on the above embodiments of the invention, the channel buffer management module 15 is also used for: When the object buffer pool is empty, a new data object is created in real time and returned to the caller; When the number of free objects in the object buffer pool reaches the preset capacity limit, the system refuses to accept data objects returned by the caller. When the number of idle objects has not reached the preset capacity limit, the system receives the data objects returned by the caller, resets the data objects to their initial state, and stores them in the object buffer pool.

[0100] In embodiments of the present invention, such as Figure 5 As shown, the buffer pool management mechanism specifically includes: S1. When the upstream processing node finishes data processing and is ready to send the result to the downstream node, the worker thread of that node first calls the `getBuffer` method of the channel buffer management module to request an available data object instance to encapsulate the data to be sent. Next, when executing the `getBuffer` method, it first acquires the mutex lock inside the channel and then checks whether the object buffer pool is empty. If the buffer pool is empty (i.e., there are currently no free objects available for allocation), this method will not block the calling thread but will immediately call a dynamic memory allocation method (such as `std::make_shared`). <datatype>A new data object instance is created on the heap in real time, then the mutex is released and the pointer to the newly created object is returned directly to the caller.

[0101] S2. After the downstream processing node retrieves a data object from the data queue and completes the corresponding processing (such as inference calculation or post-processing), the node's worker thread calls the `returnBuffer` method of the channel buffer management module to return the used data object to the channel's buffer pool for subsequent reuse. Next, upon receiving the return request, the `returnBuffer` method first acquires a mutex lock, then checks whether the number of free objects in the current object buffer pool has reached the preset capacity limit. Based on the comparison result, two different branch processing steps are executed: if the limit has been reached, step S3 is executed; otherwise, step S4 is executed.

[0102] S3. If the number of free objects in the buffer pool has reached the preset capacity limit, the returnBuffer method refuses to accept the data object returned by the caller, that is, it does not store the object in the buffer pool. At this time, the returnBuffer method directly releases the mutex lock and returns. After the pointer of the data object passed by the caller goes out of scope, the destructor is automatically triggered by the reference counting mechanism of the smart pointer, releasing all the memory resources occupied by the object.

[0103] S4. If the number of free objects in the buffer pool has not yet reached the preset capacity limit, the `returnBuffer` method receives the data object returned by the caller. Before storing the data object in the buffer pool, the `returnBuffer` method first calls the data object's internal reset method to clear all valid data fields (such as image data pointers, feature vector containers, dimensions, timestamps, etc.), restoring the data object to its initial clean state. After the reset is complete, the data object pointer is pushed into the buffer pool, and finally, the mutex is released.

[0104] In one embodiment, the preset capacity limit bufferSize can be flexibly adjusted according to the model inference time and frame rate requirements in actual applications, for example, it can be set to 4. The reasons for this setting are: first, there are usually differences in processing speed between nodes, and 4 buffer objects are sufficient to smooth out the speed differences; second, mobile devices have limited memory, and too many buffer objects will increase memory pressure.

[0105] This embodiment significantly improves the real-time performance and long-term stability of AI inference on terminal devices with limited memory resources through layered logic including dynamic creation of object buffer pools, capacity limit control, and object reset and reuse. Specifically, the strategy of creating new objects in real time when the buffer pool is empty ensures that the inference pipeline does not experience blocking or frame dropping under any load, thus effectively guaranteeing the continuity of real-time inference. The hard constraint of preset capacity limit controls the memory usage of idle objects within a predictable range, effectively avoiding the risk of memory overflow and enabling the framework to run stably on low-memory devices. The circular reuse mechanism of data objects greatly reduces frequent memory allocation and release behaviors, thereby reducing memory fragmentation and garbage collection overhead, and extending the long-term stable operation cycle of the application.

[0106] In one embodiment, the hierarchical use of mutexes is mainly reflected in the cooperation of three independent locks. Specifically, the first layer is the model management lock (m_modelMutex), which protects concurrent access to the model mapping table (m_models) and ensures thread safety for model loading, unloading, and lookup operations in a multi-threaded environment; the second layer is the pipeline scheduling lock (m_pipelineMutex), which protects concurrent access to the pipeline mapping table (m_pipelines) and ensures the safety of pipeline creation, destruction, and lookup operations; the third layer is the performance statistics lock (m_mutex), which protects the statistical data update operations in the performance monitoring module (PerformanceMonitor). Furthermore, in an environment where multiple locks coexist, this embodiment of the invention specifies a strict hierarchical acquisition rule, acquiring locks in a fixed order of model-managed locks → pipeline scheduling locks → performance statistics locks. The core principle is that when holding a higher-level lock, a lower-level lock is not acquired. Moreover, the holding time of all locks is compressed to the smallest code block through the RAII mechanism of lock guards (std::lock_guard), ensuring automatic lock release and fundamentally avoiding deadlocks caused by circular waits. In addition, running status flags (such as running flag, stopped flag, closed flag, etc.) are managed using atomic variables (std::atomic) as a lightweight synchronization supplementary mechanism independent of the aforementioned lock hierarchy.

[0107] Example 2 Figure 6 This is a flowchart of an AI model inference method provided in Embodiment 2 of the present invention. This embodiment is applicable to scenarios where AI model inference can be efficiently executed on mobile terminals or embedded devices. The method can be executed by an AI model inference device, which can be implemented in hardware and / or software and can be configured in an electronic device. Figure 6 As shown in this embodiment, an AI model inference method is provided and applied to the AI ​​model inference middleware described in any embodiment of the present invention. The method specifically includes the following steps: S210: Receive inference task instructions from the upper-layer application through the upper-layer interaction module.

[0108] In this embodiment of the invention, the upper-layer application can issue inference task instructions through the standardized API interface provided by the upper-layer interaction module. The instructions may include input data (such as pixel data of image frames or file paths) and model identifiers (used to specify which AI model to use for inference). After receiving the instruction, the upper-layer interaction module parses and verifies it, extracts the model identifier and input data, and then passes it to the pipeline scheduling module and the model management module for further processing.

[0109] S220. Load the corresponding target AI model instance based on the inference task instruction through the model management module.

[0110] In this embodiment of the invention, after receiving the inference task instruction, the model management module can extract the model identifier; then acquire the model management mutex (m_modelMutex) and search for the model instance corresponding to the model identifier in the model mapping table (m_models). If the corresponding model identifier is found and the status is READY, the model instance is used directly; if the corresponding model identifier is not found or the status is not ready, the following dynamic model loading process is triggered: the model configuration information is searched in the global configuration mapping table according to the model identifier, the LoadNetwork() method of the underlying adaptation module is called to load the model file, the NetworkCompile() method is called to compile the model, a model instance is created and stored in the mapping table, and the status is updated to READY. If a compilation failure occurs during the model loading process, DestroyNetwork() is immediately called to release the loaded network resources, the status is set to UNLOADED, and an error is returned.

[0111] S230. The pipeline scheduling module constructs the corresponding processing pipeline according to the inference task instructions, and configures the channel buffer management module between adjacent processing nodes; the processing pipeline includes at least an input node, an inference node, and an output node.

[0112] In this embodiment of the invention, after receiving the inference task instruction from the upper-layer interaction module, the pipeline scheduling module first extracts the model identifier and business type information from the instruction to determine the required pipeline node structure. Then, it instantiates the input node, inference node (bound to the specified model identifier), and output node sequentially according to the data flow order. Each node only completes internal state initialization at this point without starting a worker thread. Next, it calls the add downstream node interface of each node, pointing the output port of the previous node to the input port of the next node, forming a complete unidirectional acyclic data link. While establishing the connection, a channel buffer management module is created for each pair of adjacent nodes, setting the buffer pool capacity to a preset value (e.g., default 4) and pre-creating a corresponding number of idle data objects to store in the buffer pool. Then, it registers the result callback function pre-set by the upper-layer application through the output node's interface to ensure that the inference result can be correctly returned. Finally, the fully constructed pipeline instance is stored in the pipeline mapping table inside the scheduling module using the model identifier as the key for quick lookup and routing during subsequent data input.

[0113] S240. Receive input data from the inference task instruction through the input node and send the input data to the inference node.

[0114] In this embodiment of the invention, after receiving the inference task instruction from the upper layer, the input node can parse the input data to be inferred (e.g., image frames), and then call the getBuffer method of the channel buffer management module to obtain a free internal data object from the buffer pool. If the buffer pool is empty, a new one is created in real time. The original data is then filled into the storage area of ​​the data object, and metadata fields such as data type, size, and timestamp are set. Next, the input node sends the data object containing the encapsulated data to the data queue of the channel buffer management module, and the enqueueing is completed under the protection of the condition variable synchronization mechanism. The worker thread of the inference node listens to the upstream data queue, and after being awakened by the condition variable, reads the data object carrying the input data in the queue, parses and extracts the input data, thereby completing the data transfer between the input node and the inference node.

[0115] S250: The inference node performs inference calculations based on the target AI model instance and the inference call interface provided by the underlying adaptation module, and sends the obtained inference results to the output node.

[0116] In this embodiment of the invention, the inference node reads a pre-processed input data object from the data queue of the channel buffer management module configured between upstream adjacent nodes. This data object carries the original input data to be inferred. Next, the inference node calls the unified inference call interface provided by the underlying adaptation module, passing the data to be inferred from the input data object and the handle parameter of the target AI model instance to the inference call interface. Upon receiving the call request, the underlying adaptation module forwards the request to the corresponding heterogeneous AI inference backend based on the inference backend bound to the target AI model instance. The inference backend (NPU / GPU / CPU) then performs the actual forward network computation. After completing the inference computation, the inference backend returns the generated inference result to the underlying adaptation module, which then performs format normalization before sending it back to the inference node. The inference node writes the inference result into a data object and sends it to the data queue of the channel buffer management module bound to the downstream output node. Finally, the inference node calls the `returnBuffer` method to reset the data object used this time and return it to the buffer pool. It then loops back to the starting point to continue waiting for and processing the next frame of data, repeating this process until a stop signal is received and the loop exits.

[0117] S260: The inference results are fed back to the upper-layer application via the upper-layer interaction module through the output node.

[0118] In this embodiment of the invention, the output node receives the data object carrying the inference result from the upstream channel buffer management module, performs standardized encapsulation of the inference result according to the preset specifications and supplements the task meta-information (such as task identifier, corresponding model identifier, inference time, status code, etc.), and then submits the encapsulated inference result to the upper-layer interaction module; at the same time, the data object after use is returned to the object buffer pool for reuse. After the upper-layer interaction module performs legality verification on the received inference result, it feeds back the inference result to the upper-layer application through the asynchronous callback interface.

[0119] The AI ​​model inference method provided in this invention receives inference task instructions through an upper-layer interaction module, achieving unified access to inference requests from the entry point. The results are then fed back to the upper-layer application via the same module, constructing a complete asynchronous non-blocking closed loop. This allows the main thread to continue processing other tasks without waiting for inference to complete, significantly improving application responsiveness. The model management module loads corresponding target AI model instances on demand based on inference task instructions, enabling multiple inference tasks to independently load their required models. Model resources are only loaded when needed, effectively avoiding the waste of memory and computing power caused by loading all models simultaneously at device startup, thus improving system resource utilization efficiency. A pipeline scheduling module constructs a processing pipeline including input nodes, inference nodes, and output nodes, and a channel buffer management module is configured between adjacent nodes. This decomposes the complete inference task into three stages: data input, model inference, and result output. Each stage, driven by independent worker threads, transmits and synchronizes data through channel buffers, achieving pipelined parallel processing. This significantly reduces single-frame processing latency and significantly improves the overall system throughput. Meanwhile, the inference node performs calculations based on the unified inference call interface of the target model instance and the underlying adaptation module, which shields the differences between different AI SDKs and hardware, so that the same inference process can run on different hardware platforms without modification, and has good cross-platform compatibility and portability.

[0120] To facilitate a thorough understanding of the technical solution of this invention and its working mechanism in practical applications by those skilled in the art, the following section takes a real-time target detection scenario on a mobile terminal as an example to detail the complete implementation process of the AI ​​model inference middleware and inference method provided by this invention.

[0121] This embodiment uses an object detection application as an example. This application needs to detect target objects (such as people, vehicles, etc.) in images in real time from the camera preview stream and draw detection boxes and category labels on the screen. It can be applied to Android devices equipped with an NPU (Neural Processing Unit). In this embodiment, the pipeline includes the following processing nodes: Input node: Receives raw image data generated by camera preview callback, receives input data from inference task instructions issued by upper-layer application through upper-layer interaction module, and sends the input data to preprocessing node.

[0122] Preprocessing node: Performs preprocessing operations on the image, including scaling the image to the input size required by the YOLO model and normalizing the pixel values ​​to make the data meet the model input requirements.

[0123] Inference Node: Receives preprocessed tensor data, performs inference calculations based on the YOLO model instance loaded by the model management module and the inference call interface provided by the underlying adaptation module, and sends the obtained inference results to the post-processing node.

[0124] Post-processing node: Parses the output tensor of the YOLO model, extracts the coordinate information, class probability and confidence score of candidate detection boxes, then performs the Non-Maximum Suppression (NMS) algorithm to filter out redundant detection boxes, and sends the processed detection results to the output node.

[0125] Output node: Feeds the detection results back to the upper-layer application via the upper-layer interaction module, so that the application can draw detection boxes and labels on the preview screen.

[0126] like Figure 7 As shown, the complete AI inference process includes: S1. The upper-layer interaction module receives inference task instructions from the upper-layer application, parses and verifies the legality of the instructions, extracts the input data and model identifiers, and passes them to the pipeline scheduling module.

[0127] S2. The model management module searches for the corresponding model instance in the model mapping table based on the model identifier in the inference task instruction. If it exists and the status is ready, it is used directly; otherwise, it calls the underlying adaptation module to load and compile the model, stores the new instance in the mapping table, and updates the status to ready.

[0128] S3, the pipeline scheduling module instantiates each processing node (input node, preprocessing node, inference node, postprocessing node and output node) in sequence, connects each node in sequence according to the data flow direction, configures a channel buffer management module between adjacent processing nodes, and registers the result callback function of the upper layer application.

[0129] S4. The pipeline scheduling module calls the start method of the pipeline to create an independent worker thread for each processing node in the pipeline. After each worker thread starts, it enters the main loop and blocks waiting for the arrival of upstream data.

[0130] S5. The input node obtains a free data object through the getBuffer method, writes the input data into the object, and then calls the send method of the downstream node channel to send the data object to the preprocessing node.

[0131] S6. After receiving the data object from the upstream channel, the preprocessing node performs preprocessing operations on the data (such as image scaling, normalization, etc.), and sends the data object to the inference node after processing.

[0132] S7. After receiving the data object from the upstream channel, the inference node obtains the target model instance, calls the inference interface of the underlying adaptation module to perform inference calculation, and sends the output result to the post-processing node.

[0133] S8. After receiving the inference output from the upstream channel, the post-processing node performs post-processing operations (such as confidence filtering, non-maximum suppression, etc.) and sends the final result to the output node.

[0134] S9. The output node converts the inference result into a format that the upper-layer application can recognize. It then pushes the result to the upper-layer application via the upper-layer interaction module through a callback function for subsequent UI display. Finally, it resets the data object and returns it to the object buffer pool.

[0135] S10. Repeat steps S5 to S9. Each node forms a pipeline-style parallel processing under the drive of an independent working thread until a stop instruction is received.

[0136] S11. In response to the stop command, the pipeline scheduling module recursively propagates the stop signal from the entry node to the downstream nodes, and stops each processing node in reverse order from the downstream node to the upstream node. Each node stops its working threads and releases its internal resources.

[0137] S12. In response to the uninstallation command, the model management module traverses the model mapping table, calls the underlying adaptation module to release the resources occupied by each model, updates the status of all models to the unloaded state, and clears the mapping table.

[0138] This embodiment has at least the following technical effects: ① Modular design makes the system easy to maintain and expand, decoupling the functional modules and facilitating independent upgrades and replacements; ② Node-based pipeline architecture improves the system's parallel processing capability, with each node processing different stages of different frames of data simultaneously under the drive of independent worker threads, achieving pipelined parallel computing; ③ Multi-model management mechanism supports the subsequent expansion of other models. The model management module maintains a model instance mapping table with model identifiers as keys, and adding a new model only requires adding the corresponding configuration without modifying existing code; ④ Thread-safe design ensures orderly access to shared resources through mutex locks and atomic operations, avoiding data races and deadlocks, and ensuring long-term stable operation of the system; ⑤ Performance optimization strategy reduces runtime memory allocation through object pooling technology and avoids redundant calculations through inference result caching, effectively improving inference speed and resource utilization efficiency; ⑥ Multiple buffering mechanism, through the separate design of data queues and object buffer pools, achieves circular reuse of data objects, reduces memory allocation overhead, reduces memory fragmentation, and enables the system to maintain stable and efficient inference performance even on mobile devices with limited memory resources.

[0139] Example 3 Figure 8 This is a schematic diagram of the structure of an AI model inference device provided in Embodiment 3 of the present invention. Figure 8 As shown, this device is used in AI model inference middleware and includes: The instruction receiving module 31 is used to receive inference task instructions issued by the upper-layer application through the upper-layer interaction module.

[0140] The model loading module 32 is used to load the corresponding target AI model instance based on the inference task instructions through the model management module.

[0141] The pipeline construction module 33 is used to construct the corresponding processing pipeline according to the inference task instructions through the pipeline scheduling module, and to configure the channel buffer management module between adjacent processing nodes; the processing pipeline includes at least an input node, an inference node and an output node.

[0142] The data input module 34 is used to receive input data from the inference task instructions through the input node and send the input data to the inference node.

[0143] The inference execution module 35 is used to perform inference calculations based on the target AI model instance and the inference call interface provided by the underlying adaptation module through the inference node, and send the obtained inference results to the output node.

[0144] The result feedback module 36 is used to feed back the inference results to the upper-layer application via the upper-layer interaction module through the output node.

[0145] The AI ​​model inference device provided in the embodiments of the present invention can execute the AI ​​model inference method provided in any embodiment of the present invention, and has the corresponding functional modules and beneficial effects of the execution method.

[0146] Example 4 Figure 9 A schematic diagram of an electronic device 40 that can be used to implement embodiments of the present invention is shown. The electronic device is intended to represent various forms of digital computers, such as laptop computers, desktop computers, workstations, personal digital assistants, servers, blade servers, mainframe computers, and other suitable computers. The electronic device can also represent various forms of mobile devices, such as personal digital processors, cellular phones, smartphones, wearable devices (e.g., helmets, glasses, watches, etc.), and other similar computing devices. The components shown herein, their connections and relationships, and their functions are merely illustrative and are not intended to limit the implementation of the invention described and / or claimed herein.

[0147] like Figure 9 As shown, the electronic device 40 includes at least one processor 41 and a memory, such as a read-only memory (ROM) 42 or a random access memory (RAM) 43, communicatively connected to the at least one processor 41. The memory stores computer programs executable by the at least one processor. The processor 41 can perform various appropriate actions and processes based on the computer program stored in the ROM 42 or loaded from storage unit 48 into the RAM 43. The RAM 43 may also store various programs and data required for the operation of the electronic device 40. The processor 41, ROM 42, and RAM 43 are interconnected via a bus 44. An input / output (I / O) interface 45 is also connected to the bus 44.

[0148] Multiple components in electronic device 40 are connected to I / O interface 45, including: input unit 46, such as keyboard, mouse, etc.; output unit 47, such as various types of monitors, speakers, etc.; storage unit 48, such as disk, optical disk, etc.; and communication unit 49, such as network card, modem, wireless transceiver, etc. Communication unit 49 allows electronic device 40 to exchange information / data with other devices through computer networks such as the Internet and / or various telecommunications networks.

[0149] Processor 41 can be a variety of general-purpose and / or special-purpose processing components with processing and computing capabilities. Some examples of processor 41 include, but are not limited to, a central processing unit (CPU), a graphics processing unit (GPU), various special-purpose artificial intelligence (AI) computing chips, various processors running machine learning model algorithms, a digital signal processor (DSP), and any suitable processor, controller, microcontroller, etc. Processor 41 performs the various methods and processes described above, such as AI model inference methods.

[0150] In some embodiments, the AI ​​model inference method may be implemented as a computer program tangibly contained in a computer-readable storage medium, such as storage unit 48. In some embodiments, part or all of the computer program may be loaded and / or installed on electronic device 40 via ROM 42 and / or communication unit 49. When the computer program is loaded into RAM 43 and executed by processor 41, one or more steps of the AI ​​model inference method described above may be performed. Alternatively, in other embodiments, processor 41 may be configured to execute the AI ​​model inference method by any other suitable means (e.g., by means of firmware).

[0151] Various embodiments of the systems and techniques described above herein can be implemented in digital electronic circuit systems, integrated circuit systems, field-programmable gate arrays (FPGAs), application-specific integrated circuits (ASICs), application-specific standard products (ASSPs), systems-on-a-chip (SoCs), payload-programmable logic devices (CPLDs), computer hardware, firmware, software, and / or combinations thereof. These various embodiments may include implementations in one or more computer programs that can be executed and / or interpreted on a programmable system including at least one programmable processor, which may be a dedicated or general-purpose programmable processor, capable of receiving data and instructions from a storage system, at least one input device, and at least one output device, and transmitting data and instructions to the storage system, the at least one input device, and the at least one output device.

[0152] In some embodiments, the AI ​​model inference method may be implemented as a computer program, which is implicitly included in a computer program product. When executed by a processor, the computer program implements the AI ​​model inference method of the present invention. The computer program product can be understood as a software product that primarily implements its solution through a computer program. The computer program used to implement the method of the present invention may be written in any combination of one or more programming languages. These computer programs may be provided to a processor of a general-purpose computer, a special-purpose computer, or other programmable data processing device, such that when executed by the processor, the functions / operations specified in the flowcharts and / or block diagrams are implemented. The computer program may be executed entirely on a machine, partially on a machine, partially on a remote machine as a standalone software package, or entirely on a remote machine or server.

[0153] In the context of this invention, a computer-readable storage medium can be a tangible medium that may contain or store a computer program for use by or in conjunction with an instruction execution system, apparatus, or device. A computer-readable storage medium may include, but is not limited to, electronic, magnetic, optical, electromagnetic, infrared, or semiconductor systems, apparatus, or devices, or any suitable combination thereof. Alternatively, a computer-readable storage medium may be a machine-readable signal medium. More specific examples of machine-readable storage media include electrical connections based on one or more wires, portable computer disks, hard disks, random access memory (RAM), read-only memory (ROM), erasable programmable read-only memory (EPROM or flash memory), optical fibers, portable compact disk read-only memory (CD-ROM), optical storage devices, magnetic storage devices, or any suitable combination thereof.

[0154] To provide interaction with a user, the systems and techniques described herein can be implemented on an electronic device having: a display device (e.g., a CRT (cathode ray tube) or LCD (liquid crystal display) monitor) for displaying information to the user; and a keyboard and pointing device (e.g., a mouse or trackball) through which the user provides input to the electronic device. Other types of devices can also be used to provide interaction with the user; for example, feedback provided to the user can be any form of sensory feedback (e.g., visual feedback, auditory feedback, or tactile feedback); and input from the user can be received in any form (including sound input, voice input, or tactile input).

[0155] The systems and technologies described herein can be implemented in computing systems that include backend components (e.g., as data servers), or middleware components (e.g., application servers), or frontend components (e.g., user computers with graphical user interfaces or web browsers through which users can interact with implementations of the systems and technologies described herein), or any combination of such backend, middleware, or frontend components. The components of the system can be interconnected via digital data communication of any form or medium (e.g., communication networks). Examples of communication networks include local area networks (LANs), wide area networks (WANs), blockchain networks, and the Internet.

[0156] A computing system can include clients and servers. Clients and servers are generally located far apart and typically interact through communication networks. The client-server relationship is created by computer programs running on the respective computers and having a client-server relationship with each other. The server can be a cloud server, also known as a cloud computing server or cloud host, which is a hosting product within the cloud computing service system to address the shortcomings of traditional physical hosts and VPS services, such as high management difficulty and weak business scalability.

[0157] It should be understood that the various forms of processes shown above can be used, with steps reordered, added, or deleted. For example, the steps described in this invention can be executed in parallel, sequentially, or in different orders, as long as the desired result of the technical solution of this invention can be achieved, and this is not limited herein.

[0158] The specific embodiments described above do not constitute a limitation on the scope of protection of this invention. Those skilled in the art should understand that various modifications, combinations, sub-combinations, and substitutions can be made according to design requirements and other factors. Any modifications, equivalent substitutions, and improvements made within the spirit and principles of this invention should be included within the scope of protection of this invention.< / datatype> < / bool>

Claims

1. An AI model inference middleware, characterized in that, include: The upper-layer interaction module is used to receive inference task instructions issued by the upper-layer application and to feed back the inference results to the upper-layer application. The underlying adaptation module is used to encapsulate various heterogeneous AI inference backends and provide a unified inference call interface; The model management module communicates with the underlying adaptation module and is used to maintain AI model instances; The pipeline scheduling module is communicatively connected to the upper-layer interaction module and the model management module, respectively, and is used to construct a corresponding processing pipeline according to the inference task instruction to execute the inference task indicated by the inference task instruction; the processing pipeline includes at least an input node, an inference node, and an output node; The channel buffer management module is configured between adjacent processing nodes to provide a data queue and an object buffer pool. The data queue is used to temporarily store data objects transferred between adjacent processing nodes, and the object buffer pool is used to cache idle data objects for reuse by the processing nodes.

2. The AI ​​model inference middleware according to claim 1, characterized in that, The model management module is also used for: In response to preset state change conditions, the AI ​​model instance is switched between multiple lifecycle states, including unloaded state, loading state, ready state, error state, and unloading state.

3. The AI ​​model inference middleware according to claim 1, characterized in that, The model management module is also used for: Load the corresponding target AI model instance according to the model identifier in the inference task instruction, and unload the loaded AI model instances in batches in response to the uninstallation instruction.

4. The AI ​​model inference middleware according to claim 1, characterized in that, The pipeline scheduling module is also used for: An independent worker thread is created for each of the processing nodes in the processing pipeline, and each worker thread drives the corresponding processing node to perform data processing operations in parallel.

5. The AI ​​model inference middleware according to claim 1, characterized in that, The pipeline scheduling module is also used for: In response to a stop command, a stop signal is recursively propagated from the entry node of the processing pipeline to the downstream nodes, and each processing node is stopped in reverse order from the downstream node to the upstream node, waiting for the worker threads of each processing node to exit and release resources.

6. The AI ​​model inference middleware according to claim 1, characterized in that, The channel buffer management module is also used for: The first condition variable controls the blocking and waking of the sending thread, and the second condition variable controls the blocking and waking of the receiving thread. The first condition variable and the second condition variable are different condition variables.

7. The AI ​​model inference middleware according to claim 1, characterized in that, The channel buffer management module is also used for: In response to a close command, a close flag is set and a first condition variable and a second condition variable are used to wake up the blocked thread so that the woken thread exits the blocked state after detecting the close flag.

8. The AI ​​model inference middleware according to claim 1, characterized in that, The channel buffer management module is also used for: When the object buffer pool is empty, a new data object is created in real time and returned to the caller; When the number of free objects in the object buffer pool reaches the preset capacity limit, the system refuses to accept the data object returned by the caller. When the number of idle objects has not reached the preset capacity limit, the system receives the data object returned by the caller, resets the data object to its initial state, and stores it in the object buffer pool.

9. An AI model inference method, characterized in that, The method, applied to the AI ​​model inference middleware according to any one of claims 1-8, comprises: Receive inference task instructions from the upper-layer application through the upper-layer interaction module; The model management module loads the corresponding target AI model instance based on the inference task instruction; The pipeline scheduling module constructs a corresponding processing pipeline based on the inference task instructions, and a channel buffer management module is configured between adjacent processing nodes; the processing pipeline includes at least an input node, an inference node, and an output node; The input node receives the input data from the inference task instruction and sends the input data to the inference node. The inference node performs inference calculations based on the target AI model instance and the inference call interface provided by the underlying adaptation module, and sends the obtained inference results to the output node. The inference results are fed back to the upper-layer application via the upper-layer interaction module through the output node.

10. An electronic device, characterized in that, The electronic device includes: At least one processor; and A memory communicatively connected to the at least one processor; wherein, The memory stores a computer program that can be executed by the at least one processor, the computer program being executed by the at least one processor to enable the at least one processor to perform the AI ​​model inference method of claim 9.