A logarithmic position encoding method for long sequences

The relative position of sequence elements is dynamically encoded in the Transformer model through the logarithmic position encoding method, which solves the problems of insufficient context capture and generalization ability in long sequence processing in the existing technology, and achieves more efficient long sequence feature understanding and differentiation. Length input adaptability.

CN117995277BActive Publication Date: 2024-08-23YANGZHOU UNIV
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202410173253.2
Authority / Receiving Office
CN · China
Patent Type
Patents(China)
Current Assignee / Owner
Filing Date
2024-02-07
Publication Date
2024-08-23
Estimated Expiration
2044-02-07

AI Technical Summary

Technical Problem

Existing positional encoding technology cannot effectively capture complex contextual relationships when processing long sequences, especially the generalization ability for long-distance dependencies and inputs of different lengths, and simple relative encoding simplifies long-distance relationships into a single expression, limiting the The feature capturing ability of the model.

Method used

The logarithmic position coding method is used to encode relative position information through logarithmic transformation of sequence elements, and a multi-head attention layer is integrated in the Transformer model to dynamically adjust the relationship representation between elements, avoiding the length dependence and simple relativeness of static absolute coding. Coding the long-distance simplification problem.

Benefits of technology

It improves the accuracy and efficiency of the model in long sequence processing, can distinguish different long-distance relationships, and enhances the understanding of long-distance element relationships and the generalization ability of inputs of different lengths.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN117995277B
    Figure CN117995277B
Patent Text Reader

Abstract

The present invention proposes a logarithmic position encoding method suitable for long sequences, comprising the following steps: obtaining long sequence data from a public database and dividing it into a training set and a validation set; constructing a logarithmic position encoding module for locating sequence elements to obtain the logarithmic position encoding of the sequence; constructing a multi-head attention layer that integrates logarithmic position encoding to obtain the attention layer output of the sequence elements; constructing a data encoder based on a custom position encoding module and a multi-head attention layer to encode the sequence data; inputting the training set sequence data into the constructed data encoder model for training, using performance indicators to evaluate the model performance, and retaining the best performing model. While maintaining sensitivity to the relative positions of elements in the sequence, the present invention also allows the model to effectively process long-distance element relationships, thereby improving the accuracy and efficiency of long sequence processing.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] The present invention relates to the fields of deep learning and natural language processing, and in particular to a logarithmic position encoding method suitable for long sequences. Background Art

[0002] In recent years, with the rise of the Transformer model, since the multi-head attention module it uses cannot differentiate the same words in different positions, it is essential to add position encoding to it. In the existing position encoding technology, there are many different position encoding strategies, but there are also some inevitable shortcomings in practical applications. First, using absolute encoding, the word embedding vector is integrated with the absolute position encoding at the model input stage. Such static position encoding only considers the absolute position of each word in the sequence, but does not directly reflect the relative distance between words. This limits the model's ability to handle long-distance dependencies, especially in understanding the complexity of context in long sequences. Second, using absolute encoding to train input sequences of a specific length causes the model to over-adapt to inputs of a specific length, thereby reducing the model's generalization ability to inputs of different lengths. This is particularly evident when dealing with sequences of highly dynamic lengths. Third, when using simple relative encoding to construct relative position expressions, all words whose distance from the central word exceeds the maximum distance threshold are uniformly covered into relative position expressions of words whose distance is the maximum distance threshold. Although simple relative position encoding is effective in dealing with long-distance dependencies, it simplifies all long-distance relationships into a single expression, which limits the model's ability to capture complex sequence features and loses the ability to distinguish different long-distance relationships.

[0003] The invention patent with application number 202111595100.X discloses a relative position encoding method and system. Although this relative position encoding method has a certain effect on long sequence training, it loses consideration of long-distance elements in actual use and cannot capture complex long sequence features. Summary of the invention

[0004] Purpose of the invention: In order to overcome the shortcomings of the background technology, the present invention discloses a logarithmic position encoding method suitable for long sequences. While maintaining sensitivity to the relative positions of elements in the sequence, the method also allows the model to effectively process long-distance element relationships, thereby improving the accuracy and efficiency of long sequence processing.

[0005] Technical solution: The logarithmic position encoding method applicable to long sequences described in the present invention comprises the following steps:

[0006] S1. Obtain long sequence data from the public database and divide it into training set and validation set;

[0007] S2, construct a logarithmic position encoding module for locating sequence elements, and obtain the logarithmic position encoding of the sequence;

[0008] S3. Build a multi-head attention layer that integrates logarithmic position encoding to obtain the attention layer output of the sequence elements;

[0009] S4. Build a data encoder based on a custom position encoding module and a multi-head attention layer to encode the sequence data;

[0010] S5. Input the training set sequence data into the constructed data encoder model for training, use performance indicators to evaluate the model performance, and retain the best performing model.

[0011] Furthermore, the long sequence data in S1 is a long sequence with more than 1000 words.

[0012] Furthermore, the long sequence data in S1 are the sequence data of the new coronavirus with more than 1,000 amino acids, and they are preprocessed.

[0013] Among them, preprocessing includes:

[0014] Only human host-associated sequences were retained;

[0015] Only the spike protein part of the coronavirus protein sequence is selected;

[0016] Screen out spike protein sequences with a length of less than 1000 amino acid residues;

[0017] De-duplicate protein sequences;

[0018] Sequences with more than ten consecutive amino acid mutations were removed.

[0019] Furthermore, in S2:

[0020] The relative position information between elements is encoded by logarithmic transformation of sequence element index. n ), whose logarithmic position code is a ij K Defined as:

[0021]

[0022] Among them, W K is a set of learnable weight vectors, k is a custom constant, log k represents the logarithm with base k, and |ji| represents the element x i and x j The distance in the sequence, when i=j, that is, the distance between an element and itself is 0, the logarithmic position encoding is simplified to Similarly, the logarithmic position encoding a ij V Similar to a ij K The definition of is associated with different model components, keys K and values ​​V, and uses different weight vectors.

[0023] Furthermore, in S3:

[0024] The multi-head attention layer assigns data to each head and assigns attention scores to the data according to the logarithmic position of the data in the data sequence. Similarly, for the sequence x = (x1, x2, ..., x n ), using logarithmic position encoding a ij K Instead of a simple relative encoding, the attention score e is calculated ij , the expression is:

[0025]

[0026] Among them, W Q and W K are the weight matrices of query Q and key K respectively. In addition, a ij K is the element x i and x j The logarithmic position encoding between reflects the relative position information of the elements in the sequence, d z is a constant used to scale the result of the dot product to prevent the gradient from vanishing or exploding;

[0027] Based on element x i and x j The similarity score e between ij , further calculate each element x i With other elements x j The attention weight α between ij , attention weight α ij is obtained by applying the softmax function to e ij After normalization, the expression is:

[0028]

[0029] Combined with the calculated attention weight α ij and the logarithmic positional encoding value a ij V To get each head for each element x in the sequence i The output z i , the output represents z iIt depends not only on the attention weight of the corresponding element, but also on the weighted contribution of all other elements. The expression is:

[0030]

[0031] Where W V is the weight matrix of value V, a ij V Represents element x i and x j The logarithmic position encoding between ij K Similarly, it is used to adjust the sequence element x j Contribution

[0032] Each head of the multi-head attention calculates its own output z i , after the multi-head attention mechanism is completed, the output z of all heads i In order to combine the multi-dimensional information of multi-head attention into a unified representation, the spliced ​​output is linearly transformed through a fully connected layer, and the weight matrix and bias are used to transform the data, and finally the output z of the attention layer is obtained. out .

[0033] Furthermore, in S4:

[0034] In the training set and validation set, the sequence data is first characterized and converted into a vector form acceptable to the model, and then passed to the multi-head attention layer. After the multi-head self-attention layer is instantiated, the output is X: [B, L, D], where B represents the custom batch size, L represents the sequence length, and D represents the hidden layer dimension of the sequence.

[0035] In the model architecture, the sequence data passes through two encoding layers in turn. Each encoding layer consists of a multi-head attention layer and a feed-forward neural network with ReLU activation function. After each encoding layer, layer normalization operation is performed to stabilize the learning process, and finally outputs an encoded tensor E with the same dimension as the input X, retaining the batch size B, sequence length L and hidden layer dimension D of the input sequence.

[0036] Furthermore, in S5:

[0037] In the early stage of model training, the training and validation data sets are randomly shuffled to prevent the model from learning a specific ordering of the data and use the data loader to generate large training and validation data to enhance the generalization ability of the model; sparse classification cross entropy is used as the loss function, and SGD is used as the optimizer to train the entire model. The custom metric callback function uses sparse classification accuracy, precision, recall, F1 index, and Matthews correlation coefficient performance indicators to monitor the performance on the validation set.

[0038] Beneficial effects: Compared with the prior art, the advantages of the present invention are:

[0039] (1) Encoding by logarithmic transformation of sequence element index can more effectively capture the relative position relationship between words. Compared with static absolute position encoding, logarithmic position encoding can distinguish different relative distances through its mathematical properties instead of just considering absolute position. Such an encoding strategy can provide rich information for understanding dependencies in long sequences, especially when the context is complex.

[0040] (2) The logarithmic position encoding used to encode the distance between elements is dynamic and does not depend on the specific length of the sequence like the static absolute position encoding. That is, when the length changes, the model is no longer applicable. However, the logarithmic position encoding can adapt to inputs of different lengths even when the length of the sequence changes during training, thereby improving the generalization ability of the model when processing inputs of different lengths;

[0041] (3) Logarithmic position encoding avoids the problem of treating all words beyond the maximum distance threshold uniformly through its transformation method. Unlike simple relative position encoding, logarithmic position encoding can assign different position representations to words beyond a certain distance threshold, thereby allowing the model to distinguish more distant relationships and capture complex features in the sequence, while maintaining the ability to identify different long-distance relationships in long sequences. BRIEF DESCRIPTION OF THE DRAWINGS

[0042] Figure 1 This is a flowchart for preprocessing the novel coronavirus sequence data;

[0043] Figure 2 It is a schematic diagram of the calculation formula of the logarithmic position encoding module;

[0044] Figure 3 Insert position map for log position encoding in self-attention mechanism;

[0045] Figure 4 The figure is a flow chart of the logarithmic position encoding method applicable to long sequences of the present invention. DETAILED DESCRIPTION

[0046] The following is a detailed description in conjunction with specific embodiments and the accompanying drawings.

[0047] The logarithmic position encoding method of the present invention is suitable for long sequences, based on the Transformer model, referring to Figure 1-4 , including the following steps:

[0048] Step 1: Obtain long sequences with a vocabulary of more than 1,000 words from public databases, such as the sequence data of the new coronavirus with more than 1,000 amino acids, and preprocess them to divide them into training sets and validation sets;

[0049] Preprocess the downloaded novel coronavirus sequence data. The specific preprocessing process is as follows: Figure 1 As shown, it includes: focusing on studying the characteristics of the new coronavirus and the human immune system, and only retaining sequences related to the human host; the spike protein is the key protein for the virus to enter the host cell, and only the spike protein part of the new coronavirus protein sequence is selected; sequences with a length of less than 1000 amino acid residues are screened out, and shorter protein sequences cannot contain enough information and are difficult to conduct effective research and analysis; protein sequences are deduplicated; protein sequences with more than ten amino acid mutations do not conform to basic biological assumptions, and sequences with more than ten consecutive amino acid mutations are removed, and finally divided into training set and validation set in an 8:2 ratio.

[0050] Step 2: Build a logarithmic position encoding module for locating sequence elements and obtain the logarithmic position encoding of the sequence;

[0051] The relative position information between elements is encoded by logarithmic transformation of sequence element index. n ), whose logarithmic position code is a ij K Can be defined as:

[0052]

[0053] Among them, W K is a set of learnable weight vectors, k is a custom constant, log k represents the logarithm with base k, and |ji| represents the element x i and x j The distance in the sequence. When i=j, that is, the distance between an element and itself is 0, the logarithmic position encoding is simplified to

[0054] like Figure 2 As shown, compared with the relative position encoding a ij K , which is expressed as:

[0055]

[0056] Among them, W K is a set of learnable weight vectors, k is the custom maximum element distance (usually 2), log k represents the logarithm with base k, and |ji| represents the element xi and x j The distance in the sequence. The relative position uniformly encodes the long-distance relative position as This limits the model's ability to handle long-distance dependencies;

[0057] Similarly, the logarithmic position encoding a ij V Similar to a ij K The definitions of are associated with different model components (keys K and values ​​V) and use different weight vectors.

[0058] Step 3: Build a multi-head attention layer that integrates logarithmic position encoding and obtain the attention layer output of the sequence elements, such as Figure 3 The output shown is the attention score e at different positions ij , attention weight a ij , each head is each element x in the sequence i The output z i ;

[0059] The multi-head attention layer assigns data to each head and assigns attention scores to the data according to the logarithmic position of the data in the data sequence. Similarly, for the sequence x = (x1, x2, ..., x n ), using logarithmic position encoding a ij K Instead of a simple relative encoding, the attention score e is calculated ij , the expression is:

[0060]

[0061] Among them, W Q and W K are the weight matrices of query Q and key K respectively. In addition, a ij K is the element x i and x j The logarithmic position encoding between reflects the relative position information of the elements in the sequence. z is a constant used to scale the result of the dot product to prevent the gradient from vanishing or exploding;

[0062] Based on element x i and x j The similarity score e between ij , further calculate each element x i With other elements x j The attention weight α between ij The attention weight α ij is obtained by applying the softmax function to e ijAfter normalization, the expression is:

[0063]

[0064] Combined with the calculated attention weight a ij and the logarithmic positional encoding value a ij V To get each head for each element x in the sequence i The output z i The output represents z i It depends not only on the attention weight of the corresponding element, but also on the weighted contribution of all other elements. The expression is:

[0065]

[0066] Where W V is the weight matrix of value V, a ij V Represents element x i and x j The logarithmic position encoding between ij K Similarly, it is used to adjust the sequence element x j Contribution

[0067] Each head of the multi-head attention calculates its own output z i , after the multi-head attention mechanism is completed, the output z of all heads i are concatenated together. If there are h heads, the concatenated output is expressed as: z = [z1; z2; ...; z h ], in order to merge the multi-dimensional information of multi-head attention into a unified representation, the concatenated output is linearly transformed through a fully connected layer, and the weight matrix and bias are used to transform the data, and finally the output z of the attention layer is obtained out , the expression is: out = zW O , where W o A weight matrix representing a linear transformation.

[0068] Step 4: Build a data encoder based on the custom position encoding module and multi-head attention layer to encode the sequence data;

[0069] In the training set and validation set, the sequence data is first featurized and converted into a vector form acceptable to the model, and then passed to the multi-head attention layer. After the multi-head self-attention layer is instantiated, the output is X: [B, L, D], where B represents the custom batch size, L represents the sequence length, and D represents the hidden layer dimension of the sequence.

[0070] In order to reduce the risk of overfitting during training, we adopted a dropout strategy. In the model architecture, the sequence data passes through two encoding layers in turn, each of which consists of a multi-head attention layer and a feed-forward neural network (FFNN) with ReLU activation function. After each encoding layer, a layer normalization operation is performed to stabilize the learning process, and finally an encoded tensor E with the same dimension as the input X is output, retaining the batch size B, sequence length L and hidden layer dimension D of the input sequence.

[0071] Step 5: Input the training set sequence data into the constructed data encoder model for training, use performance indicators to evaluate the model performance, and retain the best performing model;

[0072] In the early stage of model training, the training and validation data sets are randomly shuffled to prevent the model from learning a specific ordering of the data and using the data loader to generate large training and validation data to enhance the generalization ability of the model. Sparse classification cross entropy is used as the loss function, and SGD is used as the optimizer to train the entire model. The custom metric callback function uses sparse classification accuracy, precision, recall, F1 index, and Matthews correlation coefficient performance indicators to monitor the performance on the validation set.

Claims

1. A logarithmic position encoding method suitable for long sequences, characterized in that: The following steps are involved: S1. Obtain long sequence data from the public database and divide it into training set and validation set; S2, construct a logarithmic position encoding module for locating sequence elements, and obtain the logarithmic position encoding of the sequence; S3. Build a multi-head attention layer that integrates logarithmic position encoding to obtain the attention layer output of the sequence elements; S4. Build a data encoder based on a custom position encoding module and a multi-head attention layer to encode the sequence data; S5. Input the training set sequence data into the constructed data encoder model for training, use performance indicators to evaluate the model performance, and retain the best performing model; In S2: The relative position information between elements is encoded by logarithmic transformation of sequence element index. n ), whose logarithmic position code is a ij K Defined as: Among them, W K is a set of learnable weight vectors, k is a custom constant, log l represents the logarithm with base k, and |ji| represents the element x i and x j The distance in the sequence, when i=j, that is, the distance between an element and itself is 0, the logarithmic position encoding is simplified to W1 K ; Similarly, the logarithmic position encoding a ij V Similar to a ij K The definition of is associated with different model components, keys K and values ​​V, and uses different weight vectors; In the S3: The multi-head attention layer assigns data to each head and assigns attention scores to the data according to the logarithmic position of the data in the data sequence. Similarly, for the sequence x = (x1, x2, ..., x n ), using logarithmic position encoding a ij K Instead of a simple relative encoding, the attention score e is calculated ij , the expression is: Among them, W Q and W K are the weight matrices of query Q and key K respectively. In addition, a ij K is the element x i and x j The logarithmic position encoding between reflects the relative position information of the elements in the sequence, d z is a constant used to scale the result of the dot product to prevent the gradient from vanishing or exploding; Based on element x i and x j The similarity score e between ij , further calculate each element x i With other elements x j The attention weight α between ij , attention weight α ij is obtained by applying the softmax function to e ij After normalization, the expression is: Combined with the calculated attention weight α ij and the logarithmic positional encoding value a ij V To get each head for each element x in the sequence i The output z i , the output represents z i It depends not only on the attention weight of the corresponding element, but also on the weighted contribution of all other elements. The expression is: Where W V is the weight matrix of value V, a ij V Represents element x i and x j The logarithmic position encoding between ij K Similarly, it is used to adjust the sequence element x j Contribution Each head of the multi-head attention calculates its own output z i , after the multi-head attention mechanism is completed, the output z of all heads i In order to combine the multi-dimensional information of multi-head attention into a unified representation, the spliced ​​output is linearly transformed through a fully connected layer, and the weight matrix and bias are used to transform the data, and finally the output z of the attention layer is obtained. out ; In S4: In the training set and validation set, the sequence data is first characterized and converted into a vector form acceptable to the model, and then passed to the multi-head attention layer. After the multi-head self-attention layer is instantiated, the output is X: [B, L, D], where B represents the custom batch size, L represents the sequence length, and D represents the hidden layer dimension of the sequence. In the model architecture, the sequence data passes through two encoding layers in sequence. Each encoding layer consists of a multi-head attention layer and a feed-forward neural network with ReLU activation function. After each encoding layer, layer normalization operation is performed to stabilize the learning process, and finally outputs an encoded tensor E with the same dimension as the input X, retaining the batch size B, sequence length L and hidden layer dimension D of the input sequence; In S5: In the early stage of model training, the training and validation data sets are randomly shuffled to prevent the model from learning a specific ordering of the data and using the data loader to generate large training and validation data to enhance the generalization ability of the model; sparse classification cross entropy is used as the loss function, and SGD is used as the optimizer to train the entire model. The custom metric callback function uses sparse classification accuracy, precision, recall, F1 index, and Matthews correlation coefficient performance indicators to monitor the performance on the validation set; The long sequence data in S1 is the sequence data of the new coronavirus with more than 1,000 amino acids, and it is preprocessed; the preprocessing includes: Only human host-associated sequences were retained; Only the spike protein part of the coronavirus protein sequence is selected; Screen out spike protein sequences with a length of less than 1000 amino acid residues; De-duplicate protein sequences; Sequences with more than ten consecutive amino acid mutations were removed.

2. The logarithmic position encoding method for long sequences according to claim 1, characterized in that: The long sequence data in S1 is a long sequence with more than 1000 words.