Code optimization method based on large model

By constructing a code analysis and optimization method based on a large model, and combining multilingual pre-trained models and cross-language attention mechanisms, the problems of cross-language collaboration and adaptability to new projects in existing code optimization analysis technologies are solved, achieving efficient and accurate code optimization and development collaboration.

CN121934873APending Publication Date: 2026-04-28SUPCON TECH CO LTD
View PDF 1 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
SUPCON TECH CO LTD
Filing Date
2025-12-01
Publication Date
2026-04-28

AI Technical Summary

Technical Problem

Existing technologies for code optimization analysis suffer from insufficient cross-language collaborative optimization capabilities, poor adaptability to new projects, lack of real-time feedback mechanisms for developers, and insufficient executability of fix suggestions, resulting in low efficiency and insufficient accuracy of automatic review and optimization.

Method used

We employ a large-scale model-based code analysis and optimization approach. We construct a large-scale code analysis and optimization model through a multi-task learning architecture, combine multi-language pre-trained models and cross-language attention mechanisms, utilize abstract syntax trees and control flow graphs to model code structure, and employ multi-head classifiers and incremental analysis strategies to generate optimization analysis reports and support developer feedback mechanisms.

Benefits of technology

It significantly improves code optimization efficiency, enhances the accuracy of code problem identification and development collaboration efficiency, supports multi-language project optimization, reduces the workload of manual review, and optimizes model performance by dynamically adjusting detection sensitivity and incremental analysis strategies.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN121934873A_ABST
    Figure CN121934873A_ABST
Patent Text Reader

Abstract

The invention discloses a code optimization method based on a large model, and belongs to the technical field of artificial intelligence. The method specifically comprises the following steps: constructing a code analysis optimization large model based on a multi-task learning architecture; through a CI / CD plug-in or an API interface, an automatic task is triggered when a code is submitted or a request is combined; preprocessing the code for triggering the task, generating an abstract syntax tree and a control flow graph corresponding to the code, and performing multi-language embedding processing; inputting a preprocessing result into the optimization large model, extracting code semantic features, and detecting code problems by adopting a multi-label classification technology; positioning problem code snippets, and generating repair suggestions through a sequence-to-sequence architecture in combination with a natural language generation module; and automatically generating an analysis report containing problem information and repair suggestions, and integrating the analysis report to a development collaboration platform. According to the method, the core pain point of a traditional code optimization method is effectively solved, and an automatic, precise and multi-scene adaptive code optimization system is constructed.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention belongs to the field of artificial intelligence technology, and in particular relates to a code optimization method based on a large model. Background Technology

[0002] Currently, traditional code optimization and analysis methods are mostly manual reviews or optimization based on static rule matching and code structure analysis tools. These methods not only require a lot of manual time and resources, or require pre-setting complex optimization rules and parameters, but also generally do not support the identification of semantic rule problems in the code. As the code logic and structure become increasingly complex, traditional methods gradually become unable to perform efficient and accurate automatic review and optimization work.

[0003] On the other hand, while existing intelligent code evaluation and repair methods have made some progress in graph fusion modeling, they still have significant shortcomings when dealing with real-world complex engineering environments: First, they lack cross-language collaborative optimization capabilities, making it difficult to achieve semantic association and unified optimization analysis conclusions for mixed-language projects; second, they have poor adaptability to new projects without historical data, as existing methods rely on sufficient historical version commit records for vulnerability identification and lack the ability to review new projects in their initial stages; third, they lack a dynamic optimization mechanism for real-time developer feedback, making it difficult to continuously adapt to team development habits and reduce false positive rates as projects iterate; and fourth, the engineering feasibility details of repair suggestions are insufficient, although they can provide automatic or semi-automatic repair solutions, they still lack explanations of the business logic adaptability of the repair points and quantitative analysis of the cross-module impact scope.

[0004] For example, Chinese invention patent application CN120541851B discloses a code evaluation and repair method based on large model technology, which provides the following technical solutions: introducing a structure-aware code analysis model, generating a set of change information tuples by parsing historical version submission records, constructing a code attribute graph through syntax parsing, control flow and data flow analysis, and then using a graph neural network to generate structured code feature data; constructing a model based on a large language model, introducing a subspace mapping function and a self-activation response mechanism, and optimizing the model by combining an evidence lower bound loss function to achieve vulnerability identification, and providing two repair methods.

[0005] Therefore, it is necessary to propose relevant technical solutions that are suitable for implementation to address these existing problems. Summary of the Invention

[0006] The purpose of this invention is to provide a code optimization method based on a large model. By constructing a large code analysis and optimization model, it can detect and locate problematic segments and generate repair suggestions and optimization analysis reports, thereby solving the problem of low efficiency of conventional optimization analysis methods.

[0007] A further objective of this invention is to adapt multilingual pre-trained models and cross-lingual attention mechanisms to multilingual and mixed-language projects, adopt incremental code analysis strategies to reduce resource consumption, use multi-head classifiers to detect multi-dimensional issues such as code standardization and security, and allocate weights based on task importance and dynamically adjust detection sensitivity to solve the problems of insufficient optimization accuracy and scenario adaptability.

[0008] To achieve the various objectives of this invention, the present invention adopts the following technical solution: a code optimization method based on a large model, comprising: S1: Building a large-scale code analysis and optimization model based on a multi-task learning architecture; S2: Trigger automatic analysis and optimization tasks when code is committed or merged via CI / CD plugins or API interfaces; S3: Preprocess the code that triggers the task, generate the corresponding abstract syntax tree and control flow graph, and perform multi-language embedding; input the preprocessing results into the code analysis and optimization model, extract the semantic features of the code, and use multi-label classification technology to detect code problems; S4: Locates problematic code snippets, generates repair suggestions through a sequence-to-sequence architecture combined with a natural language generation module; automatically generates an optimization analysis report containing problem information and repair suggestions, and integrates it into the development collaboration platform.

[0009] As a preferred approach, when constructing the large model for code analysis and optimization, attention mechanisms and graph neural networks are introduced, and the code structure is jointly modeled through abstract syntax trees and control flow graphs.

[0010] Preferably, the abstract syntax tree is used to extract node types, parent-child node relationships, and nested structures, and node vectors are generated using a graph neural network. The code flowchart is modeled as a directed graph to obtain the control flow graph. Branch logic, loop structures, and exception handling paths are analyzed, and control flow features are generated using a graph convolutional network or a graph attention network. The node vectors of the abstract syntax tree and the control flow features of the control flow graph are concatenated and input into the encoder, and the correlation between code structure and semantics is captured through a cross-attention mechanism.

[0011] During the joint modeling process, for scenarios with deep code nesting or multi-function interactions, an attention mechanism is used to dynamically focus on the core code structure (such as core function calls and key branch logic) to avoid information dilution caused by full graph modeling. At the same time, the node update frequency of the graph neural network is optimized to ensure that the ability to extract structural features remains efficient when processing large-scale code.

[0012] During the node vector generation stage, feature weights are added to high-frequency key node types such as loops and conditional judgments to strengthen the representation of core syntactic structures. When generating control flow features, key execution paths are selected by combining path coverage, such as abnormal triggering paths and high-frequency execution paths, to reduce the interference of redundant paths on feature quality and make the cross-attention mechanism more accurately capture the deep relationship between structure and semantics.

[0013] Preferably, the code analysis and optimization model adopts a multilingual pre-trained model, which distinguishes the code context of different programming languages ​​through language embedding. For mixed language projects, the code analysis and optimization model performs structured encoding on code fragments of different languages ​​respectively, and integrates the analysis results of each fragment through a cross-language attention mechanism. The natural language generation module outputs a unified optimization analysis conclusion.

[0014] For low-resource programming languages, transfer learning is used to reuse pre-trained features of high-resource languages ​​to reduce the analysis error of low-resource language code. When integrating cross-language attention, weights are assigned based on the similarity of language syntax (such as C and C++, JavaScript and TypeScript) to improve the consistency of analysis results for language segments with high syntactic relevance.

[0015] Preferably, the natural language generation module supports multilingual description output and can generate the optimization analysis report in a specified language according to the language habits or needs of the target project development team.

[0016] It supports custom language templates for development teams, and allows preset industry-specific terminology and report formats. The generation module can call preset templates for output. It also supports real-time language switching to meet the report viewing needs of multinational teams in multilingual collaboration.

[0017] Preferably, the optimization analysis report includes a severity level of the problem and a classification of the problem type; the optimization analysis report supports a jump function, and clicking on the problem location description can directly locate the corresponding code snippet in the code repository.

[0018] The severity level of the problem is graded and associated with the priority of repair. The problem type is categorized and accompanied by common repair directions. The jump function is associated with the historical modification record of the code repository. Clicking it will display the previous analysis opinions for that segment, helping developers understand the background of the problem.

[0019] Preferably, the code analysis and optimization model establishes a dynamic feedback optimization mechanism. Developers evaluate the effectiveness of the generated optimization results and the repair suggestions, mark the feedback information, input the feedback information into the code analysis and optimization model for incremental learning, and update the model parameters to optimize the performance of the code analysis and optimization model. The feedback information is labeled with standardized tags (such as "false alarm", "ineffective repair suggestion", "missing issue") to help the model accurately locate the optimization direction; incremental learning adopts a small batch parameter update strategy to avoid model performance fluctuations caused by single feedback, and at the same time, historical feedback data is retrained once a month to consolidate the optimization effect and prevent model performance degradation.

[0020] Preferably, the multi-label classification technology detects code problems and assigns weights to different automatic analysis and optimization tasks based on the importance of the optimization analysis tasks, with the weight of security vulnerability detection tasks being higher than that of code standardization detection tasks; a probability threshold mechanism is introduced to dynamically adjust the sensitivity of problem detection.

[0021] Weight allocation supports project customization. For example, projects in the financial and medical fields can increase the weight of security vulnerability detection, while open-source collaborative projects can increase the weight of code standardization. The probability threshold adjustment is associated with the accuracy of historical model analysis of related projects, balancing detection precision and efficiency.

[0022] Preferably, when the automatic analysis and optimization task is triggered, an incremental code analysis strategy is adopted, which only performs the optimization analysis process on newly added or modified code segments, without having to perform repeated analysis on the entire code.

[0023] Before incremental analysis, identify the type of code change and exclude changes that have no functional impact, such as comment modifications and formatting adjustments, to avoid invalid analysis. At the same time, track the dependencies between new code and historical code. If there are potential risks in the historical code called by the new code, alert the associated risks in a synchronized manner to ensure that the analysis covers dependency scenarios.

[0024] Preferably, the code analysis and optimization model is also configured with a multi-head classifier, which includes multiple sub-classifiers. Each sub-classifier corresponds to the detection of problems in the dimensions of code standardization, security, performance, and maintainability. After each sub-classifier independently outputs its detection results, the code analysis and optimization model summarizes them into a unified multi-dimensional optimization analysis conclusion.

[0025] Each subclassifier has an independent optimization channel, and iterative updates are made to address different dimensions of issues such as security vulnerabilities and performance bottlenecks to improve the detection accuracy of a single dimension. When summarizing the conclusions, the causal links between issues are marked to help developers prioritize solving the root causes and reduce redundant fixes.

[0026] The present invention has the following beneficial effects: 1. No manual configuration of rules and parameters is required. The large model is automatically optimized through code analysis, which greatly reduces the workload of manual review, significantly improves code optimization efficiency, and reduces process complexity. 2. By combining abstract syntax trees and control flow graphs for joint modeling, and using attention mechanisms to extract deep semantic features of the code, multi-label classification technology is adopted and weights are assigned according to task importance. The detection sensitivity can also be dynamically adjusted, which effectively improves the accuracy of code problem identification and reduces false positives and false negatives. 3. Supports multi-language and mixed-language project optimization, and can generate optimization analysis reports in specified languages ​​according to team needs, with strong versatility; the optimization analysis reports include severity level and type classification of problems, improving development collaboration efficiency; through a multi-head classifier, it covers multiple dimensions of code standardization, security, performance, and maintainability detection, comprehensively ensuring code quality. Attached Figure Description

[0027] Figure 1 This is a flowchart of a code optimization method based on a large model according to the present invention.

[0028] Figure 2 This is a sequence diagram of operations for code review in an automatic code optimization method according to a certain embodiment of the present invention. Detailed Implementation

[0029] Embodiments of the present invention are described in detail below, examples of which are illustrated in the accompanying drawings. The embodiments described below with reference to the accompanying drawings are exemplary and are only used to explain the present invention, and should not be construed as limiting the present invention.

[0030] This embodiment takes the code optimization scenario of a certain central control OMC3.0 system (communication network operation and maintenance management system) as an example, combined with... Figure 1 Flowchart and Figure 2 The operation sequence diagram is explained in detail.

[0031] This embodiment uses the Transformer model with a multi-task learning architecture as the basic framework, and selects CodeBERT and GraphCodeBERT for pre-training. The pre-training data covers mainstream programming languages ​​such as Python, Java, and C++. The data sources include GitHub open-source operation and maintenance project code (approximately 5 million lines) and enterprise historical operation and maintenance system code (approximately 2 million lines, including manually annotated defect fragments).

[0032] The pre-training data is mixed in a ratio of "open source code: enterprise historical code = 7:3". The batch size is set to 64. The learning rate adopts a cosine annealing strategy (initial learning rate 5e-5, minimum learning rate 1e-6). The training epochs are 10. After each epoch, 1000 defect samples labeled by the enterprise are used for validation. Pre-training is stopped when the accuracy of the validation set exceeds 85%.

[0033] Each month, gather the previous month's valid feedback data (≥1000 entries) and mix it with the original training data at a ratio of 1:10 to construct a retraining dataset. Retraining is only performed on the evaluation dimensions in the feedback set. For example, if most of the feedback is about security issues, only the security subclassifier will be retrained. The training rounds are set to 3-5 rounds, and an "early stop mechanism" is adopted. If the accuracy of the validation set does not improve for two consecutive rounds, the training will stop. After retraining, a full test is performed to ensure that the accuracy of each dimension improves and the false positive rate decreases. Only after the target is met will the online model be updated to ensure stable iteration of model performance.

[0034] During model construction, an attention mechanism and a graph neural network (GNN) are introduced, and the code structure is jointly modeled by an abstract syntax tree (AST) and a control flow graph (CFG).

[0035] The abstract syntax tree is used to extract node types, parent-child node relationships, and nested structures, and node vectors are generated using a graph neural network. The code flowchart is modeled as a directed graph to obtain the control flow graph. Branch logic, loop structures, and exception handling paths are analyzed, and control flow features are generated using a graph convolutional network or graph attention network. The node vectors of the abstract syntax tree and the control flow features of the control flow graph are concatenated and input into the encoder. The cross-attention mechanism is used to capture the correlation between code structure and semantics.

[0036] During the joint modeling process, for scenarios with deep code nesting or multi-function interactions, an attention mechanism is used to dynamically focus on the core code structure (such as core function calls and key branch logic) to avoid information dilution caused by full graph modeling. At the same time, the node update frequency of the graph neural network is optimized to ensure that the ability to extract structural features remains efficient when processing large-scale code.

[0037] During the node vector generation stage, feature weights are added to high-frequency key node types such as loops and conditional judgments to strengthen the representation of core syntactic structures. When generating control flow features, key execution paths are selected by combining path coverage, such as abnormal triggering paths and high-frequency execution paths, to reduce the interference of redundant paths on feature quality and make the cross-attention mechanism more accurately capture the deep relationship between structure and semantics.

[0038] AST encoding: Python's ast module is used to parse the code and generate an AST, extracting node types (such as FunctionDef, IfStmt, TryStmt) and parent-child node nesting relationships (such as "nested conditional statements within loops"). A node vector with a dimension of 512 is generated through the graph convolutional layer of GNN. For high-frequency key nodes such as "nested loops" and "anomaly capture", the feature weights are increased to strengthen the representation of the core syntactic structure.

[0039] CFG Coding: The PyTorchGeometric tool is used to model the code flow diagram as a directed graph, analyze branch logic (such as "main flow and exception branches"), loop structure (such as "infinite loop risk") and exception handling path (such as "uncaught IO exception"), and generate 512-dimensional control flow features through Graph Attention Network (GAT); select "exception trigger path" and "high-frequency executed operation and maintenance instruction path" as critical paths, and remove redundant comment-related paths to reduce feature interference.

[0040] The AST node vector and CFG control flow features are concatenated into a 1024-dimensional feature vector, which is then input into the Transformer encoder. The cross-attention mechanism is used to capture the relationship between structure and semantics (e.g., when detecting "unprocessed anomalies", attention is simultaneously paid to the missing TryStmt node in the AST and the abnormal path break in the CFG).

[0041] Meanwhile, the model is configured with a multi-head classifier, containing four sub-classifiers, each corresponding to one of the core evaluation dimensions of the OMC3.0 system: Security subclassifier: Detects issues such as "hard-coded database passwords", "SQL injection risks", and "missing permission checks"; Performance subclassifier: Detects problems such as "frequent I / O operations within loops", "large uninitialized arrays", and "redundant computation"; Standardization subclassifier: Detects issues such as "variable naming does not conform to the operation and maintenance system specifications (e.g., missing omc_ prefix)" and "incomplete function comments"; Maintainability subclassifier: Detects problems such as "function code exceeding 200 lines", "duplicate code blocks", and "incompatible dependency library versions".

[0042] Each subclassifier is independently iterated and optimized, and its weights are updated monthly based on the system's defect repair records. The optimal initial settings are: a weight of 0.4 for the security subclassifier, 0.3 for the performance subclassifier, and 0.2 and 0.1 for standardization and maintainability, respectively, to match the operation and maintenance system's requirement of "security and performance priority".

[0043] In a preferred embodiment, a new "database interaction risk" detection rule is added to the security subclassifier of the multi-head classifier. This rule includes three sub-problems: "SQL statement concatenation leading to injection risk", "unreasonable database connection pool parameters", and "unclosed result set leading to connection leakage". The detection weight of this rule is increased to 0.3 within the subclassifier (the original total weight of the security subclassifier remains unchanged at 0.4, while the weights of other rules are reduced proportionally).

[0044] In a preferred embodiment, a "database-specific detection layer" is added to the security subclassifier to address high-frequency risks in database operations (SQL injection, connection leakage, and hard-coded passwords). During the preprocessing stage, SQL statements are additionally parsed to generate an "SQL syntax tree," extracting features such as "parameter concatenation," "result set closure," and "plaintext passwords," which are then input into the model in conjunction with AST / CFG features. During detection, an "SQL risk rule base" (containing 100+ common database risk patterns) is used to assist in judgment, improving the accuracy of database problem detection. Remediation suggestions are embedded with "best practices for database operations" (such as parameterized queries, connection pool configuration, and encrypted password storage) to ensure compliance with database security standards.

[0045] In a preferred embodiment, for scheduled task code (such as periodic data collection and log cleanup in an operations and maintenance system), a new "scheduled task-specific feature" is added to the performance subclassifier, including task cycle, timeout, number of retries, and execution dependencies. When modeling with CFG, the focus is on analyzing whether "task execution time exceeds the cycle", "whether it contains blocking I / O", and "whether the failure retry logic is reasonable". The detection results include "task execution risk assessment" (such as "task cycle of 300 seconds, estimated execution time of 400 seconds, there is a risk of backlog"). The remediation suggestions specify engineering solutions such as "timeout setting", "task splitting strategy", and "asynchronous execution transformation".

[0046] In a preferred embodiment, the multi-head classifier adds a "Scalability" sub-classifier to address necessary plug-in architecture requirements (supporting third-party operation and maintenance plugin integration). This sub-classifier detects issues such as "plugin interfaces not compatible with older system versions," "custom operation and maintenance commands not registered to the core scheduler," and "plugin configuration files not placed in the specified directory." This sub-classifier has a weight of 0.15, and the weights of other sub-classifiers are adjusted accordingly (security 0.35, performance 0.3, standardization 0.15, maintainability 0.05). This ensures that the evaluation dimensions better align with the system's plug-in expansion needs, reducing compatibility issues during later plugin integration and lowering the risk of failure after plugin deployment.

[0047] This embodiment triggers automated analysis and optimization tasks through the GitLab CI plugin (team collaboration tool). When developers commit code or initiate a pull request on GitLab (code hosting platform), GitLab CI automatically calls the code optimization tool via API to trigger optimization analysis tasks (corresponding to...). Figure 2 The process of "submitting code → sending optimization request" in China.

[0048] The code analysis and optimization model employs a multilingual pre-trained model, which distinguishes the code context of different programming languages ​​through language embedding. For mixed-language projects, the code analysis and optimization model performs structured encoding on code fragments of different languages ​​and integrates the analysis results of each fragment through a cross-language attention mechanism. The natural language generation module outputs a unified optimization analysis conclusion.

[0049] An incremental code analysis strategy is executed after the automatic task is triggered: First, use Git's diff command to identify the type of code change and exclude changes that have no functional impact, such as "only modifying comments" or "adjusting indentation" (e.g., if the developer only modifies function comments, the analysis tool will skip that segment). Use regular expression matching to exclude changes that have no functional impact, such as comment modifications or format adjustments, and retain only logical code changes as the objects of analysis and optimization.

[0050] For newly added or modified code snippets (such as the "new base station status query function"), their dependencies on historical code (such as the "database connection utility class" called by the function) are automatically tracked. If the dependent class has a potential risk of "connection not being closed", it is also included in the analysis.

[0051] Tools such as PyDep, JDepend, and GoDep are used to parse the function call chain and import dependencies of newly added code. If the newly added code calls historical code, the analysis records of the historical code are automatically traced. If there are unresolved risks in the historical code, they are included in the scope of this analysis and an "Association Risk Warning" is generated. The dependency analysis results are embedded in the preprocessed output in the form of a "dependency graph" to help the model identify cross-version risk transmission.

[0052] Perform "format standardization" on the input code, including removing redundant blank lines, standardizing indentation, and standardizing comment format (e.g., function comments must include parameter descriptions, return values, and function descriptions); use specific formatting rules for code in different languages ​​to ensure consistency in the model input format.

[0053] Feature enhancement and noise filtering: During the preprocessing stage, "key syntactic structures" (such as loops, conditional statements, and exception handling) in the code are marked to enhance the model's focus on core logic; at the same time, "test code" and "automatically generated code" (such as API interface code generated by Swagger) are filtered out by file path matching (such as test / directory, generated / directory) or code comment markers (such as / / Auto-generated) to avoid invalid analysis; for extremely long code files (≥1000 lines), a "segmentation" strategy is adopted, which splits the code by function / class and generates features independently, and then integrates them into file-level analysis results to prevent feature dilution when the model processes large files.

[0054] The preprocessing stage also performs multilingual embedding processing. For example, for mixed language segments where Python calls C++, the model's multilingual pre-training capability is used to distinguish the language context using language embedding vectors. Then, the analysis results are integrated through a cross-language attention mechanism. For example, the "memory leak" problem in the C++-driven function should be synchronously associated with the "resource release logic" of the Python call layer.

[0055] The problem detection process employs multi-label classification technology to simultaneously identify multiple issues in the code and introduces a probability threshold mechanism to dynamically adjust the detection sensitivity. An optimal initial threshold is 0.6. If the false positive rate for security issues exceeds 10% in three consecutive optimization analyses (e.g., misjudging "legitimate operation and maintenance password reading logic" as "hard-coded password"), the threshold can be increased to 0.7. If the false negative rate for performance issues exceeds 5% (e.g., failing to detect "frequent database queries within a loop"), the threshold can be decreased to 0.5.

[0056] Problem localization is achieved through token-level attention weights of Transformer. For example, when "frequent writing of operation and maintenance logs within a loop" is detected, the model will highlight the statement "calling omc_log.write() within a for loop" in the code and mark the specific path of the segment in the GitLab code repository (e.g., / omc3.0 / core / base_station / query_5g_status.py:120-135).

[0057] The repair recommendations are generated using a sequence-to-sequence (Seq2Seq) architecture combined with a natural language generation (NLG) module, and are fully adapted to the system's business logic.

[0058] Below are two specific examples. If "hard-coded database password" is detected, the generated suggestion is "It is recommended to change db_password="omc@2024_db" in the code to read the password from the configuration file / omc3.0 / config / db_auth.yaml and call the omc_config.get("db.password") method to obtain the password. After modification, the permissions of the configuration file deployed by the operation and maintenance team need to be updated synchronously (only root user is allowed to read and write) to avoid the risk of password leakage." If "frequent database queries within a loop" is detected, the suggestion is "It is recommended to call omc_db.query("SELECT*FROMbase_station_status") to obtain the full base station status data outside the loop, and then filter the target base station information from the local cache data inside the loop. This can reduce the number of database queries and reduce database load and interface response latency."

[0059] In a preferred embodiment, the NLG module generates natural language suggestions based on "industry terminology templates + business logic adaptation rules". The template includes four parts: "problem description, repair steps, precautions, and cross-module impact description". It supports project-customized templates and can preset business-specific terms (such as "base station" and "network element" in the operation and maintenance system) and repair specifications (such as database operations needing to include permission verification) to ensure that the suggestions meet the actual development needs of the project.

[0060] In a preferred embodiment, the NLG module supports switching between Chinese and English, and can generate Chinese reports (for domestic operations and maintenance teams) or English reports (for cross-border collaboration scenarios) according to the team's needs. It also has a preset "operations and maintenance system industry terminology template" (such as terms like "base station", "network element", "configuration distribution", "fault alarm" etc.) to ensure that the suggested expressions conform to industry conventions.

[0061] The optimization analysis report is automatically integrated into the GitLab platform, and developers can view it directly on the merge request page. The report includes a severity level classification of the problem ("Critical", "High Risk", "Medium Risk", "Low Risk") and associated remediation priorities. It supports code navigation; clicking on the problem location description (e.g., "query_5g_status.py:120-135") will directly locate the corresponding segment in the GitLab code repository, and simultaneously display the previous analysis records of that segment (e.g., "It was marked as 'uninitialized variable' on 2024-04-15, and this is a newly added performance issue"). It also indicates the cross-module impact scope of the problem, for example, "The memory leak problem only affects the base station status query module, does not depend on the core scheduling module and alarm module, and no adjustments to other module code are required during the repair."

[0062] The dynamic feedback optimization mechanism is implemented through GitLab's "Optimization Analysis Feedback" function. Developers analyze the results and fix suggestions to evaluate their effectiveness, marking them with standardized tags such as "false positives" (e.g., the model misclassifies legitimate logic as a problem), "invalid fix suggestions" (e.g., suggestions conflict with C++ driver layer compatibility), and "missed issues" (e.g., "configuration file not detected"). This feedback information is input into the code in real time for analysis and optimization of the large model for incremental learning, using a small batch (batch size=32) parameter update strategy to avoid model performance fluctuations caused by single feedback. On the 5th of each month, the feedback data from the previous month (approximately 500 labeled records) is centrally retrained to consolidate the optimization effect and prevent model performance degradation.

[0063] In a preferred embodiment, for low-resource programming languages, transfer learning is used to reuse pre-trained features from high-resource languages, reducing the analysis error of low-resource language code. During cross-language attention integration, weights are assigned based on language syntactic similarity (e.g., C and C++, JavaScript and TypeScript) to improve the consistency of analysis results for language segments with high syntactic relevance. For example, for Rust (used in a small number of low-resource languages ​​in the central control system, used for the underlying hardware interaction module, with less than 100,000 lines of labeled data), a transfer learning strategy is used to reuse C++ pre-trained features. Since Rust and C++ have a syntactic similarity of 60% and both emphasize memory safety and performance, the transfer weight of the C++ pre-trained features is set to 0.8. This allows the model to quickly adapt to Rust code optimization based on C++ defect identification experience, ultimately significantly improving the accuracy of Rust code analysis and solving the problem of high analysis error in low-resource languages.

[0064] In a preferred embodiment, the NLG module supports real-time language switching. When collaborating across borders (such as maintaining the system with overseas branch teams), developers can click the "Language Switch" button on the GitLab review interface to convert the Chinese optimization analysis report into an English report in real time. The system also provides a domain-specific terminology mapping table to ensure the accuracy and professionalism of the report in a multilingual environment and avoid misunderstandings of terminology.

[0065] In a preferred embodiment, to accommodate the optimization needs of 30+ merge requests daily, multiple high-performance graphics cards are used for GPU parallel computing during model deployment, supporting the simultaneous execution of 10 optimization tasks. Containerized deployment is achieved through Kubernetes, automatically adjusting the number of computing nodes based on the task queue length. Combined with an incremental analysis strategy, the optimization time for the system's core modules (approximately 100,000 lines of code) is reduced from 20 minutes for full analysis to 2-3 minutes for incremental analysis. Simultaneously, through a "task priority scheduling" mechanism, the optimization task for the "emergency repair branch in the production environment" is given the highest priority, ensuring that the response time for urgent needs is controlled within 1 minute, significantly improving team development efficiency. The above embodiments fully verify the feasibility and effectiveness of the method of the present invention. All operation steps and parameter settings are based on actual operating specifications and can be directly promoted.

Claims

1. A code optimization method based on a large model, characterized in that, include: S1: Building a large-scale code analysis and optimization model based on a multi-task learning architecture; S2: Trigger automatic analysis and optimization tasks when code is committed or merged via CI / CD plugins or API interfaces; S3: Preprocess the code that triggers the task, generate the corresponding abstract syntax tree and control flow graph, and perform multi-language embedding processing; The preprocessing results are input into the code analysis and optimization model to extract semantic features of the code and use multi-label classification technology to detect code problems. S4: Locates problematic code snippets, generates repair suggestions through a sequence-to-sequence architecture combined with a natural language generation module; automatically generates an optimization analysis report containing problem information and repair suggestions, and integrates it into the development collaboration platform.

2. The code optimization method based on a large model according to claim 1, characterized in that, When constructing the large model for code analysis and optimization, attention mechanisms and graph neural networks are introduced, and the code structure is jointly modeled by abstract syntax trees and control flow graphs.

3. The code optimization method based on a large model according to claim 2, characterized in that, The abstract syntax tree is used to extract node types, parent-child node relationships, and nested structures, and node vectors are generated through a graph neural network. The code flowchart is modeled as a directed graph to obtain the control flow graph. Branch logic, loop structures, and exception handling paths are analyzed, and control flow features are generated through a graph convolutional network or a graph attention network. The node vectors of the abstract syntax tree are concatenated with the control flow features of the control flow graph and then input into the encoder. The correlation between code structure and semantics is captured through a cross-attention mechanism.

4. A code optimization method based on a large model according to claim 1 or 2, characterized in that, The code analysis and optimization model adopts a multilingual pre-trained model, which distinguishes the code context of different programming languages ​​through language embedding. For mixed language projects, the code analysis and optimization model performs structured encoding on code fragments of different languages, and integrates the optimization analysis results of each fragment through a cross-language attention mechanism. The natural language generation module outputs a unified analysis and optimization conclusion.

5. The code optimization method based on a large model according to claim 4, characterized in that, The natural language generation module supports multilingual description output and can generate the optimization analysis report in a specified language according to the language habits or needs of the target project development team.

6. A code optimization method based on a large model according to claim 1 or 5, characterized in that, The optimization analysis report includes a severity level of the problem and a classification of the problem type; the optimization analysis report supports a jump function, and clicking on the problem location description can directly locate the corresponding code snippet in the code repository.

7. A code optimization method based on a large model according to claim 1 or 2, characterized in that, The code analysis and optimization model establishes a dynamic feedback optimization mechanism. Developers evaluate the effectiveness of the generated optimization analysis results and the repair suggestions, mark the feedback information, and input the feedback information into the code analysis and optimization model for incremental learning to update the model parameters and optimize the performance of the code analysis and optimization model.

8. The automatic code optimization method based on a large model according to claim 1, characterized in that, The multi-label classification technology detects code problems and assigns weights to different automatic analysis and optimization tasks based on their importance, with the weight of security vulnerability detection tasks being higher than that of code standardization detection tasks. A probability threshold mechanism is introduced to dynamically adjust the sensitivity of problem detection.

9. A code optimization method based on a large model according to claim 1 or 8, characterized in that, When the automatic analysis and optimization task is triggered, an incremental code analysis strategy is adopted, which only performs the optimization analysis process on newly added or modified code segments, without having to perform repeated analysis on the entire code.

10. The code optimization method based on a large model according to claim 1, characterized in that, The code analysis and optimization model is also configured with a multi-head classifier, which contains multiple sub-classifiers. Each sub-classifier corresponds to the detection of problems in the dimensions of code standardization, security, performance, and maintainability. After each sub-classifier independently outputs its detection results, the code analysis and optimization model summarizes them into a unified multi-dimensional optimization analysis conclusion.

Citation Information

Patent Citations

  • A code evaluation and repair method based on large model technology

    CN120541851B