Trajectory contract based end-side generated model cross backend mixed precision compilation method
By constructing a trajectory consistency contract and a standardized computation graph, the problem of error localization in cross-platform deployment of edge-generated models is solved, achieving stable generation and coordinated running performance on different backend devices, and improving the adaptability and maintainability of the model.
Patent Information
- Application Number
- CN202611322987.8
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-08-28
- Publication Date
- 2026-11-20
Smart Images

Figure CN123137657A_ABST
Abstract
Description
Technical Field
[0001] This invention belongs to the field of edge-side quantization compilation technology, and in particular relates to a cross-backend mixed-precision compilation method for edge-side generative models based on trajectory contracts. Background Technology
[0002] With the development of generative artificial intelligence technology, edge text-to-image generation models are gradually being applied on mobile terminals and edge devices. These models are mostly based on an iterative denoising generative architecture, which generates image content step by step through multi-step latent variable state updates. They can complete inference locally without relying on cloud services and have the characteristics of strong data privacy and low response latency.
[0003] Mixed-precision compilation is a common technique in edge model deployment. It refers to assigning appropriate numerical precision and quantization methods to operators based on the numerical sensitivity of different network modules. While preserving the generation effect as much as possible, it reduces the latency, memory usage and power consumption of model inference, and adapts to the limited computing power and resource conditions of edge devices.
[0004] The neural network inference backend is the underlying support for the operation of edge models. Currently, mainstream mobile platforms use different vendor-specific inference frameworks, such as Qualcomm AI Runtime on Android and Core ML framework on iOS. Different backends have their own operator fusion rules, numerical implementation logic, and memory scheduling mechanisms. After the same source model is compiled and optimized by different backends, the node boundaries and execution paths of the computation graph will be significantly different.
[0005] When front-end generative models are deployed across platforms, an engineering model with independent conversion and calibration for each back-end is commonly adopted. Common post-training quantization techniques often aim to optimize the reconstruction error of a single forward propagation. For quantization optimization of diffusion-type generative models, calibration strategies are often designed around the activation distribution differences along the time step dimension to improve the quantization effect under a single back-end.
[0006] However, this type of deployment lacks a unified semantic comparison benchmark across backends, making it impossible to trace and analyze the accumulation of errors in the multi-step generation process. The quantized configurations obtained from desktop simulations often exhibit performance deviations when running on real devices. Furthermore, existing mass production solutions struggle to form a closed-loop optimization by incorporating execution feedback from real devices, making it difficult to stably balance generation quality and runtime performance under device resource constraints, thus hindering the multi-platform scalability of edge-side generation models. To address these issues, the following solutions are proposed. Summary of the Invention
[0007] The purpose of this invention is to provide a cross-backend hybrid precision compilation method for edge-side generation models based on trajectory contracts. By constructing a standardized computation graph with step-by-step semantic anchors and mapping it to the backend source, a trajectory consistency contract is established and closed-loop precision repair is performed based on real devices. This can form a unified error verification benchmark across backends, coordinate generation quality and operating overhead under resource constraints, and solve the problems of difficulty in error localization and deviation between desktop calibration and actual machine effects in existing deployment methods.
[0008] To solve the above-mentioned technical problems, the present invention is achieved through the following technical solution: This invention provides a method for cross-backend mixed-precision compilation of end-side generative models based on trajectory contracts, comprising the following steps: Obtain the iterative generation model to be deployed, at least one target backend, the capability description of the target edge device, and the corresponding resource envelope for deployment; The iterative generation model is converted into a normalized computation graph that does not depend on the target backend fusion rules. Each step of the iterative generation is labeled, and trajectory anchor points with stable semantic labels are set at the step boundaries and key subgraph boundaries. A set of calibration test cases with defined input parameters is constructed, and the normalized computation graph is executed with reference accuracy. The reference trajectory signature and final reference output of each trajectory anchor point are collected. The downstream error amplification capability of each trajectory anchor point is estimated, and a differentiated error budget is allocated to each trajectory anchor point based on the total error upper limit to form a trajectory consistency contract. Based on the accuracy and operator capabilities supported by the target backend, candidate accuracy mappings are generated, the normalized computation graph is compiled into candidate artifacts corresponding to the target backend, and a source mapping relationship is established from backend computation nodes to normalized trajectory anchor points. Deploy candidate workpieces to real target edge devices and run calibration test cases to collect real machine trajectory signatures, final output results, and device resource operation data; Based on the source mapping, the actual machine trajectory signature is aligned to the corresponding normalized trajectory anchor point. The anchor point error and the total trajectory error are calculated. It is determined whether the candidate workpiece simultaneously satisfies the trajectory consistency contract and resource envelope constraint. If satisfied, the subsequent steps are performed. If not satisfied, the minimum compilable subgraph with the highest default contribution is located. After adjusting the precision configuration, quantization parameters or compilation strategy, the process is returned to recompile. The accepted candidate artifacts, accuracy mapping, source mapping, device fingerprint information, trajectory contract version, physical acceptance records, and rollback artifact associations are encapsulated into a deployment package specific to the target edge device.
[0009] Furthermore, the trajectory anchor points include at least the input latent variable anchor points and output latent variable anchor points of each denoising generation step, and also include at least one subgraph anchor point from the temporal noise embedding, normalization layer output, attention module output, residual fusion, output convolution, and decoder upsampling node; the stable semantic identifier of the trajectory anchor points is generated by combining module semantics, topological trimming, input and output tensor shapes, parameter sources, and step numbers, and is not affected by back-end operator fusion or splitting.
[0010] Furthermore, the trajectory signature is a structured low-overhead digest of the anchor tensor, which includes at least two of the following: channel mean, channel variance, absolute maximum value, quantile, quantization saturation ratio, normalized direction vector or cosine similarity feature, fixed random projection, and hash digest (for identity verification); the reference trajectory signature and the actual trajectory signature adopt the same calculation rules.
[0011] Furthermore, the estimation of downstream error amplification capability and the allocation of error budget specifically include: injecting a small perturbation similar in shape to quantization noise into the tensor of each reference anchor point; running the downstream reference subgraph corresponding to the anchor point; obtaining the error propagation coefficient of the anchor point based on the degree of error change in the final image; and allocating a local error budget to each anchor point by combining the upper limit of the total trajectory error, the importance weight of the anchor point, and the error propagation coefficient. Anchor points with higher error propagation coefficients are allocated stricter error tolerances, and all budgets are limited to preset safety upper and lower limits.
[0012] Furthermore, the anchor point error is obtained by a weighted combination of three types of error terms: the first type is the normalized root mean square error of the anchor point tensor, the second type is the cosine similarity difference of the anchor point tensor, and the third type is the statistical feature difference of the trajectory signature; the weights of the three types of error terms are dynamically adjusted according to the type of anchor point.
[0013] Furthermore, the generation of the candidate precision mapping aims to minimize the cost of device resources, comprehensively considering four resource indicators: inference latency, memory usage, operating energy consumption, and deployment package size. The candidate configuration must simultaneously meet the constraints of anchor point error, total trajectory error, final image precision, and device resource envelope, and only the precision and operator configuration actually supported by the target backend are adopted.
[0014] Furthermore, the source mapping is generated based on source graph node identifiers, compiler debugging metadata, operator fusion mode library, topological trimming, tensor shape, and step number; a single backend fusion node corresponds to one or more normalized trajectory anchor points, and multiple backend nodes can correspond to the same normalized trajectory anchor point; after the faulty subgraph is located, repair actions are selected from high to low unit cost benefit, including at least one of the following: improving the subgraph accuracy level, adjusting the quantization scale and granularity, closing operator fusion that causes numerical drift, splitting the subgraph for independent refinement, replacing high-precision operator paths, and progressively expanding the backoff range.
[0015] Furthermore, for target backends that cannot directly export intermediate tensors, a dedicated verification probe artifact is compiled and generated: a temporary output node is added at the cut edge of the target topology, or the signature calculation logic is built into the computation graph to output only the trajectory signature; the probe node is removed from the production artifact after acceptance; the production artifact can remove the complete debug probe, but the deployment package retains an independent lightweight self-test probe artifact, or the signature output interface of the selected key anchor point is retained in the production artifact; if the backend completely prohibits additional output, the default subgraph is located by compiling segment by segment or by binary probe.
[0016] Furthermore, the deployment package includes a manifest file that is bound to each workpiece. The manifest records at least six types of information: identity hash of the model and normalized computation graph, backend and compiler version and driver compatibility range, accuracy configuration and quantization parameter summary, trajectory contract and calibration set version information, target device compatibility range and measured resource results, rollback workpiece identifier and fault handling strategy.
[0017] Furthermore, the compilation method also includes runtime artifact selection and self-check rollback steps: when the edge device starts the application, it collects the current device fingerprint and matches the accepted artifacts that are compatible and have the best resource cost in the local deployment package; when a backend driver upgrade, system version change, or device fingerprint is detected that is only within the compatibility range, a lightweight trajectory self-check is performed to compare the key anchor signature with the tolerance range; if the self-check passes, the preferred artifact is loaded; if the self-check fails, it automatically switches to the high-precision rollback artifact; the target backend includes at least one of QNN / HTP, MNN, NNAPI on Android and Core ML on iOS, and the iterative generation model includes a diffusion model, a flow matching model, or a consistency model, and the backbone of its denoising network or velocity prediction network includes U-Net or Diffusion Transformer (DiT).
[0018] The present invention has the following beneficial effects: This invention improves the consistency and adaptability of edge-side generative models across backends with mixed precision compilation. By establishing standardized semantic anchors and backend source mappings, a unified semantic comparison benchmark is constructed between the fusion computation graphs of different backends, providing a basis for error localization. Differentiated error budgets are allocated based on the downstream error propagation characteristics of the anchors, and precision configurations are adjusted in conjunction with feedback from real device execution, coordinating generation quality and runtime overhead under device resource constraints. Relying on a closed-loop process of compilation, verification, and repair, it adapts to the characteristics of diverse edge devices. The deployment package, with its acceptance records and rollback mechanism, supports dynamic runtime adaptation and version compatibility, improving deployment stability and maintainability.
[0019] Of course, any product implementing this invention does not necessarily need to achieve all of the advantages described above at the same time. Attached Figure Description
[0020] To more clearly illustrate the technical solutions of the embodiments of the present invention, the accompanying drawings used in the description of the embodiments will be briefly introduced below. Obviously, the 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.
[0021] Figure 1 This is a flowchart illustrating the cross-backend hybrid precision compilation method for the end-side generation model based on trajectory contracts according to the present invention. Figure 2 This is a schematic diagram of the standardized computation graph, step boundary anchor points, key subgraph anchor points, and Android / iOS backend source mapping for this invention. Figure 3 This is a schematic diagram illustrating the dual-path trajectory acquisition with the same input, as well as the three-level consistency determination of the operator / anchor point, inter-step latent variables, and final image in this invention. Figure 4 This is a schematic diagram illustrating the relationship between the downstream error propagation coefficient, local tolerance, and repair priority in this invention. Figure 5 This is a schematic diagram of the closed-loop process of default location, accuracy repair, recompilation, and acceptance driven by the execution result of the target device in this invention. Figure 6 This is a schematic diagram of the workpiece selection, lightweight self-inspection, and high-precision rollback process based on device fingerprint and Manifest of the present invention. Figure 7 This is a schematic diagram illustrating the dual-backend compilation, real-machine verification, and artifact packaging of Android QNN / HTP and iOS Core ML, using JuZhou 1.0 as an example. Detailed Implementation
[0022] The technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. 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 are within the scope of protection of the present invention.
[0023] Please see Figures 1 to 7As shown, this invention is a method for cross-backend hybrid precision compilation of edge-side generative models based on trajectory contracts. The overall technical solution of the compilation method includes: receiving the iterative generative model M to be deployed, the target backend set B, the target device capability description F, and the resource envelope R. First, the source model is converted into a normalized computation graph that does not depend on specific backend fusion rules. Trajectory anchor points are set at the step boundaries and key compilable subgraph boundaries; then, fixed calibration test cases are performed using reference accuracy to obtain the reference trajectory and the downstream error amplification coefficients of each anchor point, forming a trajectory consistency contract T. For each target backend b, the system generates a candidate accuracy mapping q, which will... Compile into candidate artifacts This process executes and collects anchor signatures and resource data on the actual target device. This is achieved through source mapping. Align the backend node output to the normalized anchor point, and determine whether the trajectory error, final output error, and resource consumption satisfy T and R. If not, locate the smallest compilable subgraph with the highest default contribution, adjust its accuracy or operator implementation, and recompile. The workpiece and device fingerprints, compilation information, accuracy map, contract version, measurement results, and rollback workpiece relationships are all encapsulated together.
[0024] Definitions of terms and symbols: Normalized computation graph A directed graph obtained from PyTorch, ONNX, or other source models, preserving the mathematical semantics and module boundaries of the model but not depending on the target backend fusion result.
[0025] Backend computation graph : A graph used in QNN / HTP, Core ML, MNN, NNAPI, GPU, or other runtime environments after constant folding, quantization insertion, layout transformation, and operator fusion are performed by the target compiler.
[0026] Source mapping : Backend nodes, fusion cores, or artifact subgraphs to A mapping of one or more normalized nodes; the mapping records the source node set, topological cut edges, tensor shape, and semantic labels.
[0027] Track anchor point : No. Within a generation step or at the step boundary, the first... An observable semantic tensor can be a complete tensor or a statistical signature generated from that tensor.
[0028] Track signature : Structured summaries for low-overhead comparison anchors, which may include channel mean / variance, absolute maximum, quantile, saturation ratio, normalized direction vector or cosine similarity features, fixed random projection or hash; it does not require saving the entire original tensor.
[0029] Trajectory Consistency Contract T: a set of anchor point definitions, reference signatures, step / subgraph error budgets, final output tolerances, deterministic conditions, and resource constraints.
[0030] Precision mapping q: A mapping from a normalized subgraph or the smallest compilable unit of the backend to the numerical types, quantization scales, zeros, granularity, and fusion strategies supported by the target backend.
[0031] Equipment closed loop: Candidate workpieces must run on the real target equipment or a hardware execution environment equivalent to the target equipment, and the equipment measurement results directly drive the next round of accuracy map or compilation strategy updates.
[0032] Normalized computational graph and trajectory anchor point construction: In a preferred embodiment, the system first unfolds the generation process according to the sequence of "conditional encoding—initial latent variables—iterative update from step K to step 1—latent variable decoding—output image". For implementations that iteratively execute the same U-Net, it can be replicated at the logical layer as K call instances with step identifiers, but sharing the same weight references. Each step sets at least input latent variable anchors and output latent variable anchors; sub-image anchors can also be set after temporal / noise embedding, normalization, attention, residual fusion, output convolution, and VAE upsampling at each level.
[0033] Anchor points are not uniquely identified by the source layer name, but rather by a stable identifier composed of module semantics, topological cut edges, input / output shapes, parameter sources, and step numbers. For example, "step=2 / denoiser.mid / post_norm / shape=[1,C,H,W]". This way, even if QNN fuses normalization, activation, and convolution into a single kernel, or Core ML splits the same module into multiple nodes, they can still be aligned to the same anchor point based on the cut edges and the set of source nodes.
[0034] For supplier backends that cannot directly export intermediate tensors, the compilation system can additionally generate probe artifacts solely for verification: adding temporary outputs at the target cut edges, or outputting only the signature after calculating the mean, variance, quantile approximation, and fixed random projection within the graph. The production artifact removes the probes after acceptance, incurring no ongoing debugging costs. If the backend completely disallows additional outputs, the breach subgraph can be located through segmented compilation or by bisecting the probe artifacts.
[0035] Calibration use cases and reference trajectory generation: The calibration use cases consist of a set of prompts or conditions P, a set of random seeds S, a set of output resolutions H, a set of scheduling parameters U, and a set of optional device scenarios D. Each use case must fix the text encoding result, initial random latent variables, step sequence, guiding coefficients, and decoding parameters, so that the reference path and candidate backend paths differ only in numerical implementation and compilation strategy. For Chinese models, short prompts, long prompts, color / quantity / location, classical Chinese poetry, and style descriptions can be covered; these are only used to cover the input distribution and do not constitute language or business limitations in this case.
[0036] The reference path can be an FP32 model executed in a controlled computing environment or a validated FP16 normalized model. The reference execution records the complete tensor or trajectory signature for each anchor point, and also records the final image and ensemble-level semantic / distribution metrics. Candidate paths, on the other hand, must invoke the compiled target backend artifact and run it on the target device. To suppress sporadic measurement noise, the same use case can be executed repeatedly, distinguishing between numerical errors, runtime nondeterminism, and resource jitter.
[0037] Anchor point error, downstream propagation coefficient, and budget allocation:
[0038] Let the reference state and candidate state at step k be respectively and , No. The reference tensor and candidate tensor of each normalized anchor point are respectively and Anchor point error can be expressed as: ; In the formula, This represents a measure of difference in the signature of the mean, variance, quantiles, saturation proportion, or random projection. Configure according to anchor point type. Normalization / activation anchor points that are sensitive to numerical range can improve... Weights, such as direction-sensitive attention outputs, can increase the weights of cosine terms.
[0039] To determine the actual impact of local errors of the same magnitude in different steps, the system applies a small perturbation to the reference anchor point that is similar in shape to the quantization noise. And run its downstream reference subgraph to estimate the error propagation coefficient: ; Even when a complete tensor cannot be injected, estimation can be achieved through finite difference, subgraph-by-subgraph precision switching, or small-scale perturbation of the quantization scale. The system is based on the upper limit of the total trajectory error B and the propagation coefficient. Importance of anchor points Budget allocation for safety lower / upper limits This allows for stricter local tolerances for high-propagation, high-importance anchor points. Budget allocation can be calculated statically or renormalized based on actual default contributions after the initial equipment operation.
[0040]
[0041] Candidate precision map generation and backend compilation: The system will Divided into units where the target backend can have its precision set independently or can be compiled independently. For each cell, the candidate set consists of the weight precision, activation precision, quantization granularity, symmetric / asymmetric scheme, cumulative precision, fusion strategy, and alternative operators actually supported by the target backend. The system must not assume that all backends support the same numerical types; for example, if a backend does not support in-graph INT8 / FP16 mixing, the precision cell can be expanded to a complete subgraph, or an explicit transformation can be inserted at the subgraph boundary and its cost evaluated.
[0042] Initial candidates can start with the backend configuration that has the lowest resource cost, or they can start with high-precision workpieces and gradually reduce their precision. The compiler generates a backend computation graph for each candidate. , workpiece and source mapping Source mapping can be generated jointly by source graph node ID, compiler debugging metadata, fusion mode library, input / output clipping edges, and tensor shape; for backend nodes whose unique source cannot be determined, they are recorded as a normalized set of nodes rather than being forced to be one-to-one.
[0043] The candidate selection problem is a constrained optimization problem that minimizes the cost of device resources under error constraints, and can be expressed as: ; Among them, the resource items are based on actual tests on the target device. If the internal NPU memory of the backend is not visible, the host visible memory, the constant / temporary buffer estimation given by the compiler, the runtime reserved failure information, and the continuous running stability are used together as feasibility judgments. Host process memory errors are not equated with complete NPU memory.
[0044] Alignment of target device trajectory acquisition with source: The candidate artifact runs on the target device according to the calibration use case. The debug artifact outputs anchor tensors or signatures, per-step delays, subgraph delays, host-visible memory, available device buffer information, temperature / power consumption, or continuous operating status. The system verifies the embedded hints, hashes of initial latent variables, and scheduling parameters to ensure complete consistency between the reference path and candidate path inputs.
[0045] Subsequently based on Map back the backend observation points If a fusion core covers multiple normalized nodes, joint anchor points are established at its input / output tangents, and the default contribution is temporarily assigned to the fusion group; if necessary, the fusion is shut down or a finer-grained probe artifact is generated for secondary localization. If multiple backend nodes correspond to the same normalized node, they are compared after layout recovery, inverse quantization, and deterministic linear transformation are completed. Therefore, Android QNN graphs and iOS Core ML graphs can still be evaluated under the same trajectory contract, even if the number and naming of nodes differ.
[0046] Breach of contract sub-map location and equipment closed-loop accuracy repair: If a candidate fails to meet the contract requirements, the system calculates the weighted contribution of each default anchor point. And merged into the backend minimum compilable subgraph through source mapping. For each fix action The system estimates its error reduction amount With the addition of latency / memory / power consumption ,according to Sort by prioritizing actions that offer the highest return per unit cost without disrupting the resource envelope.
[0047] (1) Improve the weight, activation or accumulation precision of the default subgraph to a higher precision supported by the backend; (2) Redetermine the quantization scale, zero point, pruning quantile, channel-by-channel / group-by-group granularity, or use different activation ranges for different steps; (3) Disable operator fusion, fast approximation or layout transformation that cause significant numerical drift, and replace them with verifiable equivalent implementations; (4) Insert explicit quantization / inverse quantization boundaries within the fusion group, or split it into two sub-maps that can be determined to different precisions; (5) For nodes that do not support target precision, use the high-precision path, CPU / GPU path or accepted alternative operator of the target backend. (6) If local repair still fails, the rollback range is gradually expanded until a module-level or full-model high-precision workpiece is used.
[0048] The system recompiles and repairs the candidates and repeats the verification on the same target device until an artifact that simultaneously satisfies the trajectory contract and resource envelope is obtained, or it is determined that no candidate that meets the conditions exists on the device / backend. The latter is not considered a successful compilation, and an "unsupported" status should be output or a conservative rollback artifact that has already passed should be selected.
[0049] Deployment package list, device fingerprints, and artifact identities:
[0050] Each accepted deployment artifact is associated with an inseparable Manifest. The Manifest records at least the model weight hash, normalized graph hash, backend graph / artifact hash, source mapping version, trajectory contract version, precision mapping, quantization parameter summary, compiler and backend version, target SoC / system / ABI compatibility range, calibration set version, measured resource results, acceptance time, rollback artifact ID, and digital signature.
[0051]
[0052] Runtime selection, self-test, and rollback: When the application starts, it collects the device fingerprint F, including the SoC model, operating system and ABI, backend / driver version, capability set, and currently available resources, and selects the most compatible and resource-efficient accepted artifact from the local deployment package. If the fingerprint matches the Manifest exactly, it can be loaded directly; otherwise, if it only falls within the declared compatibility range or a driver / system upgrade is detected, a lightweight self-test is performed first.
[0053] Lightweight self-testing can use pre-defined hint embeddings, fixed random seeds, and low-cost probe steps to compare several key signatures with the tolerances in the Manifest. Self-testing does not require uploading user text, latent variables, or generating images. If successful, the preferred artifact is used; if it fails, it switches to a higher-precision or more conservative artifact, records the failure anchor and device version, and triggers offline recompilation when conditions permit. This mechanism solves the problem of old artifacts being "loadable but no longer satisfying the precision contract" after the backend driver changes the numerical kernel.
[0054] Android Implementation Example: The Android implementation follows the high-level module division of JuZhou 1.0: the text side can be executed by MNN / CPU, and U-Net and VAE are exported from PyTorch as ONNX and then converted into QNN / HTP artifacts. The system establishes device fingerprints and backend capability sets for SM8850, SM8750, SM8475 or other target SoCs, sets normalized anchor points for the four logical steps of U-Net and VAE, and compiles candidate INT8 or mixed-precision artifacts supported by the target backend.
[0055] Each candidate must run a calibration set on the corresponding device. If the output anchor point of a QNN fusion group exceeds the limit, the system can first increase the legal execution accuracy of the fusion group or disable specific fusions; if the QNN does not support the local accuracy, the fusion group is expanded into an independently compileable subgraph, or a module-level rollback artifact is selected. Finally, the ContextBinary, accuracy mapping, and device measurement results are written to the Manifest, and the application dynamically loads them on a SoC basis. The INT8 artifact described in the technical report can be used as the first-round candidate or performance baseline in this case, but it does not mean that the new closed loop of this invention has been implemented in the report.
[0056] iOS Example: The iOS implementation exports CLIP, U-Net, and VAE to ONNX and converts them into a Core ML model package. Verified FP16 artifacts can be used as references or for high-precision backtracking. The system then generates compressed or hybrid precision candidates based on the specific Core ML / device capabilities. The candidate artifacts are then subjected to the same calibration test case on the target iPhone, and the optimized numerical trajectory of the Core ML graph is determined to satisfy the contract through step anchors and source mapping.
[0057] If Core ML only allows a certain level of precision to be applied to specific layers, weights, or computational units, the precision unit must be scaled up to its actual capabilities, without fabricating numerical types that the backend does not support in the claims or embodiments. The approved .mlpackage or compiled .mlmodelc is encapsulated together with the device / system compatibility scope, trajectory acceptance results, and FP16 rollback artifacts.
[0058] End-to-end steps: S1: Obtain the iterative generation model to be deployed, the target backend, the target device capability description, and the resource envelope.
[0059] S2: Convert the source model into a normalized computation graph, expand or label each generation step, and set trajectory anchor points at the step boundaries and key subgraph boundaries.
[0060] S3: Generate deterministic calibration use cases, execute them with reference accuracy, and record the reference trajectory signature, final output, and resource baseline.
[0061] S4: Estimate the downstream error propagation coefficient of each anchor point by perturbation or precision switching, allocate the anchor point error budget, and form a trajectory consistency contract.
[0062] S5: Generate candidate precision mappings based on the target backend capabilities, compile the normalized computation graph into candidate artifacts, and generate source mappings from backend nodes to normalized nodes.
[0063] S6: Execute candidate artifacts on the real target device and collect anchor signatures, final output, and available latency, memory, power consumption, and stability data.
[0064] S7: Calculate anchor point error, trajectory error, final output error, and resource constraint violation based on source mapping.
[0065] S8: If it fails, locate the smallest compilable subgraph with the highest default contribution, adjust the precision, quantization parameters, fusion or operator path and return to S5.
[0066] S9: If successful, encapsulate the workpiece, precision mapping, source mapping, device fingerprint, contract version, acceptance result, rollback relationship, and digital signature into a deployment package.
[0067] S10: Selects workpieces based on device fingerprints at runtime; performs lightweight trajectory self-check when compatibility is uncertain, and loads back the workpiece or triggers recompilation if it fails.
[0068] One specific application of this embodiment is: Step S1: Obtain the input constraint parameters of the compilation task. It accepts four types of inputs as boundary conditions for the entire compilation process, adapting to edge deployment scenarios: The iterative generative model M to be deployed includes, but is not limited to, generative networks with iterative state updates such as diffusion models, flow matching models, and consistency models. Typical structures include conditional encoding modules, iterative denoising modules (such as U-Net and DiT), and decoding modules (such as VAE). It supports arbitrary conditional inputs such as text, images, and multimodal data, and is not bound to a specific model backbone or training algorithm.
[0069] Target backend set B: includes at least one edge-side inference backend, such as QNN / HTP, MNN, NNAPI on the Android side, Core ML on the iOS side, and general edge inference frameworks such as ONNX Runtime and TensorRT.
[0070] Target device capability description F: A set of hardware and system attributes of the edge device, including SoC model, operating system version, ABI architecture, backend / driver version, computing power and memory capabilities, and supported numerical precision and operator set.
[0071] Resource envelope R: The upper limit of resource constraints that the deployment must meet, including thresholds for single-step inference latency, end-to-end inference latency, peak memory usage, energy consumption, and deployment package size.
[0072] Step S2: Construct a normalized computation graph and set anchor points for the step-by-step trajectory. The source model is transformed into a unified semantic intermediate representation independent of the backend fusion rules, establishing a benchmark coordinate system aligned across backends: Generate a normalized computational graph The directed computation graph is converted from source model formats such as PyTorch and ONNX, which fully preserves the mathematical semantics and module boundaries of the model. It does not perform operator fusion, layout transformation and quantization insertion specific to the target backend, and serves as a unified semantic benchmark for all backends.
[0073] Expanding the iterative generation steps: For the generation process of repeatedly calling the same denoising network, it is replicated at the logic layer as follows: Each call instance is identified by a step number, and all instances share the same weighted reference. The total number of noise reduction steps can be configured as 1, 2, 4, 8, 16, 28, etc.
[0074] Set up multi-level trajectory anchor points: Set observable semantic tensors as trajectory anchor points at the step boundaries and key subgraph boundaries of the computation graph. ,in To generate step numbers, Anchor point numbers within the same step: Step-level anchors: Each denoising step must set input latent variable anchors and output latent variable anchors; Subgraph-level anchors: Subgraph anchors can be set after temporal / noise embedding, normalization layers, attention modules, residual fusion, output convolution, and VAE upsampling nodes.
[0075] Anchor point stability identification rules: Anchor points are not uniquely identified by the source layer name. Instead, a unique stable identifier is generated by combining "module semantics + topological trimming + input / output tensor shape + parameter source + step number". For example, step=2 / denoiser.mid / post_norm / shape=[1,C,H,W], to ensure that semantic alignment can still be completed after backend fusion or splitting of operators.
[0076] Probe workpiece reserved design: For supplier backends that cannot directly export intermediate tensors, the probe workpiece generation logic is predefined: a temporary output node is added at the target cutting edge, or the statistical calculation logic is built into the graph to output only the signature; the probe node can be removed after the production workpiece passes acceptance, with no continuous running overhead; if the backend completely prohibits additional output, it supports locating the default area by compiling segment by segment and using binary probe.
[0077] Step S3: Generate deterministic calibration test cases and collect reference trajectories. By fixing the input variables and eliminating irrelevant interference, a baseline trajectory for consistency verification is generated: Constructing a set of calibration test cases: Each calibration test case consists of a set of prompts / conditions. Random seed set Output resolution set Scheduling parameter set Equipment scenario collection Composition; use cases cover short / long texts and different semantic categories to cover the model input distribution.
[0078] Input deterministic constraints: All calibration test cases must fix the text encoding results, initial random latent variables, denoising step sequence, guiding coefficients, and decoding parameters to ensure that the difference between the reference path and the candidate path comes only from the numerical implementation and compilation strategy, and to eliminate errors caused by inconsistency in input.
[0079] Execute the reference path and record the baseline: Execute the normalized model with reference accuracy (FP32 or validated FP16) in a controlled computing environment to obtain the reference trajectory: Record each anchor point Complete tensor or trajectory signature ; Record the final output image and set-level semantic / distribution metrics; Repeatedly execute the same use case to obtain the inherent fluctuation baseline of the reference path.
[0080] Track signature definition: Track signature A low-overhead structured summary of the anchor tensor, containing at least two of the following: channel mean / variance, absolute maximum value, quantile, quantization saturation ratio, normalized direction vector or cosine similarity feature, fixed random projection, and hash digest (for identity verification; if used for similarity comparison, locality-sensitive hashing or quantization feature digest can be used); consistency verification can be achieved without saving the complete original tensor.
[0081] Step S4: Estimate the anchor point error propagation coefficient, allocate the error budget, and form a trajectory contract. Quantify the impact of local errors on the final generated result, allocate error tolerances differently, and form a unified trajectory consistency constraint standard: Anchor point error calculation method: For the first Step 1 Anchor points, candidate tensors With reference tensor error Defined as: ; In the formula, To normalize the root mean square error, Cosine similarity; To statistically measure signature differences, the deviation of the mean, variance, quantiles, saturation ratio, or random projected signatures can be measured. The weighting coefficient is adjusted based on the anchor type: normalized / activation-type anchors are increased. Weights, attention output anchors increase the weights of cosine terms.
[0082] Downstream error propagation coefficient estimation: Inject a small perturbation with a shape similar to quantization noise into each anchor point. Run the downstream reference subgraph, calculate the error change in the final output, and obtain the error propagation coefficient of the anchor point. : ; In the formula, The perceptual error of the final image, It is a numerical stability constant; when a complete tensor cannot be injected, the propagation coefficient can be estimated by finite difference, subgraph precision switching, and small-scale perturbation of the quantization scale.
[0083] Anchor point error budget allocation: based on the upper limit of total trajectory error Propagation coefficient Anchor point importance weight Assign a local error budget to each anchor point This allows for stricter tolerances for anchor points with high dissemination and importance: ; In the formula, This is a truncation function. , These represent the lower and upper limits of the budget, respectively; the budget supports static calculation and can also be normalized based on actual default contributions after the first round of equipment operation.
[0084] Form a trajectory consistency contract T: The contract is a unified standard for compilation and acceptance, which includes: anchor point definition set, reference signature set, error budget for each anchor point, final output tolerance, deterministic execution conditions, and resource constraint threshold.
[0085] Step S5: Generate candidate precision maps, execute backend compilation, and establish source maps. Candidate precision configurations are generated with the goal of minimizing resources, compiled into the target backend artifact, and a traceability relationship is established from the backend nodes to the normalized nodes. Divide the compilation unit into precision units: normalize the computation graph Divide into the smallest unit set whose precision can be set independently for the target backend and which can be compiled independently. If the backend does not support fine-grained mixing precision, then expand the unit granularity to the complete subgraph or module level.
[0086] Construct a candidate precision set: The candidate configuration for each compilation unit includes the weight precision, activation precision, quantization granularity, symmetric / asymmetric quantization scheme, cumulative precision, operator fusion strategy, and alternative operator implementations actually supported by the target backend; it is not assumed that all backends support the same numerical type.
[0087] Constrained Optimization Objective: The candidate accuracy is selected as a constrained optimization problem. The objective function is to minimize the device resource cost while satisfying the trajectory contract and resource envelope. ; Constraints: ; In the formula, For resource item weights, The total trajectory error, For the final image error, This refers to the set of valid precision configurations supported by the target backend.
[0088] Memory values should be used as the first choice based on the actual measured values of the target device. If the internal buffer of the NPU / HTP is not visible, feasibility should be determined by combining the host's visible memory, compiler buffer estimation, runtime allocation failure information, and continuous operation stability to avoid misjudging the actual memory of the device.
[0089] Backend compilation and artifact generation: for each target backend Based on candidate precision mapping Compile the normalized graph into a backend computation graph. With candidate workpieces The compilation process performs backend standard optimizations such as constant folding, quantization insertion, layout transformation, and operator fusion.
[0090] Establish source mapping Generate a mapping relationship between backend nodes / fusion cores and normalized node sets. The mapping basis includes: source graph node ID, compiler debugging metadata, fusion mode library, topology trimming, tensor shape, and step number. If a single backend fusion node corresponds to multiple normalized nodes, it is recorded as a set of normalized nodes, without forcing a one-to-one mapping. If multiple backend nodes correspond to the same normalized node, the corresponding relationship is recorded and alignment logic for layout recovery and dequantization is reserved.
[0091] Step S6: Execute on the target edge device to collect trajectory signatures and resource data. Deploy candidate artifacts to real target edge devices for execution, obtain real execution data, and avoid discrepancies between desktop simulation and actual machine operation: Real-world operating environment requirements: Candidate workpieces must be executed on real edge hardware equivalent to the target device, and cannot be replaced by desktop simulators or pseudo-quantization results; the deterministic calibration test cases of step S3 are reused in the running process.
[0092] Data collection content: Trajectory data: tensors or trajectory signatures for each anchor point, and the final output image; Resource data: latency per step, subgraph-level latency, host-visible memory, available device buffer information, power consumption / temperature, and continuous operation stability; Consistency check: Verify the hash values of the hint embedding, initial latent variables, and scheduling parameters to ensure they are completely consistent with the reference path input.
[0093] Noise suppression: Repeatedly execute the same use case multiple times, distinguish between numerical system errors, runtime nondeterministic fluctuations, and resource jitter, and eliminate occasional interference.
[0094] Step S7: Complete alignment based on source mapping and perform compliance determination. Align the observation data collected from the backend to normalized anchor points, and determine whether the trajectory contract and resource envelope are satisfied from three dimensions: The backend observes the alignment logic of the normalized anchor points: If a single fusion core covers multiple normalized nodes, a joint anchor point is established on its input / output tangent edges, and the default contribution is temporarily assigned to the fusion group; If multiple backend nodes correspond to the same normalized node, error comparison should be performed after layout restoration, dequantization, and determination of linear transformation. The observations from different backends (such as Android QNN and iOS Core ML) are all aligned to the same set of normalized anchor points, achieving unified evaluation across backends.
[0095] Level 3 consistency determination: Anchor point level: Calculate one by one Determine whether the condition is met. ; Trajectory level: Calculate the weighted total trajectory error Determine whether the total error does not exceed the upper limit. At the same time, it verifies whether the error continues to increase with each step; Image-level: Calculate the perceptual distance, structural similarity, and representational cosine similarity of paired images with the same seed, and verify whether the set-level semantic index drift is within the tolerance range.
[0096] Resource constraint determination: Compare measured latency, memory usage, power consumption, package size, and resource envelope. The threshold is used to determine whether the constraint is met.
[0097] Determination of the result branch: If both the trajectory contract and the resource envelope are satisfied, proceed to the encapsulation stage of step S9; if any one of them is violated, proceed to the repair stage of step S8.
[0098] Step S8: Locating the breached subgraph and repairing the closed-loop accuracy, then iteratively recompiling. The smallest compilable unit that contributes the most to the positioning error is selected as the optimal repair action based on the benefit-cost ratio. After recompiling and verification, a closed-loop optimization of the device-in-the-loop is formed: Default contribution calculation and subgraph location: Calculate the weighted contribution of each default anchor point. By mapping the sources of defaults, the default contributions are merged into the smallest compilable subgraph of the backend to locate the core error sources.
[0099] A collection of six types of repair actions: Precision Enhancement: Increase the precision of the weights, activations, or accumulations of the default subgraphs to a higher precision level supported by the backend; Quantization parameter adjustment: recalculate the quantization scale, zero point, and clipping quantization quantization granularity (channel-by-channel / group-by-group), or set independent activation ranges for different steps; Fusion and layout adjustment: Operator fusion, fast approximation, and layout transformation that cause numerical drift are disabled and replaced with verifiable equivalent operators; Subplot splitting: Insert explicit quantization / dequantization boundaries within the fusion group to split it into two subplots with independently adjustable precision; Operator path replacement: For nodes that do not support the target precision, switch to a high-precision backend path, a CPU / GPU fallback path, or an accepted alternative operator; Graded rollback: When local repair is ineffective, the rollback range is gradually expanded until the module level or the entire model of the high-precision workpiece is reached.
[0100] Repair action sorting rules: For each candidate repair action The estimated reduction in error With the cost of new resources Revenue per unit cost Sort in descending order, prioritizing actions that yield the highest returns without exceeding the resource envelope.
[0101] Iterative recompilation and termination conditions: After updating the precision mapping, return to step S5 to recompile and repeat the verification on the same target device; The iteration termination condition is: the workpiece satisfies both the trajectory contract and the resource envelope, or it is determined that there is no feasible configuration for the device / backend, and the conservative rollback workpiece is output.
[0102] Step S9: Package the deployment package and generate a list of workpieces with acceptance records. The accepted artifacts and their full metadata are encapsulated into deployable deliverables, retaining complete traceability and compatibility information: The core components of the deployment package include: target backend artifact, precision mapping file, source mapping file, trajectory contract version file, physical acceptance report, rollback artifact, and digital signature file.
[0103] Manifest core fields: Each artifact is associated with an inseparable manifest metadata list, containing six core fields:
[0104]
[0105] Step S10: Runtime device fingerprint matching, lightweight self-test and dynamic rollback During the operation of edge devices, intelligent selection and safety verification of workpieces are implemented to cope with changes in driver / system versions. When the application starts, it collects the fingerprint of the current device, including SoC model, system version, ABI, backend / driver version, capability set, and available resources. It then matches the accepted artifacts in the local deployment package that are compatible and have the best resource cost. If the fingerprint is accurately matched, it can be loaded directly.
[0106] Probe Retention and Self-Check Mechanism Explanation: It's important to clarify that the debug probes used to output complete intermediate tensors are removed during the acceptance phase to avoid continuous debugging overhead during production inference. However, a separate, lightweight self-check probe artifact is retained in the deployment package, or a signature digest output interface for selected key anchor points is retained in the production artifact for runtime self-checking. This self-check probe does not output a complete tensor; it only outputs a low-overhead trajectory signature (such as channel mean, quantiles, hash digests, etc.) for comparison with the tolerance recorded in the Manifest.
[0107] A lightweight self-test is triggered when the device fingerprint is within the compatibility range or when a backend driver / system upgrade is detected. The self-test process does not upload user text, latent variables, or generate images; it only uses preset calibration data.
[0108] Run the preset hint embedding, fixed random seed and low-cost probe steps, compare the tolerance in the key anchor signature with the Manifest; if the self-check passes, load the preferred workpiece.
[0109] When the self-test fails, it automatically switches to high precision or conservative workpiece rollback and records the failure anchor point and equipment version information; when conditions permit, it triggers offline recompilation to solve the numerical trajectory drift problem caused by driver changes.
[0110] In the description of this specification, references to terms such as "an embodiment," "example," "specific example," etc., indicate that a specific feature, structure, material, or characteristic described in connection with that embodiment or example is included in at least one embodiment or example of the invention. In this specification, illustrative expressions of the above terms do not necessarily refer to the same embodiment or example. Furthermore, the specific features, structures, materials, or characteristics described may be combined in any suitable manner in one or more embodiments or examples.
[0111] The preferred embodiments of the present invention disclosed above are merely illustrative of the invention. These preferred embodiments do not exhaustively describe all details, nor do they limit the invention to the specific implementations described. Clearly, many modifications and variations can be made based on the content of this specification. This specification selects and specifically describes these embodiments to better explain the principles and practical applications of the invention, thereby enabling those skilled in the art to better understand and utilize the invention. The invention is limited only by the claims and their full scope and equivalents.
Claims
1. A method for cross-backend mixed-precision compilation of end-side generative models based on trajectory contracts, characterized in that, The compilation method includes the following steps: Obtain the iterative generation model to be deployed, at least one target backend, a capability description of the target edge device, and the corresponding resource envelope for deployment; The iterative generation model is converted into a normalized computation graph that does not depend on the target backend fusion rules. Each step of the iterative generation is labeled, and trajectory anchor points with stable semantic labels are set at the step boundaries and key subgraph boundaries. A set of calibration test cases with defined input parameters is constructed, and the normalized computation graph is executed with reference accuracy. The reference trajectory signature and final reference output of each trajectory anchor point are collected. The downstream error amplification capability of each trajectory anchor point is estimated, and a differentiated error budget is allocated to each trajectory anchor point based on the total error upper limit to form a trajectory consistency contract. Based on the accuracy and operator capabilities supported by the target backend, candidate accuracy mappings are generated, the normalized computation graph is compiled into candidate artifacts corresponding to the target backend, and a source mapping relationship is established from backend computation nodes to normalized trajectory anchor points. Deploy candidate artifacts to real target edge devices and run calibration test cases to collect real machine trajectory signatures, final output results, and device resource operation data; Based on the source mapping, the actual machine trajectory signature is aligned to the corresponding normalized trajectory anchor point. The anchor point error and the total trajectory error are calculated. It is determined whether the candidate workpiece simultaneously satisfies the trajectory consistency contract and resource envelope constraint. If satisfied, the subsequent steps are performed. If not satisfied, the minimum compilable subgraph with the highest default contribution is located. After adjusting the precision configuration, quantization parameters or compilation strategy, the process is returned to recompile. The accepted candidate artifacts, accuracy mapping, source mapping, device fingerprint information, trajectory contract version, physical acceptance records, and rollback artifact associations are encapsulated into a deployment package specific to the target edge device.
2. The method for cross-backend mixed-precision compilation of end-side generation models based on trajectory contracts according to claim 1, characterized in that, The trajectory anchor points include at least the input latent variable anchor points and output latent variable anchor points of each denoising generation step, and also include at least one subgraph anchor point from temporal noise embedding, normalization layer output, attention module output, residual fusion, output convolution, and decoder upsampling node; the stable semantic identifier of the trajectory anchor points is generated by combining module semantics, topological trimming, input and output tensor shapes, parameter sources, and step numbers, and is not affected by back-end operator fusion or splitting.
3. The method for cross-backend mixed-precision compilation of end-side generation models based on trajectory contracts according to claim 2, characterized in that, The trajectory signature is a structured low-overhead summary of the anchor tensor, which includes at least two of the following: channel mean, channel variance, absolute maximum value, quantile, quantization saturation ratio, normalized direction vector or cosine similarity feature, fixed random projection, and hash digest; the reference trajectory signature and the actual trajectory signature use the same calculation rules.
4. The method for cross-backend mixed-precision compilation of end-side generation models based on trajectory contracts according to claim 3, characterized in that, The estimation of downstream error amplification capability and the allocation of error budget specifically include: injecting a small perturbation similar in shape to quantization noise into the tensor of each reference anchor point; running the downstream reference subgraph corresponding to the anchor point; obtaining the error propagation coefficient of the anchor point based on the degree of error change in the final image; and allocating a local error budget to each anchor point by combining the upper limit of the total trajectory error, the importance weight of the anchor point, and the error propagation coefficient. Anchor points with higher error propagation coefficients are allocated stricter error tolerances, and all budgets are limited to preset safety upper and lower limits.
5. The method for cross-backend mixed-precision compilation of end-side generation models based on trajectory contracts according to claim 4, characterized in that, The anchor point error is obtained by a weighted combination of three types of error terms: the first type is the normalized root mean square error of the anchor point tensor, the second type is the cosine similarity difference of the anchor point tensor, and the third type is the statistical feature difference of the trajectory signature; the weights of the three types of error terms are dynamically adjusted according to the type of anchor point.
6. The method for cross-backend mixed-precision compilation of end-side generation models based on trajectory contracts according to claim 5, characterized in that, The generation of the candidate precision mapping aims to minimize device resource costs, comprehensively considering four resource indicators: inference latency, memory usage, operating energy consumption, and deployment package size. The candidate configuration must simultaneously meet the anchor point error constraint, total trajectory error constraint, final image precision constraint, and device resource envelope constraint, and only the precision and operator configuration actually supported by the target backend are adopted.
7. The method for cross-backend mixed-precision compilation of end-side generation models based on trajectory contracts according to claim 6, characterized in that, The source mapping is generated based on source graph node identifiers, compiler debugging metadata, operator fusion mode library, topological trimming, tensor shape, and step number; a single backend fusion node corresponds to one or more normalized trajectory anchor points, and multiple backend nodes can correspond to the same normalized trajectory anchor point; After locating the defaulted subgraph, repair actions are selected from high to low based on the unit cost benefit, including at least one of the following: improving the subgraph accuracy level, adjusting the quantization scale and granularity, disabling operator fusion that causes numerical drift, splitting the subgraph for independent refinement, replacing the high-precision operator path, and gradually expanding the rollback range.
8. The method for cross-backend mixed-precision compilation of end-side generation models based on trajectory contracts according to claim 7, characterized in that, For target backends that cannot directly export intermediate tensors, compile and generate dedicated verification probe artifacts: add temporary output nodes at the cut edges of the target topology, or embed signature calculation logic within the computation graph to output only the trajectory signature; After acceptance, remove probe nodes from the production workpiece; the production workpiece can remove the complete debug probe, but retain the independent lightweight self-test probe workpiece in the deployment package, or retain the signature output interface of the selected key anchor point in the production workpiece; if the backend completely prohibits additional output, the faulty subgraph is located by compiling segment by segment or by binary probe.
9. The method for cross-backend mixed-precision compilation of end-side generation models based on trajectory contracts according to claim 8, characterized in that, The deployment package includes a manifest file that is bound to each workpiece. The manifest records at least six types of information: identity hash of the model and normalized computation graph, backend and compiler version and driver compatibility range, accuracy configuration and quantization parameter summary, trajectory contract and calibration set version information, target device compatibility range and measured resource results, rollback workpiece identifier and fault handling strategy.
10. The method for cross-backend mixed-precision compilation of end-side generation models based on trajectory contracts according to claim 9, characterized in that, The compilation method further includes runtime artifact selection and self-check rollback steps: when the edge device starts the application, it collects the current device fingerprint and matches the accepted artifacts that are compatible and have the best resource cost in the local deployment package; when a backend driver upgrade, system version change, or device fingerprint is detected that is only within the compatibility range, a lightweight trajectory self-check is performed to compare the key anchor signature with the tolerance range; if the self-check passes, the preferred artifact is loaded; if the self-check fails, it automatically switches to the high-precision rollback artifact; the target backend includes at least one of QNN / HTP, MNN, NNAPI on Android and Core ML on iOS, and the iterative generation model includes a diffusion model, a flow matching model, or a consistency model, and the backbone of its denoising network or velocity prediction network includes U-Net or Diffusion Transformer.
