Checkpoint-oriented serialization code automatic generation method and system

By automatically generating serialization code and optimizing field-level pruning, the development difficulty and low efficiency of checkpointing technology in high-performance computing are solved. Raw pointer support and data simplification are achieved, improving the development and storage efficiency of checkpointing.

CN123177818APending Publication Date: 2026-11-27ZHEJIANG UNIV +1
View PDF 0 Cites 0 Cited by

Patent Information

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

AI Technical Summary

Technical Problem

Existing checkpointing techniques in the field of high-performance computing suffer from problems such as the large workload of developers manually writing serialization code, insufficient support for raw pointers, and low efficiency due to data dump redundancy.

Method used

By parsing the abstract syntax tree to generate a unified symbolic representation, and combining it with a large language model for data flow analysis and field-level activity analysis, serialization code is automatically generated, and pointer dimension table entries are generated for raw pointers, thus achieving field-level pruning optimization.

Benefits of technology

It significantly reduces the workload for developers, expands the applicability of checkpointing technology, improves the execution efficiency of checkpointing, and reduces storage space usage and I/O overhead.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN123177818A_ABST
    Figure CN123177818A_ABST
Patent Text Reader

Abstract

The application discloses a checkpoint-oriented serialization code automatic generation method and system, characterized by the following steps: parsing an abstract syntax tree of a target code segment in an application program to generate a uniform symbolic representation; obtaining an activity score of each member field and pruning; traversing all member fields in the pruned uniform symbolic representation, if the type of the current member field is a pointer, generating a corresponding pointer dimension table entry for each member field, and generating corresponding serialization code and deserialization code based on the entry; if the type of the current member field is a non-pointer type, processing according to the type of the member field, which is a basic type or a custom data structure type, to generate serialization code and deserialization code conforming to the cereal library specification; the method has the advantages that the serialization code is automatically generated, the naked pointer serialization is effectively supported, the checkpoint data volume is reduced through field-level pruning, the developer burden is reduced, and the checkpoint execution efficiency is improved.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the fields of software engineering and program analysis technology, and in particular to a method and system for automatically generating checkpoint-oriented serialized code. Background Technology

[0002] In the field of High Performance Computing (HPC), checkpoint restart technology is widely used to save the running state of a system in order to cope with interruptions such as hardware failures, system maintenance, or resource scheduling that may occur during long-running computing tasks. Traditional checkpoint methods require pausing process execution, completely dumping the program's memory state to persistent storage media, and then reading the state from the storage media and restarting the program when recovery is needed. In C++ programs, implementing checkpoint functionality usually relies on serialization libraries to persist object state. Serialization converts the data structure or object state in memory into a storable or transmittable byte stream format, while deserialization restores the stored byte stream to the data structure or object state in memory, allowing the program to restore the previously saved running state from the checkpoint file and continue execution.

[0003] Cereal is one of the mainstream C++ serialization libraries. It is an open-source, lightweight, cross-platform serialization library that only includes header files. It supports C++11 features and can serialize any data type into various formats such as binary, XML, or JSON. It also provides good support for various container types and smart pointers (such as std::shared_ptr and std::unique_ptr) in the C++ standard library. However, existing checkpointing schemes based on Cereal and other serialization libraries still have several shortcomings. First, there is a lack of automated code generation mechanisms. Developers need to manually write serialization and deserialization functions for each data structure. In HPC applications, programs often involve a large number of complex data structures, and manually writing serialization code is a huge workload and prone to errors. When the data structure changes, the serialization code also needs to be modified synchronously, resulting in high maintenance costs. Second, mainstream serialization libraries such as Cereal do not support raw pointers in C++. The serialization of pointers is only supported for smart pointer types. This limitation stems from the fact that raw pointers only store runtime memory addresses. After serialization, these addresses are often invalidated when loaded. Directly storing pointer addresses can lead to segmentation faults or data loss. However, in actual HPC applications and legacy code, the use of raw pointers is still very common for performance reasons or historical reasons, which severely limits the applicability of checkpointing technology. Third, existing checkpointing methods lack data optimization mechanisms. When saving a checkpoint, all data of the current state is dumped, including a large number of temporary variables and redundant fields that will not be used after a restart. This "full dump" method results in an excessively large amount of checkpoint data, increasing I / O overhead and storage space usage, and reducing the execution efficiency of checkpointing. Summary of the Invention

[0004] The technical problem to be solved by the present invention is to provide a method and system for automatic generation of serialized code oriented to checkpoints. It realizes the automatic generation of serialized code and provides effective support for raw pointers. At the same time, it performs field-level pruning optimization on checkpoint data, thereby reducing the burden on developers, expanding the applicability of checkpoint technology and improving checkpoint execution efficiency.

[0005] The technical solution adopted by this invention to solve the above-mentioned technical problems is: a method for automatically generating serialized code oriented to checkpoints, characterized by including the following steps: Step 1: Parse the abstract syntax tree of the target code snippet in the application, extract the type information, scope information and data structure of all local and global variables involved in the target code snippet, and generate a unified symbol representation; the data structure includes member fields, and the member fields include field name, type, access permission and nesting relationship; Step 2: Use the trained large language model to perform data flow analysis and field-level activity analysis on the unified symbolic representation and its corresponding target code snippets to obtain the activity score of each member field, and make pruning decisions on all member fields according to the set activity threshold to generate pruned unified symbolic representations. Step 3: Traverse all member fields in the pruned unified symbolic representation. If the type of the current member field is a pointer, proceed to step 4; otherwise, proceed to step 5. Step 4: According to the preset naming rules of the pointer dimension table, generate a corresponding pointer dimension table entry for each member field, and generate the corresponding serialization code and deserialization code based on the generated pointer dimension table entries; Step 5: If the current member field is of a basic type, serialization is performed directly using the Cereal library's built-in serialization functionality, without generating serialization and deserialization code. If the current member field is of a custom data structure and its nesting relationship is non-nested, serialization and deserialization code conforming to the Cereal library's specifications are generated. If the current member field is of a custom data structure and its nesting relationship is nested, serialization and deserialization code conforming to the Cereal library's specifications are generated separately for each nested member field, and the recursive logic for nested serialization is implemented by the Cereal library itself.

[0006] Compared with existing technologies, the advantages of this invention are as follows: First, by parsing the abstract syntax tree and extracting variable type information, scope information, and data structure in step 1 to generate a unified symbolic representation, and then combining this with steps 3 to 5 to automatically assign different serialization code generation strategies based on member field types, fully automatic generation from program source code to serialization code is achieved. Developers do not need to manually write serialization and deserialization functions for each data structure. When the data structure changes, simply rerunning this method will automatically update the serialization code, thereby significantly reducing development workload and maintenance costs, and also avoiding logical errors that are easily introduced by manual coding. Second, by generating corresponding pointer dimension table entries for pointer-type member fields in step 4, and generating serialization and deserialization code based on these pointer dimension table entries, the raw pointer is converted into dimensional description information that can correctly record the content of the object pointed to by the pointer and its memory layout during serialization, and in reverse order... During serialization, the pointer relationships are reconstructed based on the dimension table entries, and the data of the pointed-to objects is restored. This effectively solves the technical problem that mainstream serialization libraries such as Cereal cannot handle raw pointer types, enabling legacy HPC applications that heavily use raw pointers to smoothly apply checkpointing technology. Furthermore, by using a large language model in step 2 to perform data flow analysis and field-level activity analysis on the unified symbolic representation and its corresponding target code fragments, an activity score is obtained for each member field to determine whether it will be reused after checkpointing. Based on a set threshold, inactive member fields are pruned, ensuring that only the field data truly needed in the subsequent recovery process is dumped when saving checkpoints. This avoids the unnecessary I / O overhead caused by temporary variables and redundant fields in the existing "full dump" method, effectively reducing the data volume of the checkpoint file, reducing storage space occupation, and shortening the write and read time of checkpoints, thereby improving the overall execution efficiency of checkpoint operations.To verify the practical effect of this invention, a comparative experiment was conducted on an HPC cluster (Intel Xeon Gold 6248 CPU @ 2.50GHz, 40 cores per node) using OpenFOAM v11 as the test object, targeting a test dataset of approximately 10 million grid cells. Manually writing serialization code required analyzing data structure members one by one, handling template nesting relationships and private member access permissions, taking more than 30 minutes and prone to debugging errors. However, using the method of this invention, the large language model automatically completed field activity analysis and pruning decisions and generated pruned unified symbolic representations in only about 2 minutes. The automatically generated serialization code was integrated into the project and completed lightweight configuration in only about 3 minutes, for a total of about 5 minutes to complete all the work, improving development efficiency by more than 80%. The above experimental data fully demonstrates that, while ensuring serialization correctness, this invention can reduce the development time of serialization code from half an hour to minutes, significantly improving the development efficiency of C++ program checkpointing functions in HPC scenarios, while also taking into account raw pointer compatibility and data simplification optimization, demonstrating outstanding practical value.

[0007] Furthermore, in step 2, the large language model employs a two-stage training strategy: the pre-training stage learns general semantic representations on a large-scale C++ codebase, and the fine-tuning stage optimizes field activity prediction capabilities on an annotated checkpoint dataset. Training is performed using the AdamW optimizer and a cosine annealing learning rate scheduling strategy, employing a combination of binary cross-entropy loss and dependency consistency loss. This approach adaptively adjusts the learning step size during training, avoids getting stuck in local optima, and accelerates convergence. Combining binary cross-entropy loss and dependency consistency loss ensures both the independent prediction accuracy of each field and maintains the global consistency of inter-field dependencies, significantly improving the model's prediction accuracy for field activity scores and providing a reliable data foundation for subsequent pruning decisions.

[0008] Furthermore, in step 2, the specific process for obtaining the activity score for each member field is as follows: First, the target code fragment and the unified symbol representation are converted into corresponding token sequences by a token segmenter. Each token is then processed through an embedding layer and positional encoding to obtain two independent initial vector representations. Next, these two initial vector representations are input into a multi-layer Transformer encoder, where semantic features are extracted layer by layer using a self-attention mechanism and a feedforward neural network, resulting in independent context vector sequences. The context vector sequence corresponding to the unified symbol representation is used as the query, and the context vector sequence of the target code fragment is used as the key and value. These are then fused through a cross-attention mechanism to generate a target code context vector sequence that incorporates unified symbol information. Next, all reference positions of each member field in the unified symbol representation within the target code fragment are located. The context vectors corresponding to these reference positions are extracted from the target code context vector sequence. All extracted context vectors are pooled, and combined with the type of the member field, the activity score for each member field is calculated through the output layer. By integrating reference frequency, reference context semantics, and type features, the final calculated activity score objectively reflects the actual usage probability of each field after checkpoints, providing a precise quantitative basis for subsequent field pruning.

[0009] Furthermore, in step 2, the specific method for generating the pruned unified symbolic representation is as follows: member fields with activity scores below a preset threshold are deleted, while member fields with activity scores equal to or higher than the preset threshold are retained, thus generating the pruned unified symbolic representation. This thresholding pruning strategy ensures that necessary field data is not lost during restart and recovery, while also eliminating redundant fields that will not be used after recovery from the serialization process. This minimizes the actual amount of data that needs to be serialized while ensuring the correctness of program recovery, directly reducing the amount of code output in subsequent serialization code generation steps and the total data size of the checkpoint file.

[0010] Furthermore, in step 4, the default naming rule for the pointer dimension table is <instance name>_<structure path>_<pointer member name>_<dimension information>; In step 4, the specific method for generating the corresponding serialization and deserialization code is as follows: During serialization, the value of the pointer dimension table entry is first checked. If the value is greater than 0, the dimension information is serialized first, and then the array elements pointed to by the pointer are serialized one by one through a loop. If the value is equal to 0, a null marker is serialized to represent a null pointer. During deserialization, the dimension information is first read. If the value is greater than 0, memory space of the corresponding size is dynamically allocated. Then, the array elements are deserialized one by one into the allocated memory through a loop, and the pointer is set to the address of that memory. If the value is equal to 0, the pointer is set to a null pointer. Through this branching processing mechanism based on pointer dimension table entries, the dynamic array pointed to by the raw pointer can completely save its dimension information and all element data during serialization. During deserialization, it can accurately reconstruct the memory space of the same size as the original array according to the recorded dimension information and restore all data content. Thus, the raw pointer, which originally only stored address information, is transformed into a structured data description that can be completely persisted and restored, effectively solving the fundamental problem that serialization libraries such as Cereal do not support the serialization of raw pointer types.

[0011] Furthermore, in step 4, when multiple instances of the same data structure type have the same pointer member name, the default naming rule for the pointer dimension table is <instance name>_<outer structure name>_<inner structure name>_<pointer member name>><dimension information>. Each pointer dimension table entry independently records the length of the array pointed to by the corresponding pointer. The default value is 0, indicating a null pointer or a single object. When generating serialization code, the corresponding pointer dimension table entry is found based on the instance name, the dimension information is read, and the corresponding loop serialization code is generated. When generating deserialization code, the corresponding pointer dimension table entry is also found based on the instance name, the dimension information is read, the appropriate amount of memory space is dynamically allocated, and loop deserialization code is generated to restore the data to the allocated memory. This mechanism ensures that multiple structure instances each have their own independent dimension record space, avoiding the confusion or overwriting of dimension information between different instances. This allows the pointer data of each object to be correctly serialized and saved, and accurately deserialized and restored, even in complex application scenarios containing multiple objects of the same type.

[0012] Furthermore, the generated serialization and deserialization code are externally encapsulated with data change detection proxy logic. The data change detection proxy logic is used to independently maintain a runtime hash value for each data object instance to be serialized. This hash value records the hash state of the data object instance at the last checkpoint execution time. When performing a checkpoint, the hash value of the current data object instance at the current moment is calculated. This hash value is compared with the hash value stored in memory at the previous checkpoint. If they are the same, the execution of the generated serialization code for that object instance is skipped, and only an "unchanged" flag is recorded in the current checkpoint file. If they are different, the generated serialization code is called to perform a complete serialization operation and the complete serialized data is written to the current checkpoint file. At the same time, the hash value stored in memory is updated to the hash value at the current moment. For the first checkpoint, the generated serialization code is directly called to perform a complete serialization operation and the initial hash value is saved. During deserialization, the markers in the current checkpoint file are read. If an "unchanged" marker is encountered, the process traces back along the historical versions of the checkpoint file to locate the most recent checkpoint file without an "unchanged" marker, where the complete serialized data of the object instance is stored. This complete serialized data is read, and the generated deserialization code is invoked for restoration. If no "unchanged" marker is encountered, the complete serialized data is read from the current checkpoint file, and the generated deserialization code is invoked to restore the data to the memory object instance. This incremental checkpointing mechanism based on hash comparison avoids unnecessary computational and I / O write overhead caused by repeatedly serializing the same data, especially in the common scenario where the state of many objects remains unchanged during program execution. Simultaneously, the historical backtracking mechanism ensures that correct and complete data is obtained during deserialization, thus significantly reducing checkpoint execution time and write pressure on the storage medium while guaranteeing restoration correctness.

[0013] Furthermore, the system automatically inserts the generated serialization and deserialization code into the target source code file. Specifically, it first analyzes the source code file containing the target data structure to identify the location and scope of the class or struct definition. Then, based on code style and access permissions, it determines the insertion point for the serialization code. For member functions within a class, it inserts into the public or private section of the class definition; for independent functions, it inserts into the same namespace after the class definition. Finally, it automatically adds the generated serialization code at the insertion point and adds necessary Cereal library header file inclusion statements at the beginning of the file, ensuring the indentation format of the inserted code matches the original code. This automated code integration mechanism eliminates the need for developers to manually locate the insertion point, handle C++ syntax details such as access modifiers and namespaces, or manually add header file dependencies. The generated code can be directly integrated into existing projects while maintaining consistency with the original code style, avoiding compilation errors caused by improper insertion points or format mismatches during manual integration. This further reduces the barrier to entry and integration workload for developers.

[0014] A checkpoint-oriented automatic serialization code generation system includes: The abstract syntax tree parsing module is used to parse the abstract syntax tree of the target code segment in the application, extract the type information, scope information and data structure of all local and global variables involved in the target code segment, and generate a unified symbol representation. The field pruning module, which embeds the trained large language model, is used to perform data flow analysis and field-level activity analysis on the unified symbolic representation and its corresponding target code snippets. It obtains the activity score of each member field, and makes pruning decisions on all member fields according to the set activity threshold to generate pruned unified symbolic representations. The type traversal module is used to traverse all member fields in the pruned unified symbolic representation. If the type of the current member field is a pointer, the pointer serialization module is executed; if the type of the current member field is not a pointer, the non-pointer serialization module is executed. The pointer serialization module is used to generate corresponding pointer dimension table entries for each member field according to the preset naming rules of the pointer dimension table, and generate corresponding serialization and deserialization code based on the generated pointer dimension table entries; The non-pointer serialization module is used to directly serialize a member field using the Cereal library's built-in serialization functionality if the current member field is a basic type, without generating serialization and deserialization code. If the current member field is a custom data structure with no nesting, it generates serialization and deserialization code conforming to the Cereal library's specifications. If the current member field is a custom data structure with nesting, it generates separate serialization and deserialization code conforming to the Cereal library's specifications for each nested member field, with the recursive logic for nested serialization implemented by the Cereal library itself. This system architecture solidifies the aforementioned methods and steps in a modular manner. Modules communicate and collaborate using unified symbolic representations, enabling automated and streamlined execution of the entire process from source code input to serialized code output. Developers only need to provide the target code snippet to obtain complete serialization and deserialization code output, providing an integrated and easy-to-use engineering tool for the rapid deployment of C++ program checkpoint functionality in HPC scenarios. Attached Figure Description

[0015] Figure 1 This is a schematic diagram of the overall process of the present invention; Figure 2 This is a system architecture diagram of the present invention. Detailed Implementation

[0016] The present invention will be further described in detail below with reference to the accompanying drawings and embodiments.

[0017] like Figure 1 As shown, a method for automatically generating checkpoint-oriented serialization code includes the following steps: Step 1: Parse the abstract syntax tree of the target code snippet in the application, extract the type information, scope information and data structure of all local and global variables involved in the target code snippet, and generate a JSON-formatted unified symbol representation; the data structure includes member fields, and the member fields include field name, type, access permission and nesting relationship; Examples of JSON's unified notation are as follows: { "namespace":"<the namespace of the target code, such as gmx>", "entry_function":{ "containing_function_file":"<absolute path to the file containing the entry function>", "containing_function_start_line":"<starting line number of the entry function>", "target_fragment_file":"<path to the file containing the target code fragment>", "target_fragment_start_line":"<fragment start line>", "target_fragment_end_line":"<End line of the fragment>", "header_includes_position":"<header file insertion position line number>" }, "variables":[ { "name":"<variable name>", "base_type":"<basic type, such as int / real / std::array<...>>", "is_array":" <true false>", "array_sizes":"<Array size expression, fill in null for non-arrays>", "is_pointer":" <true false>", "array_dimensions": "<number of dimensions, 0 for scalar>", "namespace": "<namespace to which the type belongs, null if none>" } , "dependencies": { "name": "<unique identifier, format: variable name type name>", "base_name": "<short type name>", "type": "<full type name, including template parameters>", "kind": "<CXXRecord|Typedef|Enum>", "namespace": "<namespace to which it belongs>", "ast_contents": { "name": "<member field name>", "type": "<member type>", "kinds": "<kind of member>", "is_array": " <true false>" } ], "insertion_info":{ "class_definition_file":"<path to the type definition file>", "friend_declarations_range":{"start":0,"end":0}, "forward_declarations_line":0, "header_includes_position":0 }, "actual_struct":"<optional: the underlying actual structure pointed to by typedef>" } ], "total_count":{ "variables":"<total number of variables>", "dependencies": "<Total number of dependencies>" } }

[0018] Step 2: Use the trained large language model to perform data flow analysis and field-level activity analysis on the unified symbolic representation and its corresponding target code snippets to obtain the activity score of each member field, and make pruning decisions on all member fields according to the set activity threshold to generate pruned unified symbolic representations. Among them, the large language model adopts a two-stage training strategy: the pre-training stage learns general semantic representation on a large-scale C++ code library, and the fine-tuning stage optimizes the field activity prediction ability on the labeled checkpoint dataset. The AdamW optimizer and cosine annealing learning rate scheduling strategy are used for training, and the loss function adopted is a combination of binary cross-entropy loss and dependency consistency loss. The large-scale C++ codebase used consists of two parts: a general C++ corpus and an HPC-specific corpus. The general C++ corpus is used to learn the general syntax structure and semantic representation of the C++ language. It is derived from publicly available open-source code datasets and code hosting platforms, including the C++ subset of The Stack open-source code dataset, the C++ portion of the CodeSearchNet corpus, and C++ repositories publicly released on GitHub and GitLab under the MIT, BSD, and Apache-2.0 licenses. After deduplication, removal of binary files, and automatic code generation, this part of the corpus is 50GB of source code and contains 20 billion tokens. The HPC-specific corpus is used to enable the model to learn semantic patterns of complex data structures, template nesting, raw pointers, and dynamic memory management in high-performance computing applications. It is derived from ten open-source HPC scientific computing software programs: OpenFOAM, GROMACS, LAMMPS, SU2, deal.II, MFEM, Trilinos, Kokkos, AMREX, and Eigen. After cleaning and deduplication, this part of the corpus is 8GB of source code and contains 3 billion tokens. The code selection criteria are as follows: First, source files must be written in C++11 or above and be able to successfully compile and generate a complete abstract syntax tree; second, a single repository must have at least 500 stars and have commit records within the past year; third, the source files must be licensed under MIT, BSD, or Apache-2.0; fourth, source files containing template classes, nested structs, structs with raw pointer members, or dynamically allocated arrays will be given priority, while empty files, purely comment files, machine-generated files, and duplicate files with a similarity of more than 90% to other repositories will be excluded.

[0019] The checkpoint dataset used in the fine-tuning phase is constructed as follows: Regarding the annotation criteria, the activity level is determined by whether a member field is reread and used after the checkpoint is restored. Specifically, for a target code segment and its subsequent execution paths, if a member field is read and used on any reachable execution path after the checkpoint, it is marked as active and labeled 1; if the field is only reassigned before being read after the checkpoint, or is not used on any subsequent reachable path, it is marked as inactive and labeled 0. Regarding the annotation method, a combination of automatic annotation using static data flow analysis and manual verification is employed: First, using a static data flow analysis tool based on the Clang / LLVM compiler frontend, a control flow graph and definition-use chain are constructed for each target code segment, and activity variable analysis is performed on each member field after the checkpoint. The system automatically generates initial activity labels. Secondly, for three types of situations where static analysis cannot accurately determine the activity—indirect access via raw pointers, inter-function data flow, and access paths determined only at runtime—personnel with HPC development experience manually review and correct the data based on actual operational patterns and domain knowledge. Simultaneously, for situations where the activity of a field depends on another field, or where a dimension field has a dependency on the pointer array it describes, additional dependency labels are added between fields as a monitoring signal for dependency consistency loss. In terms of data scale, the labeled checkpoint dataset contains 10,000 target code snippets from the aforementioned HPC software and self-built test programs, covering 200,000 labeled member field samples. The ratio of active to inactive samples is 3:7, and the dataset is divided into training, validation, and test sets in an 8:1:1 ratio.

[0020] The loss function used in the fine-tuning phase is a weighted combination of binary cross-entropy loss and dependency consistency loss, denoted as... The binary cross-entropy loss (LBCE) is used to ensure the accuracy of independent predictions for each field, and its calculation formula is: Where N is the number of field samples in a batch, The activity truth label for field i, taking either 0 or 1. The Sigmoid output score represents the predicted activity level of the model; the dependency consistency loss (Ldep) is used to constrain the predictions of dependent field pairs to remain consistent, i.e., when field u depends on field v, and u is active, v must be retained, a penalty is applied. Greater than The formula for calculating the inconsistency is: Where E is the set of labeled dependency field pairs, and |E| is the number of its elements; the weight coefficient λ is set to 0.5. The specific parameters for the two-stage training are set as follows: both the pre-training and fine-tuning stages use the AdamW optimizer, with parameters set to β1=0.9, β2=0.999, and β2=0.999. The weight decay is set to weight_decay=0.01, and a cosine annealing learning rate scheduling strategy with preheating is used. The minimum learning rate is... The maximum sequence length is 1024 tokens, dropout is 0.1, the maximum norm of gradient clipping is 1.0, and all are trained using FP16 mixed precision; the peak learning rate during the pre-training phase is... The warm-up steps are the first 5% of training steps, the batch size is 256, and the training lasts for 10 epochs. Masked language is used to model the objective, learning a general semantic representation on unlabeled C++ code. The peak learning rate during the fine-tuning phase is [missing information]. The warm-up steps are the first 10% of training steps, the batch size is 32, and the training lasts for 5 epochs. The loss function of the above-mentioned LBCE and Ldep combination is used for supervised training on the labeled checkpoint dataset. A small peak learning rate is used in the fine-tuning stage to avoid destroying the general representation learned in the pre-training stage. Cosine annealing scheduling makes the learning rate smoothly decay from the peak to the minimum value after warm-up, so as to achieve fine convergence in the later stage of training and avoid getting trapped in local optima.

[0021] In step 2, the specific steps to obtain the activity score for each member field are as follows: First, the target code fragment and the unified symbol representation are converted into corresponding token sequences (i.e., a whole composed of multiple tokens in sequence) by a token segmenter. Each is then processed through an embedding layer and positional encoding to obtain two independent initial vector representations. Next, these two initial vector representations are input into a multi-layer Transformer encoder, where semantic features are extracted layer by layer through a self-attention mechanism and a feedforward neural network, resulting in independent context vector sequences. The context vector sequence corresponding to the unified symbol representation is used as the query, and the context vector sequence of the target code fragment is used as the key and value. These are then fused through a cross-attention mechanism to generate a target code context vector sequence that incorporates unified symbol information. Next, all reference positions of each member field in the unified symbol representation within the target code fragment are located. The context vectors corresponding to these reference positions are extracted from the target code context vector sequence. All extracted context vectors are pooled, and then combined with the member field type (i.e., the member field type is mapped to a type vector through a type embedding layer and then concatenated with the pooled field-level aggregated vector as input to the output layer). Finally, the output layer calculates the value of each member symbol representation. The activity score of the field, in which the word segmenter is a sub-word segmenter based on the Byte-Pair Encoding (BPE) algorithm, trained with C++ source code, with a vocabulary size of 50,000, is used to segment the input text into tokens and map them to a sequence of integer indices; the embedding layer maps the integer index of each token to a word embedding vector of dimension 768, and the position encoding is also 768-dimensional and added element-wise to the word embedding vector, thus obtaining two independent initial vector representations, each of which is a vector sequence with a length equal to the length of the token sequence and a dimension of 768 for each vector; multi-layer Tr The Transformer encoder has 12 layers, each containing a multi-head self-attention sub-layer and a feedforward neural network sub-layer. The multi-head self-attention sub-layer has 12 attention heads, with a hidden dimension (i.e., context vector dimension) of 768 and a dimension of 64 for each attention head. The intermediate layer of the feedforward neural network sub-layer has a dimension of 3072, and the activation function is GELU. After the target code snippet and the unified symbol representation are each processed by the 12-layer Transformer encoder, they each yield a context vector sequence with a dimension of 768. The pooling operation is mean pooling, which calculates the arithmetic mean of the context vectors corresponding to all reference positions of the member field element by dimension to obtain a field-level aggregated vector.

[0022] In step 2, the specific method for generating the pruned unified symbolic representation is as follows: delete member fields whose activity scores are lower than a preset threshold, retain member fields whose activity scores are equal to or higher than the preset threshold, and generate the pruned unified symbolic representation. In this embodiment, the activity scores are normalized to the [0,1] interval using Sigmoid, and the preset threshold is set to 0.5.

[0023] For example, in the code snippet x = node.a + 3, where node is a structure containing fields a, b, c, etc., in a traditional serialization scheme, the entire node structure would be serialized. However, by performing activity analysis on the code snippet using a large language model, it is found that only field a is actually used (i.e., it participates in the addition operation), while fields b and c are never referenced. The large language model calculates a higher activity score for a and lower activity scores for b and c. Therefore, the pruning decision will remove b and c from the unified symbolic representation, keeping only a, thus generating a simplified serialized structure as the pruned unified symbolic representation.

[0024] Step 3: Traverse all member fields in the pruned unified symbolic representation. If the type of the current member field is a pointer, proceed to step 4; otherwise, proceed to step 5. Step 4: According to the preset naming rules of the pointer dimension table, generate a corresponding pointer dimension table entry for each member field, and generate the corresponding serialization code and deserialization code based on the generated pointer dimension table entries; In step 4, the default naming convention for the pointer dimension table is <instance name>_<structure path>_<pointer member name>_<dimension information>; In step 4, the specific method for generating the corresponding serialization and deserialization code is as follows: During the serialization phase, the value of the pointer dimension table entry is first checked. If the value of the pointer dimension table entry is greater than 0, the dimension information is serialized first, and then the array elements pointed to by the pointers are serialized one by one through a loop. If the value of the pointer dimension table entry is equal to 0, a null marker is serialized to represent a null pointer. During the deserialization phase, the dimension information is first read. If the value of the pointer dimension table entry is greater than 0, memory space of the corresponding size is dynamically allocated. Then, the array elements are deserialized one by one into the allocated memory through a loop, and the pointer is set to the address of that memory. If the value of the pointer dimension table entry is equal to 0, the pointer is set to a null pointer.

[0025] In this embodiment, when multiple instances of the same data structure type have the same pointer member name, the preset naming rule for the pointer dimension table is <instance name>_<outer structure name>_<inner structure name>_<pointer member name>><dimension information>. Each pointer dimension table entry independently records the length of the array pointed to by the corresponding pointer. The default value is 0, which represents a null pointer or a single object. When generating serialization code, the corresponding pointer dimension table entry is found according to the instance name, and the corresponding loop serialization code is generated after reading the dimension information. When generating deserialization code, the corresponding pointer dimension table entry is also found according to the instance name, and the corresponding memory space is dynamically allocated after reading the dimension information. Loop deserialization code is then generated to restore the data to the allocated memory.

[0026] For example, regarding the definition of a data structure: struct node { int *x; int y; }; struct a { node b; int c; }; at, tt; When two instances t and tt exist, the automatically generated pointer dimension table contains two entries, t_a_node_x and tt_a_node_x, corresponding to the pointer member tbx in instance t and the pointer member tt.bx in instance tt, respectively. The default value for each dimension table entry is 0, representing a null pointer or a single object. Users can specify the array length pointed to by the pointer by assigning values ​​to the dimension table. For multi-dimensional pointers, the dimension table can be expanded into a multi-dimensional array to record the size information of each dimension.

[0027] Step 5: If the current member field is of a basic type, serialization is performed directly using the Cereal library's built-in serialization functionality, without generating serialization and deserialization code. If the current member field is of a custom data structure and its nesting relationship is non-nested, serialization and deserialization code conforming to the Cereal library's specifications are generated. If the current member field is of a custom data structure and its nesting relationship is nested, serialization and deserialization code conforming to the Cereal library's specifications are generated separately for each nested member field, and the recursive logic for nested serialization is implemented by the Cereal library itself.

[0028] In this embodiment, the generated serialization code and deserialization code are externally encapsulated with data change detection proxy logic. The data change detection proxy logic is used to independently maintain a runtime hash value for each data object instance to be serialized. The hash value is calculated using the MurmurHash3 algorithm and records the hash state of the data object instance at the last checkpoint execution time. When performing a checkpoint, the hash value of the current data object instance at the current moment is calculated. This hash value is compared with the hash value stored in memory at the previous checkpoint. If they are the same, the execution of the generated serialization code for that object instance is skipped, and only an "unchanged" flag is recorded in the current checkpoint file. If they are different, the generated serialization code is called to perform a complete serialization operation and the complete serialized data is written to the current checkpoint file. At the same time, the hash value stored in memory is updated to the hash value at the current moment. For the first checkpoint, the generated serialization code is directly called to perform a complete serialization operation and the initial hash value is saved. During deserialization, the markers in the current checkpoint file are read. If an "unchanged" marker is encountered, the process traces back along the historical versions of the checkpoint file to locate the most recent checkpoint file that does not have an "unchanged" marker, where the complete serialized data of the object instance is stored. This complete serialized data is read, and the generated deserialization code is called to restore it. If no "unchanged" marker is encountered, the complete serialized data is read from the current checkpoint file, and the generated deserialization code is called to restore the data to the memory object instance. The first checkpoint occurs when the program reaches a preset checkpoint (which can be triggered by a timer, manually, or at a specific code location), at which point the serialization process is executed for the first time to save the state. Since there is no hash value for the "previous" checkpoint, all data must be completely serialized, and the hash value of the current data must be calculated and saved.

[0029] The second and subsequent checkpoints are triggered when the program continues running for a period of time and reaches the checkpoint again. At this time, incremental optimization can be performed using the previously saved hash value.

[0030] The checkpoint process ends when the program terminates normally, encounters an error requiring a restart, or is manually stopped by the user.

[0031] In this embodiment, the method further includes automatically inserting the generated serialization and deserialization code into the target source code file. Specifically, the method involves: first, analyzing the source code file containing the target data structure to identify the location and scope of the class or structure definition; then, determining the insertion location of the serialization code based on the code style and access permissions: for member functions within a class, it is inserted into the public or private area of ​​the class definition; for independent functions, it is inserted into the same namespace after the class definition; finally, the generated serialization code is automatically added at the insertion location, and the necessary cereal library header file inclusion statements are added to the beginning of the file; wherein the indentation format of the inserted code is kept consistent with the original code.

[0032] In this embodiment, an example of converting all active fields of data structure D into a byte stream in sequence is as follows: The order is based on the arrangement of active fields in the pruned unified symbolic representation, which is consistent with the declaration order of member fields in the source code. That is, the active fields arranged in the order of their declarations); Where ∥ represents byte stream concatenation, Representation field The binary representation of .

[0033] The MurmurHash3 algorithm is applied to byte stream B(D), and the calculation process is as follows: Initialization: h = seed (seed value, set to 0x9747b28c), grouping 4 bytes (32 bits) into a single byte stream. : ; / / Circular left shift 15 bits

[0034]

[0035] / / Circular left shift by 13 bits ; After processing the remaining bytes, perform the final mixing: / / len is the total length of the byte stream

[0036]

[0037]

[0038]

[0039] ; Final hash value: H(D) = h; Where the constant is: ; ; .

[0040] like Figure 2 As shown, a checkpoint-oriented automatic serialization code generation system includes: The abstract syntax tree parsing module is used to parse the abstract syntax tree of the target code segment in the application, extract the type information, scope information and data structure of all local and global variables involved in the target code segment, and generate a unified symbol representation. The field pruning module, which embeds the trained large language model, is used to perform data flow analysis and field-level activity analysis on the unified symbolic representation and its corresponding target code snippets. It obtains the activity score of each member field, and makes pruning decisions on all member fields according to the set activity threshold to generate pruned unified symbolic representations. The type traversal module is used to traverse all member fields in the pruned unified symbolic representation. If the type of the current member field is a pointer, the pointer serialization module is executed; if the type of the current member field is not a pointer, the non-pointer serialization module is executed. The pointer serialization module is used to generate corresponding pointer dimension table entries for each member field according to the preset naming rules of the pointer dimension table, and generate corresponding serialization and deserialization code based on the generated pointer dimension table entries; The non-pointer serialization module is used to serialize a member field directly using the Cereal library's built-in serialization functionality if the current member field is a basic type, without generating serialization and deserialization code. If the current member field is a custom data structure and its nesting relationship is non-nested, it generates serialization and deserialization code conforming to the Cereal library specification. If the current member field is a custom data structure and its nesting relationship is nested, it generates separate serialization and deserialization code conforming to the Cereal library specification for each nested member field, with the recursive logic for nested serialization implemented by the Cereal library itself.

[0041] Taking a typical HPC simulation scenario in OpenFOAM as an example: an incompressible solver based on OpenFOAM needs to periodically save checkpoints to enable fault recovery during long-term operation. This solver uses a data structure containing approximately 30 member fields, including the velocity field volVectorField U, the pressure field volScalarField p, the turbulent kinetic energy volScalarField k, the specific dissipation rate volScalarField omega, and the boundary conditions of the mesh.

[0042] In traditional manual implementations, developers need to analyze the composition of each member of a data structure (such as volVectorField). For example, its underlying structure consists of Field and GeometricField template classes, containing multiple members such as internal field values, boundary conditions, and time indices. Developers not only have to manually write serialization statements for each member, but also handle complex dependencies between types, implementing serialization support for each non-standard template parameter of GeometricField. This type of manual work is highly error-prone, and the serialization code needs to be re-maintained if the solver version is upgraded.

[0043] In contrast, the method proposed in this invention utilizes a large language model to perform field-level activity analysis on code snippets. The analysis revealed that among the 30 fields in the aforementioned data structure, only the velocity field U, pressure field p, and turbulent kinetic energy k are actually referenced and require checkpoints in all code paths of the current solver. The remaining fields, such as the specific dissipation rate omega and various boundary condition auxiliary data, are never used during the checkpoint recovery phase. The model assigns higher scores to active fields and classifies redundant fields as inactive. The resulting pruned URI contains only the three necessary fields, reducing the amount of serialized data by approximately 90% compared to the original structure.

[0044] To verify the effectiveness of this invention, the following experiments were conducted: Experimental environment: HPC cluster (Intel Xeon Gold 6248 CPU @ 2.50GHz, 40 cores per node), OpenFOAM v11, test dataset size approximately 10 million grid cells.

[0045] Table 1 Comparison of Development Time

[0046] Conclusion: For HPC applications like OpenFOAM, which have large code volumes and complex class inheritance relationships, the method proposed in this invention significantly reduces the time spent manually analyzing member fields and writing serialization code from more than 30 minutes to about 5 minutes, thus significantly improving development efficiency while ensuring serialization correctness.< / true> < / true> < / true>

Claims

1. A method for automatically generating checkpoint-oriented serialization code, characterized in that... Includes the following steps: Step 1: Parse the abstract syntax tree of the target code snippet in the application, extract the type information, scope information and data structure of all local and global variables involved in the target code snippet, and generate a unified symbol representation; the data structure includes member fields, and the member fields include field name, type, access permission and nesting relationship; Step 2: Use the trained large language model to perform data flow analysis and field-level activity analysis on the unified symbolic representation and its corresponding target code snippets to obtain the activity score of each member field, and make pruning decisions on all member fields according to the set activity threshold to generate pruned unified symbolic representations. Step 3: Traverse all member fields in the pruned unified symbolic representation. If the type of the current member field is a pointer, proceed to step 4; otherwise, proceed to step 5. Step 4: According to the preset naming rules of the pointer dimension table, generate a corresponding pointer dimension table entry for each member field, and generate the corresponding serialization code and deserialization code based on the generated pointer dimension table entries; Step 5: If the current member field is of a basic type, then the Cereal library's own serialization function is used directly for serialization, without generating serialization and deserialization code; If the current member field is of a custom data structure and its nesting relationship is non-nested, then serialization and deserialization code conforming to the Cereal library specification will be generated. If the current member field is a custom data structure and its nesting relationship is nested, then serialization and deserialization code conforming to the Cereal library specification will be generated separately for each nested member field. The recursive logic of nested serialization is implemented by the Cereal library itself.

2. The method for automatically generating checkpoint-oriented serialized code according to claim 1, characterized in that... In step 2, the large language model adopts a two-stage training strategy: the pre-training stage learns a general semantic representation on a large-scale C++ codebase, and the fine-tuning stage optimizes the field activity prediction ability on an annotated checkpoint dataset. The AdamW optimizer and cosine annealing learning rate scheduling strategy are used for training, and the loss function adopted is a combination of binary cross-entropy loss and dependency consistency loss.

3. The method for automatically generating checkpoint-oriented serialized code according to claim 1, characterized in that... In step 2, the specific steps to obtain the activity score for each member field are as follows: First, the target code fragment and the unified symbol representation are converted into corresponding token sequences by a token segmenter. After each token is processed by an embedding layer and positional encoding, two independent initial vector representations are obtained. Then, these two initial vector representations are input into a multi-layer Transformer encoder, which extracts semantic features layer by layer through a self-attention mechanism and a feedforward neural network, resulting in their own independent context vector sequences. The context vector sequence corresponding to the unified symbol representation is used as the query, and the context vector sequence of the target code fragment is used as the key and value. They are then interacted and fused through a cross-attention mechanism to generate a target code context vector sequence that incorporates unified symbol information. Next, all reference positions of each member field in the unified symbol representation in the target code fragment are located. The context vectors corresponding to these reference positions are extracted from the target code context vector sequence. All extracted context vectors are pooled, and combined with the type of the member field, the activity score of each member field is calculated through the output layer.

4. The method for automatically generating checkpoint-oriented serialized code according to claim 1, characterized in that... In step 2, the specific method for generating the pruned unified symbolic representation is as follows: delete member fields whose activity scores are lower than a preset threshold, and retain member fields whose activity scores are equal to or higher than the preset threshold, thereby generating the pruned unified symbolic representation.

5. The method for automatically generating checkpoint-oriented serialized code according to claim 1, characterized in that... In step 4, the default naming convention for the pointer dimension table is <instance name>_<structure path>_<pointer member name>><dimension information>; In step 4, the specific method for generating the corresponding serialization and deserialization code is as follows: During the serialization phase, the value of the pointer dimension table entry is first checked. If the value of the pointer dimension table entry is greater than 0, the dimension information is serialized first, and then the array elements pointed to by the pointer are serialized one by one by looping through the array. If the value of the pointer dimension table entry is equal to 0, an empty tag is serialized to represent a null pointer. During the deserialization stage, the dimension information is read first. If the value of the pointer dimension table entry is greater than 0, the corresponding size of memory space is dynamically allocated. Then, the array elements are deserialized one by one into the allocated memory through a loop, and the pointer is set to the address of that memory. If the value of a pointer dimension table entry is equal to 0, then the pointer is set to a null pointer.

6. The method for automatically generating checkpoint-oriented serialized code according to claim 5, characterized in that... In step 4, when multiple instances of the same data structure type have the same pointer member name, the default naming rule for the pointer dimension table is <instance name>_<outer structure name>_<inner structure name>_<pointer member name>_<dimension information>. Each pointer dimension table entry independently records the length of the array pointed to by the corresponding pointer. The default value is 0, which represents a null pointer or a single object. When generating serialization code, the corresponding pointer dimension table entry is found based on the instance name, and the corresponding loop serialization code is generated after reading the dimension information. When generating deserialization code, the corresponding pointer dimension table entry is also found based on the instance name, and the corresponding memory space is dynamically allocated after reading the dimension information. Loop deserialization code is then generated to restore the data to the allocated memory.

7. The method for automatically generating checkpoint-oriented serialized code according to claim 1, characterized in that... The generated serialization and deserialization code are externally encapsulated with data change detection proxy logic. The data change detection proxy logic is used to independently maintain a runtime hash value for each data object instance to be serialized. The hash value records the hash state of the data object instance at the last checkpoint execution time. When performing a checkpoint, the hash value of the current data object instance at the current moment is calculated. This hash value is compared with the hash value stored in memory at the previous checkpoint. If they are the same, the execution of the generated serialization code for that object instance is skipped, and only an "unchanged" flag is recorded in the current checkpoint file. If they are different, the generated serialization code is called to perform a complete serialization operation and the complete serialized data is written to the current checkpoint file. At the same time, the hash value stored in memory is updated to the hash value at the current moment. For the first checkpoint, the generated serialization code is directly called to perform a complete serialization operation and the initial hash value is saved. During deserialization, the markers in the current checkpoint file are read. If an "unchanged" marker is encountered, the process traces back along the historical versions of the checkpoint file to locate the most recent checkpoint file that does not have an "unchanged" marker, where the complete serialized data of the object instance is stored. This complete serialized data is read, and the generated deserialization code is called to restore it. If no "unchanged" marker is encountered, the complete serialized data is read from the current checkpoint file, and the generated deserialization code is called to restore the data to the memory object instance.

8. The method for automatically generating checkpoint-oriented serialization code according to claim 1, characterized in that... This also includes automatically inserting the generated serialization and deserialization code into the target source code file. Specifically, the process involves: first, analyzing the source code file containing the target data structure to identify the location and scope of the class or struct definition; then, determining the insertion location of the serialization code based on code style and access permissions. For member functions within a class, the code is inserted into the public or private section of the class definition; for independent functions, it is inserted into the same namespace after the class definition. Finally, the generated serialization code is automatically added at the insertion location, and necessary cereal library header file inclusion statements are added to the beginning of the file. The indentation format of the inserted code is kept consistent with the original code.

9. A checkpoint-oriented automatic serialization code generation system, characterized in that... include: The abstract syntax tree parsing module is used to parse the abstract syntax tree of the target code segment in the application, extract the type information, scope information and data structure of all local and global variables involved in the target code segment, and generate a unified symbol representation. The field pruning module, which embeds the trained large language model, is used to perform data flow analysis and field-level activity analysis on the unified symbolic representation and its corresponding target code snippets. It obtains the activity score of each member field, and makes pruning decisions on all member fields according to the set activity threshold to generate pruned unified symbolic representations. The type traversal module is used to traverse all member fields in the pruned unified symbolic representation. If the type of the current member field is a pointer, the pointer serialization module is executed; if the type of the current member field is not a pointer, the non-pointer serialization module is executed. The pointer serialization module is used to generate corresponding pointer dimension table entries for each member field according to the preset naming rules of the pointer dimension table, and generate corresponding serialization and deserialization code based on the generated pointer dimension table entries; The non-pointer serialization module is used to directly serialize the current member field using the Cereal library's own serialization function if the current member field is of a basic type, without generating serialization and deserialization code; If the current member field is of a custom data structure and its nesting relationship is non-nested, then serialization and deserialization code conforming to the Cereal library specification will be generated. If the current member field is a custom data structure and its nesting relationship is nested, then serialization and deserialization code conforming to the Cereal library specification will be generated separately for each nested member field. The recursive logic of nested serialization is implemented by the Cereal library itself.