Compilation graph optimization method and device, edge hardware platform and storage medium

By analyzing the original model, fusing attention operators, reconstructing normalization operators, and transforming non-2D convolution operators, a compilation graph adapted to edge hardware is generated, solving the problems of computation graph expansion and memory consumption on edge devices, and improving computational efficiency and stability.

CN123157192APending Publication Date: 2026-11-24WUJIE ZHIYUAN (SHANGHAI) ELECTRONIC TECHNOLOGY CO LTD +1
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611615004.X
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-10-16
Publication Date
2026-11-24

AI Technical Summary

Technical Problem

Existing computation graph optimization methods are prone to problems such as computation graph bloat, increased memory consumption, high scheduling overhead, and unstable hardware adaptation on edge devices, especially making it difficult to maintain efficient execution on complex models.

Method used

The first computation graph is generated by parsing the original model, the attention operator is fused and the normalization operator is reconstructed, the non-2D convolution operator is transformed into a computation form adapted to edge hardware, and post-processing is performed to generate a compiled graph, optimizing the overall structure and memory usage of the computation graph.

Benefits of technology

It improves the computational efficiency and hardware utilization of the compiled graph on edge hardware platforms, reduces memory usage and scheduling overhead, and enhances the execution stability of the model on edge devices.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN123157192A_ABST
    Figure CN123157192A_ABST
Patent Text Reader

Abstract

This application provides a compilation graph optimization method, apparatus, edge hardware platform, and storage medium. The method includes: parsing an original model to obtain a first computation graph; fusing attention operators in the first computation graph through convolution operations and reconstructing normalization operators to obtain a second computation graph; performing convolution processing on non-two-dimensional convolution operators in the second computation graph to obtain a third computation graph; and post-processing the third computation graph to obtain a compilation graph, which is used to generate an executable program deployed on a hardware platform. This method aims to improve the adaptability of the compilation graph to convolution acceleration characteristics on edge hardware platforms, as well as computational efficiency and hardware utilization.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This application relates to the field of artificial intelligence, and in particular to a compiler graph optimization method, apparatus, edge hardware platform, and storage medium. Background Technology

[0002] The current deployment of artificial intelligence models on edge devices typically involves converting the intermediate representation exported by the front-end framework into a computation graph adapted to the target accelerator after compilation graph optimization.

[0003] However, existing compilation graph optimizations mostly rely on fixed rules and local processing. When faced with redundant operators, attention expansion, normalization decomposition, and broadcast semantic differences, problems such as computation graph expansion, increased memory consumption, high scheduling overhead, and unstable hardware adaptation can easily occur. Complex models are difficult to maintain efficient execution on resource-constrained edge devices.

[0004] Therefore, there is an urgent need for a compilation graph optimization method to transform complex computation graphs into an efficient execution form adapted to edge hardware. Summary of the Invention

[0005] This application provides a compilation graph optimization method, apparatus, edge hardware platform, and storage medium to improve the adaptability of the compilation graph's convolution acceleration characteristics on the edge hardware platform, as well as its computational efficiency and hardware utilization.

[0006] In a first aspect, embodiments of this application provide a compiler graph optimization method, including:

[0007] The original model is analyzed to obtain the first computational graph;

[0008] The attention operators in the first computation graph are fused by convolution operations, and the normalization operator is reconstructed to obtain the second computation graph;

[0009] The non-two-dimensional convolution operators in the second computation graph are convolved to obtain the third computation graph.

[0010] The third computation graph is post-processed to obtain the compilation graph, which is used to generate an executable program deployed on the hardware platform.

[0011] In one possible embodiment, convolution processing is performed on the non-two-dimensional convolution operators in the second computation graph to obtain a third computation graph, including:

[0012] Non-two-dimensional convolution operators in the second computational graph based on declarative pattern recognition;

[0013] The input tensor and / or weights of the non-two-dimensional convolution operator are respectively convolved or convolved into four-dimensional tensors before convolution operation is performed, and the output tensor of the convolution operation is reshaped back to the original dimension to obtain the third computation graph.

[0014] And / or, perform convolution transformation and convolution operation on the tiling operation of each input tensor of the non-two-dimensional convolution operator, and concatenate the output tensors of each convolution operation in the channel dimension to obtain the third computation graph. The tiling operation refers to splitting the input tensor into multiple sub-tensors along the specified dimension.

[0015] And / or, split the non-two-dimensional convolution operators that exceed hardware limitations to obtain a third computation graph.

[0016] In one possible embodiment, the attention operators in the first computation graph are fused through convolution operations, and the normalization operator is reconstructed to obtain the second computation graph, including:

[0017] Based on the attention structure in the first computation graph of declarative pattern recognition, a multi-node computation chain is obtained, which includes: an input projection operator, an attention computation operator, and an output projection operator.

[0018] The input tensor of the multi-node computation chain is reshaped and transposed into a four-dimensional tensor, and the mapping operators in the input projection operator are transformed and merged into a first merging operator in the form of a single two-dimensional convolution.

[0019] For each attention head, the computation operators in the attention computation operator are merged into a second merging operator, and the output projection operator is converted into a two-dimensional convolution form;

[0020] The normalization operator in the first computational graph is obtained by declarative pattern recognition, and the normalization operator is reconstructed through convolution operation to obtain the second computational graph.

[0021] In one possible embodiment, post-processing of the third computation graph includes:

[0022] For each operator in the third computation graph, calculate the total number of bytes of the operator's input tensor, output tensor, and weight tensor;

[0023] If the total number of bytes exceeds the preset memory threshold, the slice is split into blocks along the divisible dimension to reassemble the operator.

[0024] In one possible embodiment, post-processing of the third computation graph includes:

[0025] Based on the broadcast and element-by-element operation structure in the third computation graph of declarative pattern recognition, the order, dimension and / or shape of the broadcast and element-by-element operation structure are normalized.

[0026] Redundant subgraphs in the third computational graph are identified and eliminated based on declarative pattern recognition.

[0027] The layout of the third computation graph, after eliminating redundant subgraphs, is transformed and optimized using probability normalization.

[0028] In one possible embodiment, normalizing the order, dimensions, and / or shape of the broadcast and element-by-element operation structure includes at least one of the following:

[0029] Swap the operand order of broadcast and non-broadcast tensors in the broadcast and element-wise operation structure so that the non-broadcast tensors are placed first.

[0030] When a broadcast dimension is detected to be inconsistent with hardware requirements, the broadcast dimension is migrated to the channel axis specified by the hardware through transpose or insertion operations.

[0031] Based on broadcast semantics, the complete dimensions of the constant tensors involved in the operation are calculated in the target output shape, and the missing dimensions of the constant tensors are filled in based on the complete dimensions.

[0032] In one possible embodiment, when the original model is a batch processing model, the method further includes:

[0033] Along the batch dimension, slice processing is performed on the preset operators in the post-processed third computation graph;

[0034] Redundant patterns generated by slicing are identified and eliminated to extract individual sample tensors directly from the input tuples of the splicing operation.

[0035] Secondly, embodiments of this application provide a compiler graph optimization apparatus, comprising:

[0036] The parsing module is used to parse the original model and obtain the first computational graph;

[0037] An optimization module is used to fuse the attention operators in the first computation graph through convolution operations and reconstruct the normalization operator to obtain a second computation graph;

[0038] The optimization module is also used to perform convolution processing on the non-two-dimensional convolution operators in the second computation graph to obtain the third computation graph;

[0039] The optimization module is also used to post-process the third computation graph to obtain a compilation graph, which is used to generate an executable program deployed on a hardware platform.

[0040] Thirdly, embodiments of this application provide an edge hardware platform, including:

[0041] A processor for executing executable programs deployed on the edge hardware platform;

[0042] A memory for storing a compilation graph generated by the first aspect and / or various possible implementations of the first aspect; the compilation graph is used to generate an executable program deployed on a hardware platform, wherein the first computation graph is obtained by parsing the original model.

[0043] Fourthly, embodiments of this application provide a computer-readable storage medium storing computer-executable instructions, which, when executed by a processor, are used to implement the first aspect and / or various possible implementations of the first aspect.

[0044] Fifthly, embodiments of this application provide a computer program product, including a computer program that, when executed by a processor, implements the first aspect and / or various possible implementations of the first aspect.

[0045] The compilation graph optimization method, apparatus, edge hardware platform, and storage medium provided in this application obtain a first computation graph by parsing the original model, and then fuse the attention operators in the first computation graph, reconstruct the normalization operators, perform convolution processing on the non-two-dimensional convolution operators, and perform post-processing on the processed computation graph. This can reduce redundant structures and heterogeneous operator forms in the computation graph, improve the overall regularity and consistency of the computation graph, thereby reducing memory usage and scheduling overhead, and improving the adaptability and stability of the generated compilation graph to the hardware platform and the deployment and execution efficiency of the executable program. Attached Figure Description

[0046] The accompanying drawings, which are incorporated in and form part of this specification, illustrate embodiments consistent with this application and, together with the description, serve to explain the principles of this application.

[0047] Figure 1 A flowchart illustrating a compiler graph optimization method provided in this application embodiment. Figure 1 ;

[0048] Figure 2 A flowchart of operator convolution transformation provided in this application embodiment;

[0049] Figure 3 A comparative schematic diagram of multi-head attention computation graph fusion before and after, provided for an embodiment of this application;

[0050] Figure 4 A flowchart illustrating a compiler graph optimization method provided in this application embodiment. Figure 2 ;

[0051] Figure 5 This is a schematic diagram of a memory-aware splitting process provided in an embodiment of this application;

[0052] Figure 6 This application provides a schematic diagram of a broadcast optimization strategy process.

[0053] Figure 7 A flowchart illustrating a compiler graph optimization method provided in this application embodiment. Figure 3;

[0054] Figure 8 This is a schematic diagram of a compiler graph optimization device provided in an embodiment of this application;

[0055] Figure 9 This is a schematic diagram of the structure of an edge hardware platform provided in an embodiment of this application.

[0056] The accompanying drawings illustrate specific embodiments of this application, which will be described in more detail below. These drawings and descriptions are not intended to limit the scope of the concept in any way, but rather to illustrate the concept of this application to those skilled in the art through reference to particular embodiments. Detailed Implementation

[0057] Exemplary embodiments will now be described in detail, examples of which are illustrated in the accompanying drawings. When the following description relates to the drawings, unless otherwise indicated, the same numbers in different drawings denote the same or similar elements. The embodiments described in the following exemplary embodiments do not represent all embodiments consistent with this application. Rather, they are merely examples of apparatuses and methods consistent with some aspects of this application.

[0058] Deploying AI models on edge hardware platforms involves steps such as model parsing, computation graph optimization, code generation, and hardware execution. Common applications include smart terminals, automotive devices, industrial inspection equipment, and IoT nodes.

[0059] Current deployment methods typically involve first parsing the original model to obtain an intermediate computational graph, then locally rewriting the operators in the graph according to preset rules, and finally generating an executable program adapted to edge hardware platforms. This type of approach mainly focuses on optimizing convolution operators, while attention, normalization, fully connected, and broadcast-related structures are often preserved in the computational graph as discrete nodes after the front end is expanded.

[0060] When a model includes attention mechanisms, normalized links, and various non-2D convolutional operators, existing optimization processes are prone to problems such as subgraph fragmentation, accumulation of redundant nodes, and inconsistent operator semantics. After importing, attention structures are often expanded into a large number of basic nodes, increasing the scheduling path and the number of intermediate tensors; normalized links, after being fragmented, are difficult to adapt to edge hardware platforms; and there is a mismatch between fully connected, one-dimensional convolutional operators and the convolutional paths preferred by edge accelerators.

[0061] On resource-constrained edge devices, these problems are amplified. Computation graph expansion increases on-chip cache pressure and off-chip memory access frequency, broadcast semantic differences lead to execution instability, and local rule-based optimization struggles to maintain the continuity of the overall graph structure. As a result, complex models struggle to simultaneously maintain low latency, small memory footprint, and stable performance.

[0062] To address the aforementioned technical challenges, a unified optimization path oriented towards the computation graph is adopted to process the first computation graph obtained from the original model parsing as a whole. Convolution operators have a more mature acceleration foundation on edge hardware platforms, attention structures are fused around convolution operations, and normalized links are reconstructed in a hardware-acceptable manner, thus compressing the scheduling and storage burden caused by discrete subgraphs.

[0063] Building upon this, the non-2D convolution operators in the second computation graph are further incorporated into convolutional processing to form a third computation graph that is more adaptable to edge hardware platforms. This is then combined with post-compilation processing to generate a compiled graph for hardware platform deployment. This process follows the deployment architecture of model export, compilation optimization, and hardware execution, focusing on improving the optimization efficiency, hardware adaptability, and operational stability of complex computation graphs.

[0064] Figure 1 A flowchart illustrating a compiler graph optimization method provided in this application embodiment. Figure 1 ,like Figure 1 As shown, the method includes:

[0065] S101: Analyze the original model to obtain the first computational graph.

[0066] Here, the original model refers to the artificial intelligence model to be deployed to the hardware platform. This original model can originate from an intermediate representation file exported by the front-end training framework or from a model exchange format file. For example, the original model could be an Open Neural Network Exchange (ONNX) model. The hardware platform refers to an edge artificial intelligence (AI) accelerator, such as a vision processing unit (NPU) or a vision processing unit (VPU). In this embodiment, the execution entity could be a compiler graph optimization device.

[0067] The first computational graph refers to the intermediate representation (IR) generated from the parsed original model, which carries the operator connections and computational dependencies in the original model. The first computational graph includes redundant operators to be optimized or nodes incompatible with the hardware. Redundant operators can be, for example, consecutive transposes / reshapes. Nodes incompatible with edge hardware platforms can be, for example, unfused attention operators.

[0068] In this step, the original model is parsed to generate a first computation graph containing redundant operators or nodes that are not adapted to edge hardware platforms.

[0069] Specifically, after receiving the original model, the system reads its basic information and then sequentially performs node instantiation, edge connection, constant binding, attribute completion, and shape inference to ultimately generate the first computational graph. Basic information may include, for example, operator type, input / output tensors, parameter constants, topological connections, shape information, operator name, attribute fields, number of input ports, number of output ports, data type, layout information, and constant dependencies.

[0070] In one possible embodiment, when parsing the original model, a model import process is first performed, mapping the operator semantics corresponding to different front-end frameworks to an intermediate representation within the compilation system. Then, a directed acyclic graph is constructed based on the tensor producer-consumer relationship. In another exemplary embodiment, for the original model already derived using the intermediate representation, its nodes and edges can be directly mapped to the first computation graph to prevent premature folding of control and data dependencies in the original model. For model structures containing subgraph calls, conditional branches, or repeating blocks, subgraph unrolling or hierarchical graph indexing can be completed during the parsing phase, enabling subsequent pattern matching to proceed along the unified graph interface. For constant parameters, such as convolution kernels, bias terms, normalization scaling factors, and positional encoding parameters, they can be entered into the constant pool during the parsing phase and linked to the corresponding nodes with reference relationships for direct reuse during subsequent graph rewriting.

[0071] By converting the original model into a first computational graph, a unified graph structure is used to fully carry all the computational nodes of the original model and their connection relationships, enabling subsequent pattern recognition, convolutional rewriting, and post-processing processes to be carried out on a consistent data structure.

[0072] S102: The attention operators in the first computation graph are fused through convolution operations, and the normalization operator is reconstructed to obtain the second computation graph.

[0073] Here, convolution operation refers to the core method of rewriting the operators in the first computation graph in a convolution-friendly manner. Attention operators are the objects to be fused in the attention structure of the first computation graph, and normalization operators are the objects to be reconstructed in the normalization structure of the first computation graph. The second computation graph is an intermediate computation graph obtained after completing the attention operator fusion and normalization operator reconstruction. It retains the optimized graph structure and serves as the input for subsequent convolution processing of non-two-dimensional convolution operators.

[0074] After parsing the original model, the attention structure and normalization structure in the original model will be expanded into multiple basic operator nodes, which makes it impossible to take advantage of the hardware acceleration features of convolution or to be supported by the hardware.

[0075] For example, in the original model, such as the Transformer architecture, the attention structure is its core computational unit. However, after importing ONNX into the model, the attention structure is expanded into multiple basic operator nodes, resulting in multiple memory allocations and releases. The peak memory usage far exceeds the requirements after fusion, and the scheduling overhead of each operator accumulates, making it impossible to utilize the hardware's acceleration features for convolution. Taking the multi-head attention (MHA) mechanism in the original model as an example, after importing ONNX, a single MHA is expanded into 25+ basic operator nodes, including: dense→reshape→split→strided_slice→batch_matmul→concatenate→softmax→…

[0076] The normalization chain in the original model is expanded into a series of basic operators after being imported into ONNX. This results in the inability to call hardware-provided acceleration instructions, multiple unnecessary memory reads and writes in intermediate results, and potential degradation of numerical precision due to multiple rounding operations. For example, the normalization chain is expanded into a series of basic operators such as mean→sub→square→mean→add(eps)→sqrt→div→mul(gamma)→add(beta).

[0077] In this step, based on the subgraph structure related to the attention mechanism and normalization links on the first computational graph of declarative pattern recognition, the originally scattered mapping nodes and computational nodes are rewritten into equivalent structures suitable for convolutional operations. This involves generating new convolutional nodes, necessary rearranged nodes, and reconstructed normalized nodes. Finally, the atomic graph is replaced with the new nodes, thereby reducing the number of independent nodes and intermediate tensors. After the replacement is complete, intermediate nodes and intermediate tensors that have lost their references are deleted, forming the second computational graph.

[0078] For example, the subgraph structure related to the attention mechanism may include nodes such as input mapping, weight mapping, tensor rearrangement, correlation calculation, scaling, probability normalization, and result projection. The subgraph structure related to the normalization link may include an operator chain consisting of multiple basic nodes such as mean calculation, variance calculation, offset addition, square root, reciprocal, scaling, and bias.

[0079] In one possible implementation, the fusion of convolutional operations of attention operators can be achieved by rewriting linear mapping relationships into convolutional computations. For query, key, and value mappings in the original attention structure, their weights and input data can be adapted to the format of convolutional computations; for multiple parallel mapping branches, merging processing can be performed.

[0080] By fusing attention operators and reconstructing normalization operators through convolution operations, the original discrete structure with long scheduling paths can be compressed into a more compact convolution-friendly structure, making the second computation graph more adaptable to the execution units and on-chip storage organization of edge hardware while maintaining functional equivalence.

[0081] S103: Perform convolution processing on the non-two-dimensional convolution operator in the second computation graph to obtain the third computation graph.

[0082] Convolution processing refers to converting non-two-dimensional convolution operators into a form that convolution operations can handle. Examples of convolution processing include dimensionality transformation, weight rearrangement, tensor expansion, and necessary slicing. The third computation graph is the computation graph obtained by performing convolution processing on the non-two-dimensional convolution operators in the second computation graph, providing direct input for subsequent post-processing.

[0083] Edge AI accelerators typically perform depth optimizations on 2D convolutions, but have limited or no support for other operators. For example, fully connected layers cannot directly utilize 2D convolution accelerators; hardware often does not support 1D convolutions and must be upgraded to 2D convolutions; pooling / reduction operations cannot utilize convolution accelerators; and other operators that exceed hardware limitations and are not directly supported by hardware.

[0084] In this application, the second computation graph, after being fused by attention operators and reconstructed by normalization operators, may still contain fully connected, one-dimensional convolution, matrix multiplication, tiling, broadcast-related operators, and other non-two-dimensional convolution operators that do not directly match the convolution execution path of edge hardware platforms. These non-two-dimensional convolution operators, as processing objects for further hardware adaptation, are converted into a form that convolution operations can handle in this step.

[0085] In this step, the compiler graph optimization device filters all non-two-dimensional convolution operator nodes from the second computation graph, performs conversion processing to adapt convolution computation on the non-two-dimensional convolution operators, maps computations that were not originally convolutions to convolution computation semantics for execution, thereby concentrating the main operator paths in the third computation graph to the more mature convolution acceleration channels of the hardware platform.

[0086] Specifically, the computation graph optimization device uses declarative pattern recognition to identify non-2D convolutional nodes in the second computation graph and determines the candidate transformation category for each non-convolutional node. Then, it performs shape analysis for each candidate node, calculating the tensor dimension, convolution kernel shape, stride, padding parameters, and grouping information before and after the transformation. When the convolution mapping conditions are met, it generates alternative convolutional nodes and necessary pre- and post-rearrangement nodes, and updates the edge relationships between nodes. When there are hardware limitations, it simultaneously generates split nodes, merge nodes, or channel clipping nodes. Finally, it deletes the replaced original non-convolutional nodes and corrects the dependencies to obtain the third computation graph.

[0087] In one possible embodiment, for fully connected or matrix multiplication operators, the input feature tensor is expanded into a four-dimensional tensor, and the weight matrix is ​​rearranged into convolution weights corresponding to the output channel, input channel, and spatial kernel size, thereby converting the operator into a 1×1 convolution or equivalent convolution form.

[0088] In one possible implementation, for one-dimensional convolution operators, the input is boosted to a four-dimensional tensor by adding a virtual space dimension, so that the convolution kernel is mapped to a hardware-supported two-dimensional convolution interface.

[0089] In one possible implementation, for cases where the input length is too long or the channel direction exceeds the hardware single-processing limit, the divisible dimension is determined before the convolution conversion, and the corresponding tensor is divided into multiple sub-blocks. Each sub-block generates a convolution node, and then the original output logic is restored by splicing or merging.

[0090] By convolving the non-two-dimensional convolution operators in the second computation graph, more computations can fall into the unified convolution execution path of the edge hardware platform, and the originally semantically scattered operator expressions can be unified into a graph structure that is more adapted to hardware scheduling and storage constraints.

[0091] S104: Post-process the third computation graph to obtain the compiled graph.

[0092] The compilation graph is used to generate an executable program deployed on the hardware platform. Post-processing is a further compilation graph optimization step performed on the third computation graph. Post-processing includes at least one of the following: memory-related processing, broadcast and element-wise operation normalization, redundant subgraph elimination, layout transformation and tidying, and probability normalization-related optimization.

[0093] In this step, the compilation graph optimization device identifies operators in the third computation graph that require further optimization based on declarative pattern recognition, performs post-processing to optimize the third computation graph, and uses the optimized third computation graph as the compilation graph to generate an executable program deployed on the hardware platform.

[0094] For example, taking memory-related processing as an example, if the memory required by the third computation graph exceeds a preset memory threshold, memory optimization is required; otherwise, memory-related processing is skipped. Taking the elimination of redundant subgraphs as an example, for duplicate constant nodes, duplicate rearranged nodes, identity mapping nodes, and nodes without consumers generated by multiple rounds of rewriting in the third computation graph, their reference relationships and functional equivalence are checked one by one. Nodes with the same input, the same attributes, and consistent output are merged into a single node; isolated nodes and invalid constants that no longer participate in the final output path are deleted, etc.

[0095] This application provides a compilation graph optimization method, including: parsing the original model to obtain a first computation graph; fusing attention operators in the first computation graph through convolution operations and reconstructing normalization operators to obtain a second computation graph; performing convolution processing on non-two-dimensional convolution operators in the second computation graph to obtain a third computation graph; and post-processing the third computation graph to obtain a compilation graph, which is used to generate an executable program deployed on a hardware platform. In this application embodiment, by performing a unified graph-level rewriting on the computation graph obtained from parsing the original model, the attention structure, normalization links, and various non-two-dimensional convolution operators are gradually converted into a graph structure more suitable for convolution execution paths. In the post-processing stage, normalization is completed by combining the memory threshold, broadcast requirements, and layout constraints of the hardware platform, enabling the compilation graph to be used to generate an executable program for edge hardware platforms. Automatic identification and replacement of nodes to be optimized avoids the limitations of manual rules. The optimized compilation graph adapts to the convolution acceleration characteristics of edge hardware platforms, improving computational efficiency and hardware utilization, and enhancing the operational stability of model inference.

[0096] In one possible implementation, based on the aforementioned embodiments, a further detailed description is provided of performing convolution processing on the non-two-dimensional convolution operators in the second computation graph to obtain a third computation graph. This includes: using non-two-dimensional convolution operators in the second computation graph based on declarative pattern recognition; performing convolution transformation or convolution boosting on the input tensors and / or weights of the non-two-dimensional convolution operators to four-dimensional tensors before performing convolution operations, and reshaping the output tensors of the convolution operations to their original dimensions to obtain a third computation graph; and / or performing convolution transformation and convolution operations on the tiling operations of each input tensor of the non-two-dimensional convolution operators, and concatenating the outputs of each convolution operation along the channel dimension to obtain a third computation graph; and / or splitting non-two-dimensional convolution operators that exceed hardware limitations to obtain a third computation graph.

[0097] The tiling operation refers to splitting the input tensor into multiple sub-tensors along a specified dimension.

[0098] Specifically, non-2D convolution operators and their input, output, and weight relationships are located based on a declarative pattern. For non-2D convolution operators with single inputs or single weights, their input tensors and / or weights are rewritten as four-dimensional tensors to match the tensor format of the convolution operator. Then, the corresponding convolution operation is performed, and the output tensor is restored to its original dimensions to maintain consistency with the original image interface.

[0099] Figure 2 A flowchart of operator convolution transformation is provided for embodiments of this application, such as... Figure 2 As shown, Figure 2The example demonstrates the unified conversion of three different operator forms into the hardware-optimal two-dimensional convolution operation (hereinafter referred to as Conv2D). The Dense (fully connected layer) transforms the input tensor [N,Cin] into [N,Cin,1,1] and the weights into [Cout,Cin,1,1] through a reshaping operation, making 1×1 Conv2D equivalent to matrix multiplication.

[0100] For example, when the pattern nn.dense(data,weight)[+bias_add] is detected, the two-dimensional input tensor [N,Cin] is reshaped into a four-dimensional tensor [N,Cin,1,1], and the two-dimensional weights [Cout,Cin] are reshaped into a four-dimensional tensor [Cout,Cin,1,1]. Based on the reshaped input and weight tensors, the original fully connected operation is replaced with a combination of convolution nodes and bias addition nodes. The convolution kernel of the convolution node is replaced with [1,1], i.e., nn.conv2d(data,weight,kernel=[1,1])+nn.bias_add. Finally, the output tensor is reshaped back to its original dimensions.

[0101] Continue to refer to Figure 2 One-dimensional convolution operations transform [N,Cin,W] into [N,Cin,1,W] by reshaping, and the convolution kernel into [Cout,Cin,1,Kw]. All paths converge to the hardware Conv2D accelerator for execution, and the output is then reshaped back to the original dimensions.

[0102] For example, when the Conv1dTo2d or Conv1dTransposeTo2d operator is identified, taking the identification of nn.conv1d(data,weight) as an example, the input tensor [N,Cin,W] is reshaped into [N,Cin,1,W]; the weight [Cout,Cin,Kw] is reshaped into [Cout,Cin,1,Kw]; based on the reshaped weight and the input tensor, nn.conv2d is executed, and the output tensor is reshaped into a three-dimensional form.

[0103] For example, when processing batch matrix multiplication (BatchMatmul), taking OfflineMatmulToConv or OnlineMatmul as examples, in offline mode (weights are constant), when the reshape(data)→nn.dense(weight)→reshape chain is detected, the weights are reshaped into a two-dimensional convolution kernel of [OC,IC,1,1]; the input tensor is sliced ​​along the K-dimensional axis using strided_slice, each slice is independently run in two-dimensional convolution, and the results of each slice are accumulated.

[0104] Online mode (both inputs are runtime tensors): 3Dbatch_matmul[B,M,K]×[B,K,N], reshapes the input tensor 3D[B,M,K] into a four-dimensional convolution [B,M,K,1] and executes 4Dbatch_matmul, then reshapes the output into three dimensions.

[0105] For a non-two-dimensional convolution operator with multiple input tensors, the tiling operation of each input tensor is convolved separately, and after convolution is completed in each branch, the branches are spliced ​​together according to the channel dimension to form an equivalent third computation graph.

[0106] For example, when recognizing the tile(a)+tile(b)→concat pattern, the two parallel tile operations are replaced with two independent 1×1 convolution kernels for two-dimensional convolution operations. The two-dimensional convolution operations use their respective weights and expected output shapes, and then the results are concatenated along the channel dimension.

[0107] For non-two-dimensional convolution operators whose computational or storage scale exceeds the constraints of edge hardware platforms, they are split into multiple sub-operators according to the input tensor dimension, output tensor dimension, or weight scale, and the results of the sub-operators are then recombined into the corresponding nodes in the third computation graph.

[0108] For example, for large-stride 2D convolution operations with a stride greater than a preset threshold, the original large-stride convolution operation is extracted into a convolution operation with a specified stride value in the H and W dimensions to adapt to hardware stride limitations. The large-stride convolution operation can be, for example, a convolution operation with a stride greater than 2, and the specified value can be, for example, 1.

[0109] With this implementation, non-2D convolution operators in the second computation graph can be automatically identified and converted into a convolution-friendly graph structure, unifying the intermediate representation of complex operators. The generated third computation graph is more suitable for subsequent code generation and hardware execution. After splitting overloaded operators, operator execution is more likely to fall within the resource constraints of the target platform, improving executability and stability on the hardware platform.

[0110] In one possible implementation, the second computation graph is obtained by fusing the attention operators in the first computation graph through convolution operations and reconstructing the normalization operator. This includes: obtaining a multi-node computation chain based on the attention structure in the first computation graph of declarative pattern recognition, wherein the multi-node computation chain includes: an input projection operator, an attention computation operator, and an output projection operator; reshaping and transposing the input tensor of the multi-node computation chain into a four-dimensional tensor; converting and merging each mapping operator in the input projection operator into a first merging operator in the form of a single two-dimensional convolution; merging each computation operator in the attention computation operator into a second merging operator for each attention head, and converting the output projection operator into a two-dimensional convolution; and reconstructing the normalization operator in the first computation graph of declarative pattern recognition through convolution operations to obtain the second computation graph.

[0111] In this context, the attention structure refers to the continuous computational path corresponding to attention calculation in the original model, which is summarized into a multi-node computation chain. The input projection operator performs linear projection on the input tensor to obtain Q, K, and V. The attention calculation operator performs attention calculation on Q, K, and V. The output projection operator performs projection on the attention calculation result. The first merging operator merges the three originally independent projection results into a single output. The second merging operator performs attention calculation head-by-head. For example, it can perform matrix multiplication of query and key, scaling, optional mask injection, normalization, and matrix multiplication of value head-by-head.

[0112] Specifically, based on the declarative pattern, the continuous computation path corresponding to the attention structure is located and summarized as a multi-node computation chain. The input tensor of the multi-node computation chain is reshaped and transposed into a four-dimensional tensor. For each mapping operator in the input projection operator, its parameters can be mapped to convolution kernels, channel weights, or equivalent convolution representations. Then, adjacent mapping nodes are merged to form the first merging operator, so as to merge the original three independent projection results into one output.

[0113] For each attention head, the computational relationships of each computational operator within the attention computation operator can be rewritten into a convolution-expressible operational form and fused to form a second merging operator. This second merging operator is then used to perform attention computation head-by-head, thereby simplifying the attention computation and converting the output projection operator into a two-dimensional convolutional form. During reconstruction, the normalization operator can rewrite the originally discrete normalized links into a convolution-acceptable computational structure based on its axis information and tensor dimension relationships, outputting a second computational graph that maintains semantic consistency. The adopted convolutional representation is easily matched with the execution units of edge hardware. In practical applications, other equivalent implementations of this convolutional representation can also be selected, and this application does not impose any limitations on this.

[0114] Understandably, attention operators involve multiple operations when performing attention calculations, such as Q×K, concatenation, splitting V values, and attention output. By fusing these multiple computational operators, the original attention calculation operations are simplified.

[0115] For example, taking the fusion standard Multi-Head Attention (MHA) structure as an example, the input tensor is reshaped and transposed to [B, H, W, C] (mapping the sequence length dimension to space H×W), the query (Q), key (K), and value (V) are projected and merged into a single 1×1 Conv2D, Q×K calculation is performed in batches by each head, and scaling, softmax, etc. are completed in the same loop. The output is projected through 1×1 Conv2D + bias_add and then restored to its original shape through reshaping and transposition.

[0116] For example, taking relative positional encoding MHA fusion as an example, on the basis of standard MHA, the calculation of positional bias is also incorporated into a unified Conv2D framework. That is, the positional branch of Q is combined with the positional encoding weight after element-wise addition, and the positional bias score is calculated through 1×1 Conv2D. The content score and the positional score are added together before entering softmax.

[0117] In addition, attention structure fusion schemes can also include attention fusion with positive and negative channel separation, MHA fusion with padding mask, Conv2D conversion of attention mask, multi-head slice matrix multiplication → group convolution merging, etc.

[0118] For example, in attention fusion with positive and negative channel separation, the Q / K channels are divided into positive and negative halves, processed separately, and then merged using multiply / concatenate. The fusion scheme unifies them into a Conv2D framework, preserving the semantics of positive and negative channel separation through strided_slice and negative operations.

[0119] For example, when fusing MHA with padding masks, Q, K, and V can be projected separately through independent fully connected layers, or Q, K, and V can be projected together through a single fully connected layer and then separated by a splitting operator. The fused result is then processed using the input mask. in The transpose of the injection padding mask is then incorporated into the Q×K score matrix.

[0120] For example, when performing Conv2D conversion on the attention mask, the operator chain originally used to construct the mask in the attention structure, expand_dims→broadcast→subtract→multiply, is converted into a two-dimensional convolution-based implementation. Specifically, the mask tensor is first reshaped into a four-dimensional form, processed by a 1×1 two-dimensional convolution operator with all weights of 1, and then multiplied by -1, added by 1, and multiplied by a scaling factor in sequence to obtain the desired mask form.

[0121] Building upon this, for the AttentionMask2 variant, a differentiable approximation of a conditional selection (where) operation is further implemented through clipping and multiplying by -655.04, thereby avoiding the use of the hardware-incompatible where operator.

[0122] For example, when merging multi-head slice matrix multiplication and grouped convolution, the N-way parallel strided_slice→reshape→dense→reshape→concat pattern in the computation graph is identified. This pattern is characterized by N independent matrix multiplications. It is then merged into a single grouped convolution (GroupConv) call. Specifically, all N weights are first concatenated along the output channel dimension, then the input tensor is adapted through transpose and reshaping operations, and finally, all N matrix multiplications are completed in one go using a two-dimensional convolution operator with groups=N.

[0123] For example, Figure 3 This application provides a comparative schematic diagram of multi-head attention computation graph fusion before and after. Figure 3 (a) A multi-head attention computation graph before fusion provided in an embodiment of this application. Figure 3 (b) A fused multi-head attention computation graph provided for an embodiment of this application, such as Figure 3 As shown in (a), the basic operators in the computation graph before fusion include: input → reshaping → fully connected layer (Q projection) → reshaping → Q, K, V separation → performing slice operation head-by-head → transpose and reshaping → Q×K calculation → stitching → multiplying by scaling factor and superimposing mask → Softmax operation → slice (taking V head-by-head) → batch matrix multiplication (attention weight × V) → stitching → dimension transpose and reshaping → fully connected layer (O projection) → bias addition. Figure 3 As shown in (b), the basic operators in the fused computation graph include: input, reshaping and transpose, Q, K, V projection and bias addition → single-head batch matrix multiplication (Q×K multiplied by scaling factor + mask) → Softmax normalization → split-head batch matrix multiplication (attention weights × value matrix K). From Figure 3It can be seen that after attention operator fusion, the originally scattered nodes are compressed into a more compact operator expression in the second computation graph.

[0124] For example, the normalization reconstruction process is as follows: the basic operator chain (mean→broadcast→subtract→power→mean→add→sqrt→divide→multiply→add) is matched and expanded using DFPattern. Then, condition checks are performed, including at least whether gamma / beta is constant, whether the epsilon value matches, and whether the IO amount exceeds the L1 cache. Finally, a rewrite strategy is selected based on the check results: if the IO does not exceed the limit, it is directly replaced with hardware-accelerated nn.layer_norm; if the limit is exceeded, it is split along the H dimension, and layer_norm is executed block by block before being concatenated.

[0125] By fusing the input mapping and attention computation through convolution operations, the originally scattered nodes are compressed into more compact operator representations in the second computation graph. At the same time, the normalization operator is reconstructed by convolution to maintain the consistency of computational semantics and reduce the overhead of intermediate tensor propagation. This results in the convergence of the number of nodes and dependency links in the second computation graph, and the scheduling complexity and storage burden during subsequent compilation and hardware execution are reduced accordingly.

[0126] Figure 4 A flowchart illustrating a compiler graph optimization method provided in this application embodiment. Figure 2 , Figure 4 exist Figure 1 Based on the embodiments, the post-processing of the third computational graph described above will be further explained in detail, such as... Figure 4 As shown, the method includes:

[0127] S401. For each operator in the third computation graph, calculate the total number of bytes of the operator's input tensor, output tensor, and weight tensor.

[0128] In this step, for each operator in the third computation graph, the number of bytes of the input tensor, output tensor, and weight tensor of the operator is summed to obtain the total number of bytes of the operator.

[0129] S402. If the total number of bytes exceeds the preset memory threshold, then the slice is split into blocks along the divisible dimension to reassemble the operator.

[0130] The preset memory threshold refers to the upper limit of memory allowed for a single operator execution or the on-chip capacity threshold of the edge hardware platform, such as an L1 limit. A separable dimension is a dimension that satisfies the operator semantic preservation condition and can be independently computed after slicing.

[0131] In this step, if the total number of bytes of a single operator exceeds the preset memory threshold, it indicates that directly executing the operator as a whole would exceed the hardware's capacity. When the threshold is exceeded, the divisible dimensions are determined based on the tensor dimension information of the operator, and the operator is split into blocks along the divisible dimensions to reassemble it.

[0132] After slicing along this dimension, the original operator is broken down into multiple sub-operators. Each sub-operator processes the data blocks within its corresponding slice interval, maintaining the same computational relationships as the original operator. For operators involving convolution, matrix multiplication, or channel-based aggregation, the channel dimension, output feature dimension, or batch dimension can be used as the splitting object. For operators with broadcast or reduction relationships, dimensions that will not disrupt the consistency of the results are selected based on data dependencies for block-by-block splitting. After each sub-block is executed, the output is reassembled into the complete operator result in the original dimensional order.

[0133] For example, Figure 5 This is a schematic diagram of a memory-aware partitioning process provided in an embodiment of this application, such as... Figure 5 As shown, for each operator, the number of bytes in the input tensor, output tensor, and weight tensor of the operator is summed to obtain the total number of IO bytes for the operator. If the total number of bytes for the operator does not exceed the L1 limit, the operator is kept unchanged and the splitting is skipped; if the total number of bytes for the operator exceeds the L1 limit, the splittable dimension is detected.

[0134] If the width and height of the Conv2D convolution exceed the hardware limitations, the convolution kernel is divided into multiple sub-convolution kernels along the H and W axes, and then stacked for output. If the height or width exceeds the hardware limitations, the original convolution kernel is split into multiple sub-convolution kernels along the dimensions that exceed the hardware limitations, and then stacked for output.

[0135] If the number of bytes in a single Conv2D (including weights) exceeds L1, split the input channel (IC) or the output channel (OC). Slice the weights along the IC / OC direction, slice the input along the IC / OC direction, perform conv2d channel by channel, and concatenate or accumulate the output.

[0136] If the batch size is greater than 1, the input tensor is sliced ​​one by one along the batch dimension; for each sub-tensor obtained after slicing, the original operator is executed independently; finally, the operation results of each sub-tensor are concatenated along the batch dimension to restore the original batch structure.

[0137] If splitting along the H dimension, then cut along the H axis and calculate independently, then cut off the overlapping parts and splice the output results together.

[0138] For example, when the input and output data of the depth-to-space transformation operator exceeds the L1 cache capacity, slice along the H dimension, perform the depth-to-space transformation on each slice, and then concatenate the outputs of each slice along the H dimension.

[0139] For example, when the amount of input and output data broadcast to the same shape operator (broadcast_to_like) exceeds the L1 buffer capacity, slice along the H dimension, perform the broadcast to the same shape operation on each slice, and then concatenate the outputs of each slice.

[0140] For example, for the feedforward network module of the visual Transformer, it is divided into blocks along its sequence length dimension (H-axis), specifically:

[0141] The input tensor is sliced ​​along the H-axis, and overlapping regions are preserved during slicing to handle the filling boundary effect of convolution operations at the block boundaries. The complete feedforward network operator chain is executed independently for each slice. After removing the overlapping regions between slices, the outputs of each slice are spliced ​​along the H-axis to obtain the complete output.

[0142] By splitting the data, the number of input and output bytes in each block is made smaller than the L1 cache capacity.

[0143] This application provides a compiler graph optimization method that calculates the total number of bytes for each operator in a third compiler graph. If the total number of bytes exceeds a preset memory threshold, the compiler slices the graph along a divisible dimension to reassemble the operators. This allows the operators in the third compiler graph to be reconstructed according to memory constraints before entering the compiler graph, thus controlling the data size of a single execution within the limits allowed by the edge hardware platform. This enables the operators to be stably scheduled on the edge hardware and reduces the probability of execution failure caused by excessively large local tensors.

[0144] Based on the aforementioned embodiments, the post-processing of the third computation graph further includes: identifying the broadcast and element-by-element operation structures in the third computation graph based on declarative pattern recognition, and normalizing the order, dimension, and / or shape of the broadcast and element-by-element operation structures; identifying and eliminating redundant subgraphs in the third computation graph based on declarative pattern recognition; and performing layout transformation and probability normalization optimization on the third computation graph after eliminating redundant subgraphs.

[0145] Redundant subgraphs refer to functionally equivalent parts of the computation graph with consistent inputs and outputs. For example, consistent inputs and outputs include continuous reshaping or transpose redundancy, such as frequent combinations like `reshape→reshape`, `transpose→transpose`, and `reshape→transpose→reshape` in the model. The intermediate results have no practical computational meaning but increase memory allocation and scheduling overhead. For example, functional equivalence: operators like `expand_dims`, `squeeze`, and `stack` can all be equivalently converted to `reshape` or `concat`, but the current front-end does not perform normalization. For example, redundancy type conversion: when the input and output types of a `cast` operation are the same, the operation is invalid, but it still exists in the graph.

[0146] The original model's broadcast semantics allow for flexible shape expansion, but there are gaps between implicit broadcasting in the computation graph and explicit broadcasting semantics in the hardware. For example, the operand order of broadcast operations is not standardized, the broadcast dimension is not aligned to the hardware-friendly C-axis (axis=1), and the lack of shape information causes constant broadcasting to fail to execute correctly. Furthermore, when converting the original model to a computation graph, a large number of redundant operators are introduced due to differences in framework and operator granularity.

[0147] Specifically, the module matches broadcast and element-wise operation structures using a declarative pattern library, and normalizes the order, dimensions, and / or shape of these structures. It then continues to traverse and match the third computation graph using declarative pattern recognition, identifying multiple functionally equivalent, input-output consistent, or replaceable local subgraphs by identity mappings. These subgraphs are then removed from the graph structure, resulting in a more compact intermediate graph. Finally, the module performs layout transformation on this intermediate graph and rearranges, merges, or parametrically reduces the operator chains related to probability normalization to align them with the data layout of the target execution unit, yielding an optimized graph for subsequent compilation.

[0148] For example, redundant subgraph optimization could be:

[0149] (1) Merging consecutive transposes;

[0150] Identify two consecutive transpose operations. If the net effect of the two transposes is an identity transformation, remove them directly; otherwise, merge them into a single combined transpose.

[0151] (2) Continuous shape reshaping (reshape) folding;

[0152] Identify continuous shape reshaping, such as the reshape(reshape(data,shape1),shape2) pattern. If the output shapes of the two reshapes are the same, remove them completely; otherwise, merge them into a single reshape(data,shape2) and eliminate intermediate tensors.

[0153] (3) Transpose + Reshape combination elimination (6 variants);

[0154] For the five-node chain reshape→transpose→expr→transpose→reshape, we can analyze the elimination rule of 1-element in the internal dimensions: after removing the dimensions with a value of 1 in the input shape and the output shape, we can compare them. If the pure shapes are the same, it means that the reshape+transpose combination is only for adapting the expression input format and can be directly stripped.

[0155] For example, the following six common transpose / reshape combinations can be identified and eliminated:

[0156] ①PermuteReshape (transpose→reshape net effect is to eliminate during identity transformation);

[0157] ②ReshapeTransReshape (3Dreshape→transpose→reshape, eliminates duplicate shapes);

[0158] ③ReshapeTrans (ReshapeTrans removes the entire chain when the output shape equals the input).

[0159] ④TransReshapeTransReshape(transpose([0,2,1,3])→reshape→transpose([0,2,1])→reshape→simplifies to transpose([0,1,3,2])→reshape);

[0160] ⑤ReshapeTransExprTransReshape (reshape→transpose→expression→transpose→reshape; when the intermediate expression is gelu, add, strided_slice, etc., the transformation is applied directly to the original data, eliminating the external dimensional transformations).

[0161] ⑥TransReshapeExprReshapeTrans (transpose→reshape→expression→reshape→transpose, applies a transformation to the original data, eliminating the external dimensional transformation).

[0162] (4) Redundancy operator normalization

[0163] For ExpandDimsToReshape: expand_dims(data,axis)→reshape(data,new_shape), it is uniformly reduced to reshape;

[0164] For SqueezeToReshape: squeeze(data) → reshape(data, out_shape), it is uniformly reduced to reshape;

[0165] For StackToConcat: stack([a,b],axis) → first reshape each element to add the new dimension, then concat;

[0166] For Negative: negative(data) → multiply(data, -1), eliminates negative operators that are not supported by the hardware;

[0167] For RedudantOpEliminate: Removes cast operations with the same input and output types;

[0168] For ScalarToTensor: Convert the scalar result produced by reduce_mean into a tensor form with keepdims=True to eliminate implicit broadcasting from scalar to tensor;

[0169] For ScatterNDSimplify: detect two consecutive update operations and merge them into a single multiply(data, combined_coeff) operation.

[0170] By broadcasting and element-wise structure normalization, tensor relations are kept consistent with hardware execution semantics; after eliminating redundant subgraphs, invalid nodes and dependent edges are reduced; after layout transformation and probability normalization optimization, the execution deviation caused by tensor rearrangement in the graph is further reduced, and subsequent code generation is more easily mapped to the computing units of the edge hardware platform, improving the execution continuity and resource utilization of the compiled program on the edge hardware.

[0171] Based on the foregoing embodiments, the order, dimensions, and / or shape of the broadcast and element-wise operation structures are further normalized, including at least one of the following: swapping the operand order of broadcast tensors and non-broadcast tensors in the broadcast and element-wise operation structures so that the non-broadcast tensors are placed first; when a broadcast dimension is detected to be inconsistent with hardware requirements, the broadcast dimension is migrated to the channel axis specified by the hardware through transpose or insertion operations; the complete dimension of the constant tensor participating in the operation is calculated according to the broadcast semantics under the target output shape, and the missing dimension of the constant tensor is filled in based on the complete dimension.

[0172] In the specific implementation, for the broadcast and element-wise operation structures identified in the third computation graph, when it is found that the current operand order does not conform to the execution constraints of the edge hardware platform, the operand order of the two input tensors is swapped so that the non-broadcast tensor is placed first.

[0173] When the broadcast dimension is inconsistent with hardware requirements, the dimension layout of the tensors involved in the computation is checked according to the channel axis definition of the edge hardware platform. If the broadcast dimension is located outside the channel axis, the dimension arrangement is changed by transposing, moving the dimension to the position corresponding to the channel axis. If the original tensor dimension is insufficient to directly complete the alignment, an insertion operation is performed while maintaining the broadcast semantics, supplementing a dimension of length one at the specified position so that the broadcast dimension is finally aligned with the channel axis, and generating a standardized tensor form that can be directly parsed by the subsequent compiler.

[0174] For constant tensors involved in the operation, the complete dimensions that they should have are deduced based on the broadcast semantics and the target output shape. Then, the missing dimension information in the constant tensor is supplemented based on the complete dimensions, so that its shape expression is consistent with the broadcast relationship of the output tensor.

[0175] For example, Figure 6 This application provides a schematic diagram of a broadcast optimization strategy process, as shown in the embodiments below. Figure 6 As shown, the broadcast optimization strategy includes at least the following: Strategy 1: After expanding broadcast A to the same shape as B, add the broadcast result to B and front the non-broadcast input; Strategy 2: When the broadcast axis does not match (e.g., when [1,256,1,1] is broadcast to [1,256,128,128], the dimension is not aligned to the C axis), the broadcast dimension is adjusted to the first axis (axis=1) through a transpose operation. And Strategy 3: When the dimension of the constant tensor is inconsistent with the dimension of the data tensor, direct addition cannot meet the dimension alignment requirements of element-wise operation; referring to the broadcast mechanism of NumPy, the shape of the constant tensor is padded; and through an explicit shape reshaping operation, the logical view of the constant tensor is changed to the above four-dimensional shape.

[0176] In this way, broadcast and element-wise operation structures enter the subsequent graph optimization and code generation process in a unified form that conforms to the constraints of edge hardware platforms. This reduces the parsing bias caused by differences in dimensional interpretation and makes constant tensors, broadcast tensors and non-broadcast tensors stably aligned under the same broadcast semantics, thereby improving the executability and compilation consistency of the third computation graph.

[0177] Based on the aforementioned embodiments, when the original model is a batch processing model, the method further includes: performing slicing processing on the preset operators in the post-processed third computation graph along the batch dimension; identifying and eliminating redundant patterns generated by the slicing processing, so as to directly extract individual sample tensors from the input tuples of the splicing operation.

[0178] In this context, "batch processing model" refers to a model where the original model has multiple input tensors and performs parallel inference, with the batch dimension used to distinguish different samples. The post-processed third computation graph refers to the computation graph after convolution and post-processing. Preset operators are operators that need to be further split along the batch dimension in batch scenarios; examples of preset operators include TemporalShiftRewriter, SliceBias, and SliceReLU.

[0179] Slicing decomposes the operator into multiple sample-level sub-operators according to the batch dimension, so that each sample can correspond to an independent computation path. The input tuple of the concatenation operation refers to the tensor set used to receive the results of multiple slices, and the single sample tensor is the target sample data directly extracted from the input tuple.

[0180] After post-processing, if the original model is detected to be a batch processing model, a preset operator and its input / output tensor shapes are located based on the batch dimension. For this preset operator, its input tensor, weight tensor, or intermediate results are split according to the batch dimension, so that the original batch-oriented computation is rewritten into multiple sample-level computation units. For the multiple sub-operators formed after slicing, the connection relationship between them and the splicing operation is further analyzed, and it is identified whether there is a round-trip structure of "slicing first, then splicing, and then extracting by sample". If it is found that there are repeated constructions of the same intermediate tensor, repeated transfers of the same batch fragments, or repeated creation of equivalent slice nodes in the structure, the corresponding redundant pattern is directly deleted from the third computation graph, and the input tuple of the splicing operation is rewritten into a directly indexable sample set, so that a single sample tensor can be directly extracted without invalid splicing and back-slicing.

[0181] By decomposing the operator into sample-level subgraphs in the batch dimension and merging and eliminating duplicate paths generated after slicing, the splicing operation no longer bears the burden of unnecessary data round-trip transmission, reducing the number of intermediate tensors and redundant nodes in the graph, and lowering the memory handling and scheduling overhead during execution.

[0182] For example, Figure 7 A flowchart illustrating a compiler graph optimization method provided in this application embodiment. Figure 3 ,like Figure 7 As shown, the ONNX model is parsed to obtain the first computation graph. If the edge hardware of the model to be deployed is a Dedicated Data Bus (VBUS), only the concatenation layer is deconcatenated. If it is not in VBUS mode, the first computation graph is simplified and validated, and the attention structure and reconstructed normalization structure in the first computation graph are merged to obtain the second computation graph. The non-two-dimensional convolution operators in the second computation graph are transformed to obtain the third computation graph. The third computation graph is then memory-awarely split. If the total number of bytes of an operator exceeds a preset memory threshold, it is split; otherwise, it is not split. After memory-aware splitting, broadcast repair, redundancy repair, and final simplification are performed. If the ONNX model is a batch processing model, it needs to be further split along the batch dimension to obtain the compilation graph.

[0183] Figure 8 This is a schematic diagram of a compiler graph optimization device provided in an embodiment of this application, as shown below. Figure 8 As shown, the compilation graph optimization device 80 provided in this embodiment includes a parsing module 801 and an optimization module 802;

[0184] Among them, the parsing module 801 is used to parse the original model and obtain the first computational graph;

[0185] The optimization module 802 is used to fuse the attention operators in the first computation graph through convolution operations and reconstruct the normalization operator to obtain the second computation graph;

[0186] The optimization module 802 is also used to perform convolution processing on the non-two-dimensional convolution operators in the second computation graph to obtain the third computation graph;

[0187] The optimization module 802 is also used to post-process the third computation graph to obtain a compilation graph, which is used to generate an executable program deployed on the hardware platform.

[0188] In one possible implementation, the optimization module 802 is further configured to: perform convolution transformation or convolution boosting on the input tensors and / or weights of the non-two-dimensional convolution operators to four-dimensional tensors, and then perform convolution operations on the input tensors and / or weights of the convolution operations, and reshape the output tensors of the convolution operations to their original dimensions to obtain a third computation graph; and / or perform convolution transformation and convolution operations on the tiling operation of each input tensor of the non-two-dimensional convolution operators, wherein the tiling operation refers to splitting the input tensor into multiple sub-tensors along a specified dimension, and concatenating the outputs of each convolution operation in the channel dimension to obtain a third computation graph; and / or split the non-two-dimensional convolution operators that exceed hardware limitations to obtain a third computation graph.

[0189] In one possible embodiment, the optimization module 802 is further configured to obtain a multi-node computation chain based on the attention structure in the first computation graph of declarative pattern recognition. The multi-node computation chain includes: an input projection operator, an attention computation operator, and an output projection operator. The input tensor of the multi-node computation chain is reshaped and transposed into a four-dimensional tensor. The mapping operators in the input projection operator are converted and merged into a first merging operator in the form of a single two-dimensional convolution. For each attention head, the computation operators in the attention computation operator are merged into a second merging operator, and the output projection operator is converted into a two-dimensional convolution. Based on the normalization operator in the first computation graph of declarative pattern recognition, the normalization operator is reconstructed through convolution operations to obtain a second computation graph.

[0190] In one possible embodiment, the optimization module 802 is further configured to calculate the total number of bytes of the input tensor, output tensor, and weight tensor of each operator in the third computation graph; if the total number of bytes exceeds a preset memory threshold, the operator is split block by block along the divisible dimension slice to reassemble the operator.

[0191] In one possible embodiment, the optimization module 802 is further configured to: recognize broadcast and element-wise operation structures in the third computation graph based on declarative pattern recognition; normalize the order, dimension, and / or shape of the broadcast and element-wise operation structures; recognize and eliminate redundant subgraphs in the third computation graph based on declarative pattern recognition; and perform layout transformation and probability normalization optimization on the third computation graph after eliminating redundant subgraphs.

[0192] In one possible embodiment, the optimization module 802 is also configured to swap the operand order of broadcast tensors and non-broadcast tensors in the broadcast and element-wise operation structure, so that the non-broadcast tensors are placed first; when a broadcast dimension is detected to be inconsistent with hardware requirements, the broadcast dimension is migrated to the channel axis specified by the hardware through transpose or insertion operations.

[0193] Based on broadcast semantics, the complete dimensions of the constant tensors involved in the operation are calculated in the target output shape, and the missing dimensions of the constant tensors are filled in based on the complete dimensions.

[0194] In one possible embodiment, when the original model is a batch processing model, the optimization module 802 is further configured to perform slicing processing on the preset operators in the post-processed third computation graph along the batch dimension; identify and eliminate redundant patterns generated by the slicing processing, so as to directly extract individual sample tensors from the input tuples of the splicing operation.

[0195] The compiler graph optimization device provided in this embodiment can execute the method provided in the above method embodiment. Its implementation principle and technical effect are similar, and will not be described in detail here.

[0196] Figure 9 This is a schematic diagram of the structure of an edge hardware platform provided in an embodiment of this application. Figure 9 As shown, the edge hardware platform 90 provided in this embodiment includes at least one processor 901 and a memory 902. Optionally, the hardware platform 90 further includes a communication component 903. The processor 901, memory 902, and communication component 903 are connected via a bus 904.

[0197] The memory 902 is used to store the compilation graph generated by the compilation graph optimization method described above. The compilation graph is used to generate an executable program deployed on the hardware platform. The first computation graph is obtained by parsing the original model. Its implementation principle and technical effect are similar, and will not be described again here in this embodiment.

[0198] In the specific implementation, at least one processor 901 is used to execute executable programs deployed on the edge hardware platform.

[0199] In the above embodiments, it should be understood that the processor can be a Central Processing Unit (CPU), or other general-purpose processors, digital signal processors (DSPs), application-specific integrated circuits (ASICs), etc. The general-purpose processor can be a microprocessor or any conventional processor. The steps of the method disclosed in this invention can be directly implemented by a hardware processor, or implemented by a combination of hardware and software modules within the processor.

[0200] The memory may include random access memory (RAM) and may also include non-volatile memory (NVM), such as at least one disk storage device.

[0201] The bus can be an Industry Standard Architecture (ISA) bus, a Peripheral Component Interconnect (PCI) bus, or an Extended Industry Standard Architecture (EISA) bus, etc. Buses can be categorized as address buses, data buses, control buses, etc. For ease of illustration, the buses shown in the accompanying drawings are not limited to a single bus or a single type of bus.

[0202] The compilation graph is obtained by optimizing the first computation graph based on the method provided in the above method embodiment. The compilation graph is used to generate an executable program deployed on a hardware platform. The first computation graph is obtained by parsing the original model.

[0203] The compilation diagram provided in this embodiment has a similar implementation principle and technical effect, and will not be described in detail here.

[0204] This application also provides a computer program product, including a computer program that, when executed by a processor, implements the above-described compiler graph optimization method.

[0205] This application also provides a computer-readable storage medium storing computer-executable instructions, which, when executed by a processor, implement the above-described compiler graph optimization method.

[0206] The aforementioned readable storage medium can be implemented by any type of volatile or non-volatile storage device or a combination thereof, such as static random access memory (SRAM), electrically erasable programmable read-only memory (EEPROM), erasable programmable read-only memory (EPROM), programmable read-only memory (PROM), read-only memory (ROM), magnetic storage, flash memory, magnetic disk, or optical disk. The readable storage medium can be any available medium accessible to a general-purpose or special-purpose computer.

[0207] An exemplary readable storage medium is coupled to a processor, enabling the processor to read information from and write information to the readable storage medium. Of course, the readable storage medium can also be a component of the processor. The processor and the readable storage medium can reside in an Application Specific Integrated Circuit (ASIC). Alternatively, the processor and the readable storage medium can exist as discrete components in the device.

[0208] The division of units is merely a logical functional division; in actual implementation, there may be other division methods. For example, multiple units or components may be combined or integrated into another system, or some features may be ignored or not executed. Furthermore, the coupling or direct coupling or communication connection shown or discussed may be indirect coupling or communication connection through some interfaces, devices, or units, and may be electrical, mechanical, or other forms.

[0209] The units described as separate components may or may not be physically separate. The components shown as units may or may not be physical units; that is, they may be located in one place or distributed across multiple network units. Some or all of the units can be selected to achieve the purpose of this embodiment according to actual needs.

[0210] In addition, the functional units in the various embodiments of the present invention can be integrated into one processing unit, or each unit can exist physically separately, or two or more units can be integrated into one unit.

[0211] If a function is implemented as a software functional unit and sold or used as an independent product, it can be stored in a computer-readable storage medium. Based on this understanding, the technical solution of this invention, or the part that contributes to the prior art, or a part of the technical solution, can be embodied in the form of a software product. This computer software product is stored in a storage medium and includes several instructions to cause a computer device (which may be a personal computer, server, or network device, etc.) to execute all or part of the steps of the methods of the various embodiments of this invention. The aforementioned storage medium includes various media capable of storing program code, such as USB flash drives, portable hard drives, read-only memory (ROM), random access memory (RAM), magnetic disks, or optical disks.

[0212] Those skilled in the art will understand that all or part of the steps of the above-described method embodiments can be implemented by hardware related to program instructions. The aforementioned program can be stored in a computer-readable storage medium. When executed, the program performs the steps of the above-described method embodiments; and the aforementioned storage medium includes various media capable of storing program code, such as ROM, RAM, magnetic disks, or optical disks.

[0213] Finally, it should be noted that other embodiments of the invention will readily occur to those skilled in the art upon consideration of the specification and practice of the invention disclosed herein. This invention is intended to cover any variations, uses, or adaptations of the invention that follow the general principles of the invention and include common knowledge or customary techniques in the art not disclosed herein, and is not limited to the precise structures described above and shown in the accompanying drawings, and various modifications and changes can be made without departing from its scope.

Claims

1. A compiler graph optimization method, characterized in that, include: The original model is analyzed to obtain the first computational graph; The attention operators in the first computation graph are fused by convolution operations, and the normalization operator is reconstructed to obtain the second computation graph; The non-two-dimensional convolution operators in the second computation graph are convolved to obtain the third computation graph; The third computation graph is post-processed to obtain a compilation graph, which is used to generate an executable program deployed on a hardware platform.

2. The method according to claim 1, characterized in that, The step of performing convolution processing on the non-two-dimensional convolution operators in the second computation graph to obtain the third computation graph includes: Based on declarative pattern recognition, non-two-dimensional convolution operators in the second computation graph are identified; The input tensor and / or weights of the non-two-dimensional convolution operator are respectively convolved or convolved into four-dimensional tensors before convolution operation is performed, and the output tensor of the convolution operation is reshaped back to the original dimension to obtain the third computation graph. And / or, perform convolution transformation and convolution operation on the tiling operation of each input tensor of the non-two-dimensional convolution operator, and concatenate the output tensors of each convolution operation in the channel dimension to obtain a third computation graph. The tiling operation refers to splitting the input tensor into multiple sub-tensors along a specified dimension. And / or, split the non-two-dimensional convolution operators that exceed hardware limitations to obtain a third computation graph.

3. The method according to claim 1, characterized in that, The step of fusing the attention operators in the first computation graph through convolution operations and reconstructing the normalization operator to obtain the second computation graph includes: Based on the attention structure in the first computation graph using declarative pattern recognition, a multi-node computation chain is obtained, which includes: an input projection operator, an attention computation operator, and an output projection operator. The input tensor of the multi-node computation chain is reshaped and transposed into a four-dimensional tensor, and the mapping operators in the input projection operator are transformed and merged into a first merging operator in the form of a single two-dimensional convolution. For each attention head, the computation operators in the attention computation operator are merged into a second merging operator, and the output projection operator is converted into a two-dimensional convolution form; The normalization operator in the first computation graph is identified by declarative pattern recognition, and the normalization operator is reconstructed by convolution operation to obtain the second computation graph.

4. The method according to any one of claims 1-3, characterized in that, The post-processing of the third computation graph includes: For each operator in the third computation graph, calculate the total number of bytes of the input tensor, output tensor, and weight tensor of the operator; If the total number of bytes exceeds a preset memory threshold, the operator is split into blocks along the divisible dimension to reassemble the operator.

5. The method according to claim 4, characterized in that, The post-processing of the third computation graph includes: Based on declarative pattern recognition, the broadcast and element-by-element operation structures in the third computation graph are normalized, and the order, dimension and / or shape of the broadcast and element-by-element operation structures are normalized. Redundant subgraphs in the third computation graph are identified and eliminated based on declarative pattern recognition. The layout of the third computation graph, after eliminating redundant subgraphs, is transformed and optimized using probability normalization.

6. The method according to claim 5, characterized in that, The normalization of the order, dimensions, and / or shape of the broadcast and element-by-element operation structure includes at least one of the following: Swap the operand order of the broadcast tensor and non-broadcast tensor in the broadcast and element-wise operation structure so that the non-broadcast tensor is placed first. When a broadcast dimension is detected to be inconsistent with hardware requirements, the broadcast dimension is migrated to the channel axis specified by the hardware through transpose or insertion operations. The complete dimensions of the constant tensors involved in the operation under the target output shape are inferred based on the broadcast semantics, and the missing dimensions of the constant tensors are filled in based on the complete dimensions.

7. The method according to claim 1, characterized in that, When the original model is a batch processing model, the method further includes: Along the batch dimension, slice processing is performed on the preset operators in the post-processed third computation graph; Redundant patterns generated by slicing are identified and eliminated to extract individual sample tensors directly from the input tuples of the splicing operation.

8. A compiler graph optimization apparatus, characterized in that, include: The parsing module is used to parse the original model and obtain the first computational graph; An optimization module is used to fuse the attention operators in the first computation graph through convolution operations and reconstruct the normalization operator to obtain a second computation graph; The optimization module is also used to perform convolution processing on the non-two-dimensional convolution operators in the second computation graph to obtain the third computation graph; The optimization module is also used to post-process the third computation graph to obtain a compilation graph, which is used to generate an executable program deployed on a hardware platform.

9. An edge hardware platform, characterized in that, include: A processor for executing executable programs deployed on the edge hardware platform; A memory for storing a compilation graph generated by the method of any one of claims 1-7; the compilation graph is used to generate an executable program deployed on a hardware platform, wherein the first computation graph is obtained by parsing the original model.

10. A computer-readable storage medium, characterized in that, The computer-readable storage medium stores computer-executable instructions, which, when executed by a processor, are used to implement the method as described in any one of claims 1-7.