A legal clause and code consistency verification method and system based on large model semantic vectorization, medium and equipment

By constructing a unified semantic representation space for legal provisions and smart contract code using a large language model, the problem of insufficient cross-modal semantic representation is solved, and automated consistency verification of legal provisions and smart contract code is realized, improving the objectivity and efficiency of verification.

CN121920380BActive Publication Date: 2026-07-31CENTRAL UNIVERSITY OF FINANCE AND ECONOMICS
View PDF 2 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Patents(China)
Current Assignee / Owner
CENTRAL UNIVERSITY OF FINANCE AND ECONOMICS
Filing Date
2026-01-07
Publication Date
2026-07-31

AI Technical Summary

Technical Problem

Existing technologies struggle to achieve stable, computable, and repeatable consistency verification between legal provisions and smart contract code when cross-modal semantic representation capabilities are insufficient, especially in large-scale, complex contract scenarios where the need for automated consistency verification is difficult to meet.

Method used

By using a large language model to construct structured semantic units for legal provisions and smart contract code, and mapping them to a unified shared semantic space through a pre-trained encoder, a same-modal semantic structure preservation loss function is introduced. Combined with instance-level semantic constraints, structural condition alignment and cross-modal contrast consistency loss, semantically consistent provisions and code are automatically moved closer together, while inconsistent provisions and code are automatically moved away.

Benefits of technology

It achieves automated consistency verification of legal provisions and smart contract code in the same semantic space, ensuring the objectivity and repeatability of verification, reducing reliance on human intervention, and improving verification efficiency and accuracy.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN121920380B_ABST
    Figure CN121920380B_ABST
Patent Text Reader

Abstract

This invention relates to a method, system, medium, and device for verifying the consistency of legal provisions and code based on large-scale model semantic vectorization. The method utilizes the semantic understanding and representation capabilities of a large language model to perform structured semantic parsing of legal provisions and smart contract code, constructing semantic units for legal provisions and semantic units for code behavior. These are then mapped to a unified shared semantic space through pre-trained encoders in their respective domains. Within this shared semantic space, a joint alignment objective function is constructed from three levels: instance-level semantic constraints, structural condition alignment, and cross-modal comparison consistency. This ensures that semantically consistent legal provision vectors and code vectors automatically move closer together in the shared semantic space, while semantically inconsistent vectors automatically move further apart. Based on the trained cross-modal semantic vector model, the consistency between the legal provisions and smart contract code is automatically verified by calculating the semantic vector distance between them.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of smart legal contract technology, and in particular to a method, system, medium, and device for verifying the consistency of legal provisions and code based on large-model semantic vectorization. Background Technology

[0002] The transformation of contractual clauses into smart contract code is a crucial foundational technology for achieving digital and intelligent processing of judicial business and enhancing social governance capabilities. However, legal clauses are typically expressed in natural language, characterized by semantic ambiguity, implicit conditions, multi-layered contextual dependencies, and complex structured semantic features. In contrast, smart contract code belongs to a strictly defined formal language, emphasizing grammatical norms, logical structure, and a defined execution path. For a long time, consistency verification between the two has relied primarily on manual comparison or manually written rules for semantic mapping and verification. This approach is not only costly and time-consuming, but the verification results are also highly dependent on human experience, making it difficult to guarantee the objectivity, repeatability, and stability of the verification process. This approach is no longer sufficient to meet the automation and high reliability requirements of large-scale smart contract applications.

[0003] While existing research has attempted to address these issues through various technical approaches, significant limitations remain. One type of method primarily relies on rule matching or static analysis techniques to detect the logical correctness and security of smart contract code. These methods focus on the syntax and execution path analysis at the program level, lacking the ability to understand the semantic connotations of legal provisions, and therefore cannot answer the core consistency question of "whether a specific legal provision has been correctly implemented by the smart contract." Another type of method uses traditional text similarity techniques, such as TF-IDF or Word2Vec, to vectorize legal text. However, these methods struggle to characterize the rights and obligations structure, logical conditional relationships, and event triggering mechanisms inherent in legal semantics, and cannot establish a comparable representation space with the abstract syntax tree, control flow structure, and other program semantics in smart contract code. Furthermore, while formal verification-based approaches can rigorously verify program logic, they typically cannot automatically process legal provisions in natural language form. They often require manual rewriting of legal provisions into formal specifications, resulting in high implementation costs and high professional barriers, making it difficult to support the automated consistency verification needs of large-scale, complex contract scenarios.

[0004] In recent years, large language models have made significant progress in natural language understanding and program code generation, providing new technical possibilities for cross-modal semantic modeling. However, the output of existing large language models is mainly natural language text, lacking stable, computable, and repeatable semantic vectorization representations. Furthermore, existing model systems lack an effective mechanism to uniformly map the semantics of legal provisions and smart contract code to the same representation space, making them difficult to directly apply to consistency verification tasks between legal provisions and code. Therefore, a key technical problem remains to be solved in the existing technology system: how to construct a unified semantic vectorization representation method that can simultaneously characterize the deep semantic features of legal provisions and the semantic features of program code, and support computable and measurable comparisons within the same semantic space. Constrained by the insufficient cross-modal semantic representation capabilities, existing technologies struggle to identify the implementation relationship between legal provisions and corresponding smart contract code in a stable and objective manner, and cannot accurately assess the degree of consistency or deviation between the two at the logical semantic level. Summary of the Invention

[0005] To address the aforementioned challenges, this invention relates to a method, system, medium, and device for verifying the consistency of legal provisions and code based on large-scale model semantic vectorization. This method utilizes the semantic understanding and representation capabilities of a large language model to perform structured semantic parsing of legal provisions and smart contract code, constructing semantic units for legal provisions and semantic units for code behavior. These are then mapped to a unified shared semantic space through pre-trained encoders in their respective domains, enabling legal logic elements and code logic elements to form comparable semantic representations in the vector space. To avoid disrupting the inherent semantic topology of the legal and code modalities during cross-modal alignment, a same-modal semantic structure preservation loss function is introduced during model training to constrain the structural consistency of the same-modal representation space. Simultaneously, a joint alignment objective function is constructed from three levels: instance-level semantic constraints, structural condition alignment, and cross-modal comparison consistency. This ensures that semantically consistent legal provision vectors and code vectors automatically move closer together in the shared semantic space, while semantically inconsistent vectors automatically move away. Based on the trained cross-modal semantic vector model, the consistency between the legal provisions and smart contract code is automatically verified by calculating the semantic vector distance between them.

[0006] To achieve the above objectives, the technical solution adopted by the present invention is as follows:

[0007] A method for verifying the consistency between legal provisions and code based on large-scale model semantic vectorization includes the following steps:

[0008] S1) Data Construction: Collect legal contract text and smart contract code respectively, perform clause-level segmentation on the legal contract text to construct legal clause semantic units, and perform behavior-level parsing on the smart contract code to construct code behavior semantic units;

[0009] S2) Semantic encoding: After templated serialization and context expansion, the legal text semantic units and code behavior semantic units are respectively input into the legal domain pre-trained encoder and the code domain pre-trained encoder to obtain the corresponding legal text vector and code vector.

[0010] S3) Shared semantic space mapping: Through their respective trainable linear projection layers, the legal text vectors and code vectors are mapped to a unified shared semantic space, and a homomodal structure semantic preservation loss is introduced during the mapping process to constrain the structural consistency of the homomodal embedding space.

[0011] S4) Cross-modal consistency alignment: Within the shared semantic space, instance-level alignment loss, structural condition alignment loss, and cross-modal contrastive consistency loss are jointly used for training, so that the semantically corresponding legal provision vectors and code vectors are close to each other in the embedding space, and the non-semantically corresponding vectors are far apart, thereby obtaining a consistent aligned cross-modal semantic vector model.

[0012] S5) Consistency verification: Using the trained cross-modal semantic vector model, calculate the cosine similarity between the newly input legal text and the smart contract code fragment in the shared semantic space, and output the consistency verification conclusion between the legal text and the code based on the similarity result.

[0013] Furthermore, step S1) data construction specifically includes:

[0014] S1.1) Collect different types of legal contract texts, and perform noise reduction, format standardization and text correction on the legal contract texts to form a standardized set of contract texts;

[0015] S1.2) Using a large language model fine-tuned from legal corpus, standardized contract texts are parsed at the clause level to automatically identify the clause category, key semantic elements, and logical dependencies within and between clauses, thereby generating structured legal clause semantic units.

[0016] S1.3) Collect smart contract code, and perform formatting, syntax repair, dependency completion and comment cleaning on the smart contract code to form a standardized code set;

[0017] S1.4) The standardized code is used to generate corresponding bytecode using the code compiler solc, and then a control flow graph (CFG) and a data flow graph (DFG) are constructed to generate semantic units of code behavior used to characterize the code branch structure, function call relationship and state transition process.

[0018] Further, the templated serialization in step S2) semantic encoding includes:

[0019] S2.1) For each legal provision semantic unit, generate a corresponding readable token sequence according to the predefined unified field template A. The field template A includes at least one or more of the following: provision type, subject of rights and obligations, action, applicable conditions, triggering event, time constraint, and exception provision.

[0020] S2.2) For each code behavior semantic unit, generate a corresponding readable token sequence according to the predefined unified field template B. The field template B includes at least one or more of the following: control flow mode, state operation set, event trigger flag, role permission check, asset transfer flag, and time constraint judgment.

[0021] Further, the context extension in step S2) semantic encoding includes:

[0022] When semantically encoding legal provisions or codes, the target text is concatenated with its preceding and following contexts to construct an extended input sequence. Distinguishing segment tokens are introduced during the word segmentation process to explicitly distinguish text fragments from different sources or with different semantic roles, thereby enhancing the encoder's ability to model contextual semantic dependencies.

[0023] Furthermore, the semantic preservation loss of the same modality structure in the shared semantic space mapping in step S3) is obtained in the following way:

[0024] For the legal modality, a structured label vector corresponding to the legal provision vector is generated, and the structural semantic distance between legal provisions is calculated based on the structured label vector, thereby constructing a Top-K structural semantic neighborhood for each legal provision;

[0025] For code modalities, generate behavior pattern label vectors corresponding to code vectors, and calculate the behavior pattern distance between codes based on these behavior pattern label vectors, thereby constructing a Top-K semantic neighborhood for each code segment;

[0026] The aforementioned neighborhood information is used to construct a weighted adjacency matrix, and a weighted summation of the squared vector distances within the neighborhood is introduced as a loss for preserving the semantic structure of the same modality, in order to constrain the structural semantic consistency within the same modality.

[0027] Furthermore, the loss function for joint training in step S4) cross-modal consistency alignment is:

[0028]

[0029] in, For the Euclidean distance loss of pairwise legal-code samples, The loss is calculated using the Euclidean distance between the legal text vector and the code vector. For the contrast consistency loss based on InfoNCE (Information Noise-Contrastive Estimation), , , These are adjustable weighting coefficients.

[0030] Furthermore, in step S5) consistency verification, the consistency verification conclusion includes a consistency score and / or modification suggestions; the consistency score is a numerical result calculated based on cosine similarity, and the modification suggestions include prompts indicating semantic inconsistencies in legal provisions or smart contract code.

[0031] Specifically, for example, it could be: setting multiple thresholds, outputting "consistent" when the cosine similarity is higher than the first threshold; outputting "inconsistent" and providing the missing legal elements or code behavior patterns when it is lower than the second threshold; and outputting "awaiting manual review" and listing the K most similar clauses or code snippets for reference when it is between the two thresholds.

[0032] This invention also provides a legal text and code consistency verification system based on large-model semantic vectorization, comprising:

[0033] The text acquisition module is used to acquire legal contract texts and smart contract code;

[0034] The semantic parsing module is used to perform structured semantic parsing on the legal contract text and smart contract code, and extract semantic units of legal provisions and semantic units of code behavior.

[0035] The vectorization encoding module is used to perform semantic encoding on the legal text semantic units and code behavior semantic units based on a pre-trained large language model, generating legal text vectors and code vectors;

[0036] The mapping module is used to map the legal text vectors and code vectors to a unified cross-modal shared semantic space through a trainable mapping relationship;

[0037] The alignment module is used to make the semantically corresponding legal provision vectors and code vectors approximate each other in the cross-modal shared semantic space, and to make the non-semantically corresponding vectors move away from each other.

[0038] The training module is used to jointly train based on instance-level alignment loss, structural conditional alignment loss, and cross-modal contrastive consistency loss to obtain a consistent aligned cross-modal semantic vector model.

[0039] The verification module is used to calculate the similarity between the newly input legal provisions and the smart contract code fragments using the cross-modal semantic vector model, and output a consistency verification conclusion.

[0040] The present invention also provides a computer-readable storage medium having a computer program stored thereon, wherein the program, when executed by a processor, implements the above-described method for verifying the consistency of legal provisions and code based on large model semantic vectorization.

[0041] The present invention also provides an electronic device, including a memory, a processor, and a computer program stored in the memory and executable on the processor, wherein the processor executes the program to implement the above-described method for verifying the consistency of legal provisions and code based on large model semantic vectorization.

[0042] Beneficial effects:

[0043] This invention utilizes a large model to construct structured semantic units for legal provisions and smart contract code, and then uses a large model encoder to map them to the same shared semantic space, enabling legal logic elements and code logic elements to form comparable semantic representations in the vector space. Subsequently, to ensure that the inherent semantic topology of each modality is not destroyed during cross-modal alignment, a same-modal semantic preservation loss function is introduced into the training objective. Furthermore, alignment objective functions are set based on instance-level semantic constraints, structural condition alignment, and cross-modal contrastive consistency loss, automatically bringing semantically consistent provisions and code closer together and automatically distancing inconsistent provisions and code, thereby achieving automatic consistency verification based on semantic vector distance. In other words, the role of the large model in this invention is to transform "legal language" and "programming language" into computable semantic vectors and determine whether they match in a unified space, achieving automated consistency checking without labeled samples. Attached Figure Description

[0044] Figure 1 This is a diagram illustrating the working principle and flowchart of an embodiment of the present invention;

[0045] Figure 2 This is an example diagram illustrating templated and serialized processes according to an embodiment of the present invention;

[0046] Figure 3This is a schematic diagram of the electronic device structure according to an embodiment of the present invention. Detailed Implementation

[0047] Embodiments of the present invention are described in detail below. Examples of these embodiments are illustrated in the accompanying drawings, wherein the same or similar reference numerals denote the same or similar elements or elements having the same or similar functions throughout. The embodiments described below with reference to the accompanying drawings are exemplary and intended to explain the present invention, and should not be construed as limiting the present invention.

[0048] The technical terms used in the following embodiments are explained as follows:

[0049] Semantic vectorization: Semantic vectorization refers to the technical process of mapping input text content or program code fragments into numerical vectors with fixed dimensions. In this process, the model captures the semantic relationships, contextual dependencies, logical structures, and functional behaviors inherent in the text or code through an internal semantic attention mechanism, and compresses them into computable and comparable high-dimensional vectors. The semantic vectorization used in this invention is applicable not only to legal provisions but also to structured program code. In this way, both legal provisions and code can be transformed into measurable data of a unified dimension, allowing the semantic relevance between them to be mathematically processed through vector distance, similarity calculation, or spatial transformation, providing a foundation for consistency verification.

[0050] Cross-modal semantic space: A cross-modal semantic space refers to a unified representation space used to accommodate semantic vector representations corresponding to different modalities (such as natural language and program code), enabling them to be compared and computed in the same space. In this space, regardless of whether the input data originally belongs to text, code, structured rule descriptions, or legal provisions, it is mapped to a vector representation with consistent metric attributes, allowing the system to analyze the semantic relationships between them using the same distance function, similarity function, or clustering method. This invention maps the semantic vectors of legal provisions and program code to the same cross-modal space through pre-trained models, contrastive learning, or spatial alignment algorithms, thus providing a technical foundation for semantic consistency computation of "provisional-code". This space is the core carrier for the cross-modal semantic alignment and automated consistency verification of the present invention.

[0051] Consistency verification refers to the process of determining whether the semantic content of a legal provision has been correctly and completely implemented in the target program code based on semantic relationships in a vector space. In this invention, consistency verification includes: calculating the distance between the semantic vector of the legal provision and the semantic vector of the code, determining the correspondence between the provision and the code, identifying parts of the code that may not be implemented or deviate from the requirements of the provision, and outputting a consistency score.

[0052] The embodiments of the present invention will now be described in detail with reference to the accompanying drawings.

[0053] Figure 1 This is a schematic diagram illustrating the working principle and process of this embodiment, as follows: Figure 1 As shown, the method for verifying the consistency between legal provisions and code based on large-model semantic vectorization in this embodiment specifically includes:

[0054] S1: Collect various types of legal contracts and smart contract code and construct semantic unitized representations to form embedded data of legal semantics and smart contract behavioral semantics that can be used for cross-modal alignment. This step aims to construct clause-level semantic units with legal semantic structure features and code logic behavioral semantic units from real contract texts, laying the foundation for subsequent cross-modal alignment.

[0055] Specifically, this step is handled by the text acquisition module and the semantic parsing module, and includes the following steps:

[0056] S1.1: Collect various types of contract texts through multiple channels, including legal databases, public regulatory platforms, open-source legal project libraries, and enterprise contract repositories. These include, but are not limited to, service agreements, procurement contracts, equity agreements, distribution agreements, and confidentiality agreements, to cover a wide range of legal clauses and business logic. The collected texts undergo noise reduction, format standardization, and text correction to form a standardized set of directly parsable contract texts.

[0057] S1.2: For standardized contract texts, a large language model (such as Legal-BERT) fine-tuned with a legal corpus is used to perform clause-level parsing of the contract clauses. The large model can automatically identify clause categories (obligation clauses, right clauses, conditional trigger clauses, restrictive clauses, etc.), key semantic elements (subject, action, condition, triggering event, temporal constraint, exception clauses, etc.), and logical dependencies within and between clauses, generating structured clause semantic units. Each clause semantic unit retains the original clause text and necessary contextual information to ensure the integrity of the clause semantics during subsequent encoding.

[0058] S1.3: To construct another modality that corresponds to the legal provisions, this step collects structured smart contract code from multiple sources, including open-source repositories such as GitHub and Etherscan. The collected code types cover ERC series standards, governance contracts, escrow contracts, payment settlement contracts, etc., and a standardized code set is obtained through formatting, syntax fixing, dependency completion, and comment cleaning.

[0059] S1.4: The collected smart contract source code is used to generate corresponding bytecode using the compiler solc, and CFG and DFG are constructed based on the contract abstract syntax tree to characterize the if / else branch structure, function jumps and call relationships, and the internal state transition process of the contract. This modeling method can accurately represent the behavioral semantics of smart contract code and is a key basis for determining its consistency with the structure of obligations, rights, and conditions in legal provisions.

[0060] After step S1 is completed, an independent and structured set of legal provision semantic vectors is generated, providing stable and semantically rich input for subsequent steps of legal provision and code consistency verification.

[0061] S2: The structural semantic units of the legal provisions and smart contract code generated in S1 are further structured and encoded into high-dimensional vector representations that can be used for cross-modal alignment, thereby achieving consistency comparison of legal provisions and code semantics without relying on text and code alignment samples.

[0062] Specifically, this step is handled by the vectorization coding module and includes the following steps:

[0063] S2.1 templates and serializes the fields of legal provisions and smart contract code. For each semantic unit of the provision, key fields are serialized into a model input string according to a unified template to obtain consistent encoding on a general large language model. Figure 2 These are examples of templated and serialized legal provisions and smart contract fragments, where (a) is an example of legal provision serialization and (b) is an example of smart contract fragment serialization.

[0064] The advantages of using templates are twofold: firstly, they explicitly convert the structural information of the text into readable tokens, enhancing the model's sensitivity to structured semantics; secondly, they ensure consistency in the input format across different texts, facilitating the model's learning of the mapping rule of "same structure → similar semantics." In implementation, the templates are automatically generated by the parser, and both the original text fragment and the templated text are stored in JSON, facilitating auditability.

[0065] S2.2 To reduce semantic loss caused by short texts, this step involves encoding a certain clause. Construct extended input And in the tokenizer stage, segment tokens are added to the preceding and following contexts and the target text, for example... , , In this way, Transformer's self-attention can explicitly capture the interaction between tokens within a clause and context tokens, thus incorporating cross-clause logical information into the vector. Similarly, to reduce semantic loss in short function texts, segment tokens are added to smart contract code units during the tokenizer stage.

[0066] S2.3 Expand the input sequence The data is fed into the LegalBERT pre-trained encoder to obtain a token-level output representation matrix. .in This represents the number of tokens in the input sequence. This represents the vector dimension of each token output by the encoder. Each line This corresponds to the semantic embedding representation of the respective token. Similarly, by inputting the smart contract code into the code-domain pre-trained encoder CodeBERT, the token-level output representation matrix of the code is obtained.

[0067] Specifically, mean-pooling is performed on the token subsequence corresponding to the target legal provision in the encoder output to obtain a provision-level semantic representation. Average pooling is a representation learning method that compresses several token vectors into a single text vector. In large model processing, text is split into multiple tokens and each generates a vector representation. This embodiment uses the vector of the entire text, rather than the vector of each token, for alignment between legal text and smart contract code. Therefore, this embodiment needs to compress multiple tokens into a single vector. Considering that the semantic elements of legal text (such as subjects, rights, obligations, conditions, time limits, and actions) are usually distributed throughout the sentence and their semantic contributions are relatively balanced, max-pooling might only retain a small number of extreme features, thus ignoring the structural information of the text. Furthermore, without supervised training for text-level semantics, directly using CLS tokens is unlikely to reliably capture the complete semantics of the text. Based on these considerations, this embodiment uses average pooling to ensure that all kinds of legal semantic elements in the text can be fully encoded into the final text vector representation.

[0068] S3: Align legal provisions and smart contract code in a unified cross-modal semantic space to achieve automated detection and verification of consistency between contract provisions and code implementation.

[0069] Specifically, this step is handled by the mapping module and the alignment module, and includes the following steps:

[0070] S3.1: The vector set of legal provisions obtained in step S2 With code vectors Each projection layer maps to the shared space.

[0071] Specifically, + , + .in and It is a linear mapping function that represents mapping the legal text vector and the smart contract code vector to a shared semantic space. They are essentially two fully connected layers but independent of each other. Linear projection is chosen because it does not destroy the relative semantic structure of the encoder output and allows large models to learn "rotation + translation", thereby making the vectors of the two modalities alignable. , These are projection matrices representing the legal text modality and the smart contract code modality, respectively. and It is a bias term used to control the translation of legal provisions and code projection results in the shared space.

[0072] S3.2: After performing the transformation of the projection layer, L2 normalization is applied to the legal text vector. and smart contract code vectors By performing unitization processing, only directional information is retained, thus making cosine similarity a true semantic similarity indicator.

[0073] Specifically, the formula for L2 normalization is: , ,in and The L2 norm of a vector represents the length of the vector in d-dimensional space.

[0074] S3.3: Then, a semantic preservation mechanism within the same modality is introduced to ensure that the semantic proximity relationship within the legal provision modality and the semantic topology within the code modality remain locally consistent after projection, thereby avoiding the semantic collapse problem caused by cross-modal alignment.

[0075] Specifically, this method utilizes LLM to generate semantic label graphs from legal provisions. For example, for a certain provision... The large model can output the text type, subject, action, time condition, and triggering event, and then obtain a structured representation. Then, the semantic distance is calculated based on the structural tags. ,in, The `type` parameter indicates the type of the provision. If provisions belong to the same `type`, they are given a positive reward. In legal logic, obligations should be more similar to each other and should not be mixed with rights. In the formula, "action" represents the legal act in the clause, including major legal acts such as delivery, payment, notification, and termination. "Condition" represents the triggering condition of the legal clause, such as "within 7 days," "upon delivery," and "after notification." As weight, Let be the similarity function of dimension t. This represents the availability mask for the t-th dimension, set to 0 if that dimension is missing; then, the structural semantics are constructed. ,in This means that for the i-th clause, the K closest clauses are found based on structural semantic distance, serving as its positive sample neighborhood in the same modality. This is equivalent to constructing a semantic graph of the legal clauses using structural semantic distance, with each node having K structural neighbors. Unlike the commonly used KNN algorithm, which guarantees local consistency but ignores implicit logical relationships, this method utilizes the semantic understanding capabilities of a large model to perform structured analysis of the clauses, rather than relying solely on literal vector distance.

[0076] Similarly, at the code modality level, a combination of large-scale modeling and static analysis is used to generate behavioral pattern labels for each code segment, thus making the semantic structure and behavioral patterns of the code explicit. Based on these labels and corresponding behavioral vectors, behavioral pattern distance is defined. Then, based on this, a semantic neighborhood is constructed for each smart contract code fragment. Specifically, for any code snippet denoted by index j, its behavioral semantics are represented as a structured label vector. .in Represents the control flow pattern, used to describe the structural skeleton of the code. Its value is a closed enumeration type, including sequential execution (Seq), conditional judgment + branch (if_then), conditional judgment + double branch (if_then_else), etc. Describes the set of state operations for a code segment, for example , , Equivalent; The value can be 0 or 1, and it is the event trigger flag; Permission checks for the representative role; This indicates whether there has been an asset transfer or payment processing; the value is 0 or 1. This indicates whether block time, expiration time, and lock-up period are involved. Then, the specific function for the behavior pattern is defined. ,in A set representing behavioral dimensions. Let represent the similarity function in the t-th dimension; a larger value indicates greater similarity. This represents the availability mask for the t-th dimension; if this dimension is missing, it is set to 0. Represent the weight of the t-th dimension; then construct the neighborhood. .

[0077] S3.4: To ensure that the inherent semantic topology of each modality is not destroyed during cross-modal alignment, this embodiment introduces a same-modal semantic preservation loss function in the training objective. First, for any modality (legal text or smart contract code), an adjacency weight matrix is ​​defined. , , The structural semantic distance defined in step S3.3, This represents the temperature coefficient, controlling the rate of decay. If j does not belong to the structural semantic neighborhood of i, the adjacency weight is 0, meaning no semantic preservation constraint is generated. Secondly, for... Normalization processing Finally, the following loss function is introduced: ,in For modal primitives, z is the weighted sum of the two ends of the vector mapped to the shared space: , and These parameters are set based on the data size and semantic complexity on both sides.

[0078] S3.5: After completing the structural semantic preservation within the legal modality and the code modality, this embodiment sets the alignment objective function from instance-level semantic constraints, structural condition alignment and cross-modal contrast consistency loss, so that legal provisions can be accurately mapped to smart contract code fragments that implement the logic of the provisions in the semantic space.

[0079] First, for each legal provision vector obtained by the encoder... Its corresponding code snippet vector This approach uses instance-level semantic constraints to make paired samples appear close in the vector space. The correspondence here does not refer to a deterministic pairing relationship established by manual annotation, but rather to a comparable semantic representation automatically formed after the two samples have been processed by a legal text encoder and a code snippet encoder, respectively, under the constraint of preserving structural semantics within their respective modalities. The specific loss is defined as Euclidean distance. Where N is the number of paired samples, the meaning of this loss is that if a certain legal provision Corresponding code implementation If so, its vector representation must remain consistent in the semantic space; otherwise, it will be pulled closer by this loss.

[0080] Secondly, structural condition alignment is introduced, based on the legal provision structural semantic vector obtained in step S3.3. and code behavior semantic vectors Establish structural consistency loss This means that if a legal provision stipulates that "action Y shall be performed when condition X is met", the corresponding code must have control flow, condition checks and state operations that match its type; otherwise, differences in structural dimensions will result in significant penalties.

[0081] Finally, to further enhance the robustness of cross-modal alignment, this method employs cross-modal contrastive consistency loss, utilizing the InfoNCE mechanism to apply strong alignment to positive samples and strong separation constraints to negative samples. InfoNCE is a standard contrastive loss design mechanism. Its core idea is to achieve structured proximity and separation in the semantic space by maximizing the similarity between a query vector and its corresponding positive sample vector, and minimizing its similarity with all negative sample vectors, given a query vector. Through this mechanism, the model can automatically align legal text vectors with their semantically closest code vectors without strict manual pairing, while effectively suppressing confusion between different semantic categories. For legal texts... Corresponding code Define the similarity of positive samples However, for those that do not belong to the same pair of combinations Define the similarity of negative samples. Based on this, the contrastive loss function is defined as follows: , where T is a temperature parameter used to adjust the sharpness of the distribution, meaning that correct legal-code pairs are made as close as possible in the shared space, while incorrect combinations are kept significantly separated in terms of similarity, thereby improving the discriminative ability of consistency verification.

[0082] In summary, this method integrates the three cross-modal losses into a comprehensive consistency alignment objective function: ,in , , is a weighting coefficient used to balance the importance of instance alignment, structure alignment, and contrastive learning.

[0083] S4: Set the corresponding parameters and begin cross-modal comparative learning training of the model's legal provisions and smart contract code.

[0084] Specifically, this step is handled by the training module and includes the following steps:

[0085] S4.1 uses the preprocessed legal text sample set and the smart contract code fragment sample set as inputs to the two modalities, respectively. In each training iteration, one batch is drawn from each modality, and the batch sizes of the two modalities are kept consistent to ensure stable calculation of the cross-modal alignment loss.

[0086] The forward propagation of the S4.2 dual encoders involves inputting the legal provisions within the batch into the legal encoder to obtain the semantic representation of the provisions, and inputting the smart contract code into the code encoder to obtain the semantic representation of the code. Subsequently, both types of representations are mapped to a unified shared semantic space through their respective projection layers and then normalized.

[0087] S4.3 Based on the contrast loss function set in step S3.5, set the weight parameters to form the total loss value, which is used to guide the optimization direction of the model parameters.

[0088] S4.4 Based on the total loss function calculated in step S4.3 Gradient backpropagation is performed on the learnable parameters of the legal encoder, code encoder, and projection layer to calculate the gradient of each parameter. ,in This represents all trainable parameters in the model, including the Transformer encoder weights and the weights of the cross-modal projection layer. To ensure the stability and convergence of the cross-modal vector space alignment, this method preferentially adopts an adaptive gradient optimization algorithm (such as Adam). This algorithm dynamically adjusts the learning rate based on the first and second moments of the gradients of each parameter in each iteration, thus ensuring the effectiveness and numerical stability of gradient updates even when there are significant semantic differences between legal provisions and smart contract code.

[0089] Specifically, for each parameter update, the system calculates according to the following formula. ,in This represents the parameter value in the t-th iteration. The initial global learning rate, and These are the deviation correction values ​​for the first and second moments of the gradient, respectively. To avoid smoothing terms involving division by zero, this method uses an update rule to ensure that the legal text vector and the smart contract code vector continuously approach the correspondence of positive samples in the shared semantic space, while moving away from negative samples, thereby achieving consistent alignment of cross-modal semantics.

[0090] S4.5: Continue iterating the above steps until the model converges, resulting in a semantic vectorized model that aligns the legal provisions with the smart contract code.

[0091] S5: After completing the construction of the cross-modal semantic vector space and model training, the shared semantic vectors generated by the large model, combined with the multi-level semantic judgment mechanism, enable automatic consistency judgment between the text and the code logic.

[0092] Specifically, this step is handled by the verification module and includes the following steps:

[0093] S5.1: After the model has been trained and deployed, when new legal provisions or new smart contract code snippets are input, the similarity between the two in the semantic space is measured based on vector cosine similarity.

[0094] S5.2: Output a consistency score and necessary modification suggestions for scenarios such as compliance checks and smart contract development process integration. Specifically, for example, it could be: setting multiple thresholds, outputting "consistent" when the cosine similarity is higher than the first threshold; outputting "inconsistent" when it is lower than the second threshold and providing missing legal elements or code behavior patterns; and outputting "awaiting manual review" when it is between the two thresholds and listing the K most similar clauses or code snippets for reference.

[0095] Figure 3 This is a schematic diagram of an electronic device provided in an embodiment of the present invention. The electronic device may include:

[0096] The memory 301, the processor 302, and the computer program stored on the memory 301 and capable of running on the processor 302.

[0097] When the processor 302 executes the program, it implements the legal provisions and code consistency verification method based on large model semantic vectorization provided in the above embodiments.

[0098] Furthermore, electronic devices also include:

[0099] Communication interface 303 is used for communication between memory 301 and processor 302.

[0100] The memory 301 is used to store computer programs that can run on the processor 302.

[0101] The memory 301 may include high-speed RAM (Random Access Memory) memory, and may also include non-volatile memory, such as at least one disk storage.

[0102] If the memory 301, processor 302, and communication interface 303 are implemented independently, then the communication interface 303, memory 301, and processor 302 can be interconnected via a bus to complete communication between them. The bus can be an ISA (Industry Standard Architecture) bus, a PCI (Peripheral Component Interconnect) bus, or an EISA (Extended Industry Standard Architecture) bus, etc. The bus can be divided into address bus, data bus, control bus, etc. For ease of representation, Figure 3 The bus is represented by a single thick line, but this does not mean that there is only one bus or one type of bus.

[0103] Optionally, in a specific implementation, if the memory 301, processor 302, and communication interface 303 are integrated on a single chip, then the memory 301, processor 302, and communication interface 303 can communicate with each other through an internal interface.

[0104] Processor 302 may be a CPU (Central Processing Unit), an ASIC (Application Specific Integrated Circuit), or one or more integrated circuits configured to implement embodiments of the present invention.

[0105] It should be understood that various parts of the present invention can be implemented in hardware, software, firmware, or a combination thereof. In the above embodiments, steps or methods can be implemented in software or firmware stored in memory and executed by a suitable instruction execution system. For example, if implemented in hardware, as in another embodiment, it can be implemented using any of the following techniques known in the art, or a combination thereof: discrete logic circuits having logic gates for implementing logical functions on data signals, application-specific integrated circuits (ASICs) having suitable combinational logic gates, programmable gate arrays (FPGAs), field-programmable gate arrays (FPGAs), etc.

[0106] Those skilled in the art will understand that all or part of the steps of the methods implementing the above embodiments can be implemented by a program instructing related hardware. The program can be stored in a computer-readable storage medium, and when executed, the program includes one or a combination of the steps of the method embodiments.

[0107] Although embodiments of the present invention have been shown and described above, it is understood that the above embodiments are exemplary and should not be construed as limiting the present invention. Those skilled in the art can make changes, modifications, substitutions and variations to the above embodiments within the scope of the present invention.

Claims

1. A legal clause and code consistency verification method based on large model semantic vectorization, characterized in that, Includes the following steps: S1) Data Construction: Collect legal contract text and smart contract code respectively, perform clause-level segmentation on the legal contract text to construct legal clause semantic units, and perform behavior-level parsing on the smart contract code to construct code behavior semantic units; S2) Semantic encoding: After templated serialization and context expansion, the legal text semantic units and code behavior semantic units are respectively input into the legal domain pre-trained encoder and the code domain pre-trained encoder to obtain the corresponding legal text vector and code vector. S3) Shared semantic space mapping: Through their respective trainable linear projection layers, the legal text vectors and code vectors are mapped to a unified shared semantic space, and a homomodal structure semantic preservation loss is introduced during the mapping process to constrain the structural consistency of the homomodal embedding space. S4) Cross-modal consistency alignment: Within the shared semantic space, instance-level alignment loss, structural condition alignment loss, and cross-modal contrastive consistency loss are jointly used for training, so that the semantically corresponding legal provision vectors and code vectors are close to each other in the embedding space, and the non-semantically corresponding vectors are far apart, thereby obtaining a consistent aligned cross-modal semantic vector model. S5) Consistency verification: Using the trained cross-modal semantic vector model, calculate the cosine similarity between the newly input legal text and the smart contract code fragment in the shared semantic space, and output the consistency verification conclusion between the legal text and the code based on the similarity result.

2. The method of claim 1, wherein, Step S1) Data construction specifically includes: S1.1) Collect different types of legal contract texts, and perform noise reduction, format standardization and text correction on the legal contract texts to form a standardized set of contract texts; S1.2) Using a large language model fine-tuned from legal corpus, standardized contract texts are parsed at the clause level to automatically identify the clause category, key semantic elements, and logical dependencies within and between clauses, thereby generating structured legal clause semantic units. S1.3) Collect smart contract code, and perform formatting, syntax repair, dependency completion and comment cleaning on the smart contract code to form a standardized code set; S1.4) The standardized code is used to generate corresponding bytecode using the code compiler solc, and then control flow graphs and data flow graphs are constructed to generate code behavior semantic units that characterize code branching structure, function call relationships and state transition processes.

3. The method of claim 1, wherein, Step S2) Templated serialization in semantic encoding includes: S2.1) For each legal provision semantic unit, generate a corresponding readable token sequence according to the predefined unified field template A. The field template A includes at least one or more of the following: provision type, subject of rights and obligations, action, applicable conditions, triggering event, time constraint, and exception provision. S2.2) For each code behavior semantic unit, generate a corresponding readable token sequence according to the predefined unified field template B. The field template B includes at least one or more of the following: control flow mode, state operation set, event trigger flag, role permission check, asset transfer flag, and time constraint judgment.

4. The method of claim 1, wherein, Step S2) Context extension in semantic encoding includes: When semantically encoding legal provisions or codes, the target text is concatenated with its preceding and following contexts to construct an extended input sequence. Distinguishing segment tags are introduced during the word segmentation stage to explicitly distinguish text fragments from different sources or with different semantic roles, thereby enhancing the encoder's ability to model contextual semantic dependencies.

5. The method of claim 1, wherein, Step S3) The semantic preservation loss of the same modality structure in the shared semantic space mapping is obtained in the following way: For the legal modality, a structured label vector corresponding to the legal provision vector is generated, and the structural semantic distance between legal provisions is calculated based on the structured label vector, thereby constructing a Top-K structural semantic neighborhood for each legal provision; For code modalities, generate behavior pattern label vectors corresponding to code vectors, and calculate the behavior pattern distance between codes based on these behavior pattern label vectors, thereby constructing a Top-K semantic neighborhood for each code segment; The aforementioned neighborhood information is used to construct a weighted adjacency matrix, and a weighted summation of the squared vector distances within the neighborhood is introduced as a loss for preserving the semantic structure of the same modality, in order to constrain the structural semantic consistency within the same modality.

6. The method of claim 1, wherein, Step S4) The loss function for joint training in cross-modal consistency alignment is: where, is the Euclidean distance loss for law-code pair samples, is the Euclidean distance loss for law-code pair samples, is the InfoNCE-based contrastive consistency loss, , , is the adjustable weight coefficient.

7. The method of claim 1, wherein, In step S5) consistency verification, the consistency verification conclusion includes a consistency score and / or modification suggestions; the consistency score is a numerical result calculated based on cosine similarity, and the modification suggestions include prompts for semantically inconsistent locations in legal provisions or smart contract code.

8. A system for verifying the consistency between legal provisions and code based on large-scale model semantic vectorization, characterized in that, include: The text acquisition module is used to acquire legal contract texts and smart contract code; The semantic parsing module is used to perform structured semantic parsing on the legal contract text and smart contract code, and extract semantic units of legal provisions and semantic units of code behavior. The vectorization encoding module is used to perform semantic encoding on the legal text semantic units and code behavior semantic units based on a pre-trained large language model, generating legal text vectors and code vectors; The mapping module is used to map the legal text vectors and code vectors to a unified cross-modal shared semantic space through a trainable mapping relationship; The alignment module is used to make the semantically corresponding legal provision vectors and code vectors approximate each other in the cross-modal shared semantic space, and to make the non-semantically corresponding vectors move away from each other. The training module is used to jointly train based on instance-level alignment loss, structural conditional alignment loss, and cross-modal contrastive consistency loss to obtain a consistent aligned cross-modal semantic vector model. The verification module is used to calculate the similarity between the newly input legal provisions and the smart contract code fragments using the cross-modal semantic vector model, and output a consistency verification conclusion.

9. A computer readable storage medium having stored thereon a computer program, characterized in that, The program, when executed by the processor, implements the steps of the method of any one of claims 1 to 8.

10. An electronic device comprising a memory, a processor, and a computer program stored on the memory and executable on the processor, characterized in that, The processor, when executing the program, implements the steps of the method of any one of claims 1 to 8.