A method, system, device and readable storage medium for defending against text attacks based on part-of-speech masking strategy

Through the combination of part-of-speech-based masking strategy and purifier, the problem of noise introduced by random masks in the pre-training stage of the BERT model is solved, the model's defense capability and training effect against text attacks are improved, and effective defense against text attacks is achieved.

CN117829147BActive Publication Date: 2024-08-23BEIJING XINSHU TECH CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202410016109.8
Authority / Receiving Office
CN · China
Patent Type
Patents(China)
Current Assignee / Owner
Filing Date
2024-01-04
Publication Date
2024-08-23
Estimated Expiration
2044-01-04

AI Technical Summary

Technical Problem

The random masking method of the BERT model in the pre-training stage introduces noise, resulting in large data noise, which affects the training effect of the model and its defense ability against text attacks.

Method used

Adopt a masking strategy based on part-of-speech, judge the masking probability based on part-of-speech through word segmentation and part-of-speech tagging, use the purifier to re-predict the masked segmented words, and build a model through the PyTorch framework for cross-entropy loss function training, combined with the Softmax function to calculate confidence degree, generating the most likely word as a prediction result.

Benefits of technology

It improves the model's defense capability against text attacks, reduces data noise, improves the model's training effect and accuracy on clean samples, and balances the accuracy of clean samples and the success rate of adversarial defense.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN117829147B
    Figure CN117829147B
Patent Text Reader

Abstract

The present invention provides a method, system, device and readable storage medium for defending against text attacks based on a masking strategy based on part of speech, and improves the calculation method of soft embedding, so that the purifier can successfully re-predict the segmented words that have been masked. The masker and the purifier form a defense framework against text attacks. The masker replaces a certain proportion of words in the input text with [MASK] to generate multiple mask copies. The purifier uses the Softmax function to calculate the probability distribution of different words at each position, and outputs the most likely word as the prediction result. The whole process achieves a good balance between the accuracy of clean samples and the success rate of adversarial defense.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] The present invention relates to a masking strategy based on part of speech and a defense method, system, device and readable storage medium against text attacks, belonging to the field of data security protection. Background Art

[0002] BERT (Bidirectional Encoder Representations from Transformers) is a bidirectional encoder based on Transformer. The model can better understand text through bidirectional context information. It is pre-trained on a large number of unlabeled corpora and learns language representation by predicting vocabulary in the context. The model provides powerful language representation capabilities and performs well in natural language processing tasks such as sentiment analysis, text classification, and question answering. Because it uses Transformer for modeling, BERT can handle variable-length input text and capture long-term dependencies between words.

[0003] The construction of the BERT model is usually divided into two stages: pre-training and fine-tuning. The pre-training stage uses a large-scale unlabeled corpus to train the language representation learning of the BERT model by performing two parallel tasks: first, through the language masking model (MLM), random vocabulary masking is performed on the input sentence, and the masked words are tried to be predicted, so as to learn the semantic and syntactic information of the vocabulary in the context; second, through the next sentence prediction model (NSP), a pair of sentences is received as input and whether the two sentences are continuous is predicted, so as to learn the correlation between sentences in the text. This training method enables the BERT model to obtain a more comprehensive language representation, including vocabulary, syntax and context information.

[0004] The BERT model uses random masking for pre-training, randomly selecting some words for masking and replacing them with a special [MASK] symbol. However, this random masking method introduces some noise because not all words need to be masked. BRIEF DESCRIPTION OF THE DRAWINGS

[0005] Figure 1 This is the structure diagram of the purifier. Summary of the invention

[0006] In order to solve the problems existing in the prior art, the present invention proposes a masking strategy based on part of speech and a defense method against text attacks. The specific steps of the method are as follows:

[0007] (1) Segment and tag the input text. Use the spaCy library to segment English words and decompose the text into individual words or symbols. Then use the spaCy tagger to tag each segmentation result and determine the part of speech category of each word or symbol.

[0008] (2) Determine the masking probability based on the part of speech, use the part of speech based masker to perform masking, and use the purifier to successfully re-predict the masked segmented words;

[0009] (3) The model is built using the PyTorch framework, with the masked input text as input and the target word as output for training. The model is continuously trained and optimized using the cross-entropy loss function until the model converges or reaches the preset number of training rounds. After each training round, the mask and model training process is repeated to obtain the final BERT-MLM model.

[0010] Furthermore, in step (2), nouns, verbs, adjectives and adverbs are masked with different probabilities, the masking probabilities are calculated, and training is performed.

[0011] Furthermore, in step (2), the purifier predicts masked words using the BERT-based part-of-speech language masking model and restores clean words in turn. i is the mask segmentation word w i The importance score of the masked part is calculated to enable the model to better understand the information of the masked part and improve the efficiency of data utilization. in Represents the segmentation word w i The mask probability, w m are all the masked tokens in the current mask copy, J is the loss function of the target model f, x is the input text, and f represents the target model.

[0012] Furthermore, the purifier calculates z based on the Softmax function i = The confidence level of w is where g i is the noise sampled from the Gumbel distribution, g i =-log(-log(u i )),u i is a random number uniformly sampled from the interval [0,1, h i ∈H s , H s =(h1,h2,...,h L ) is the final output of the BERT-MLM model, W c and b is the hidden state h i The weights and biases of ; the purifier finally outputs the purified sample if is a mask word [MASK], then otherwise, After a complete purification operation, n reconstructed samples X are generated. r =R(X m ).

[0013] The present invention further proposes a masking strategy based on part of speech and a defense system against text attacks, the system comprising:

[0014] (1) A preprocessing module, which performs word segmentation and part-of-speech tagging on the input text. The spaCy library is used to perform English word segmentation, breaking the text into individual words or symbols. The spaCy tagger is then used to perform part-of-speech tagging on each word segmentation result to determine the part-of-speech category of each word or symbol.

[0015] (2) Masking and purification module, which determines the masking probability according to the part-of-speech, uses the part-of-speech based masker to perform masking, and uses the purifier to successfully re-predict the masked segmented words;

[0016] (3) Model training module: This module uses the PyTorch framework to build a model, takes the masked input text as input, and trains the target words as output. It uses the cross-entropy loss function to continuously train and optimize the model until the model converges or reaches the preset number of training rounds. After each training round, the mask and model training process is repeated to obtain the final BERT-MLM model.

[0017] Furthermore, in the preprocessing module, nouns, verbs, adjectives and adverbs are masked with different probabilities, the masking probabilities are calculated, and training is performed.

[0018] Furthermore, in the masking and purification processing module, the purifier uses the BERT-based part-of-speech language masking model to predict masked words and restore clean words in turn. i is the mask segmentation word w i The importance score of the masked part is calculated to enable the model to better understand the information of the masked part and improve the efficiency of data utilization. in Represents the segmentation word w i The mask probability, w m are all the masked tokens in the current mask copy, J is the loss function of the target model f, x is the input text, and f represents the target model.

[0019] Furthermore, the purifier calculates z based on the Softmax function i = The confidence level of w is where g i is the noise sampled from the Gumbel distribution, g i =-log(-log(u i )),u i is a random number uniformly sampled from the interval [0,1, h i ∈H s , H s =(h1,h2,...,h L ) is the final output of the BERT-MLM model, W c and b is the hidden state h i The weights and biases of ; the purifier finally outputs the purified sample if is a mask word [MASK], then otherwise, After a complete purification operation, n reconstructed samples X are generated. r =R(X m ).

[0020] The present invention also provides a device, which includes: a data acquisition device, a processor and a memory; the data acquisition device is used to collect data; the memory is used to store one or more program instructions; the processor is used to execute one or more program instructions to execute any of the above methods.

[0021] The present invention further provides a computer-readable storage medium, wherein the computer storage medium contains one or more program instructions, and the one or more program instructions are used to execute any of the above methods.

[0022] The present invention proposes a masking strategy based on part of speech and improves the calculation method of soft embedding, so that the purifier can successfully re-predict the segmented words that have been masked. The masker and the purifier form a defense framework against text attacks. The masker replaces a certain proportion of words in the input text with [MASK] to generate multiple masked copies. The purifier uses the Softmax function to calculate the probability distribution of different words at each position and outputs the most likely word as the prediction result. The whole process achieves a good balance between the accuracy of clean samples and the success rate of adversarial defense. DETAILED DESCRIPTION

[0023] To address this problem, after spaCy completes word segmentation and part-of-speech tagging, the present invention proposes a part-of-speech-based masking strategy. According to the probability of occurrence of words of different parts of speech in the four more critical parts of speech, nouns, verbs, adjectives and adverbs, these four parts of speech are masked with probabilities of 0.1, 0.2, 0.3 and 0.4 respectively. The masking probability is calculated according to this masking rule, and training is performed. The part-of-speech-based masking strategy can more accurately focus on the parts of speech that have an important impact on the task, and when the text data contains a large number of words that are irrelevant to the task, it can increase the probability of masking these words, reduce data noise, and improve the model training effect.

[0024] The masking strategy based on part of speech sets masking strategies with different probabilities according to the meaning and importance of words of different parts of speech in the sentence. Nouns and verbs can usually express important information in the sentence and carry the main meaning and action of the sentence. Therefore, the masking probability of nouns and verbs is set lower to reduce the possibility of these words being masked, thereby retaining more semantic information. Adjectives and adverbs are usually used to modify nouns or verbs to provide more details or degree information. Therefore, the masking of these words has a relatively small impact on the performance of the model. The masking probability of adjectives and adverbs is appropriately increased to increase the generalization ability of the model, forcing the model to rely more on contextual information to infer the masked words.

[0025] First, the input text is segmented and POS tagged. The spaCy library is used for English word segmentation to decompose the text into individual words or symbols. For example, the sentence "The cat sat on the mat" will be segmented into ["The", "cat", "sat", "on", "the", "mat"]; further, the spaCy tagger is used for part-of-speech tagging. Each segmentation result is POS tagged to determine the part-of-speech category of each word. The tagging result of the sentence can get "cat" is a noun, "sat" is a verb, "on" and "the" are prepositions, and "mat" is a noun; the masking probability is determined according to the part-of-speech. The masking strategy based on part-of-speech masks nouns or verbs with a probability of 0.1 or 0.2. If the part of speech of the word is an adjective or adverb, it is masked with a probability of 0.3 or 0.4. According to this masking rule, the probability of "cat" being masked as [MASK] is Pr['cat'] = 0.1 / (0.1*2+0.2) = 0.25. In this example, the words to be masked are randomly selected with a certain probability, and the masked text may be "The[MASK][MASK]on the mat". The model is built using the PyTorch framework, and the masked input text is used as input and the target word is used as the label for training. The model is continuously trained through the cross entropy loss function and optimization until the model converges or reaches the preset number of training rounds. After each training round, the process of text masking and model training is repeated to continuously adjust and optimize the model. The final BERT-MLM model is obtained.

[0026] Aiming at the part-of-speech based masking strategy, an improved mask-based purifier is proposed. Since masking also affects the clean text when eliminating disturbances with high probability, the clean samples are likely to lose their original semantics after being masked, resulting in misprediction. Therefore, after masking, the unknown parts need to be restored to ensure that the prediction accuracy of the target model is not affected. The improved purifier uses the BERT-based part-of-speech language masking model to predict masked words and restore the clean words in turn. Since the masking probabilities of words of different parts of speech are different in the part-of-speech based masking strategy, a new soft embedding is used to improve the restoration rate of clean words. The soft embedding is equal to the weighted sum of the original embedding and the masked embedding, and its weight is determined by the importance score and masking probability of the masked segmented word. Each masked segmented word w i The soft embedding is defined as:

[0027]

[0028] Among them, e mask is the embedding vector of the mask word [MASK], Yes i The embedding vector, w iis the masked segmentation word. i Yes i The importance score of in Represents the segmentation word w i The mask probability, w m are all the masked tokens in the current mask copy, J is the loss function of the target model f. The larger the value, the greater the w i The more important it is, the greater the probability of being disturbed in an attack. The larger the p i The bigger, The closer to e mask , the purifier has a greater probability of correcting it to a clean word; The smaller the p i The smaller, The closer More semantics before masking are retained, and the purifier is more inclined to predict it as w i Similar words or restore to w i .

[0029] A more specific example:

[0030] See the structure diagram of the purifier Figure 1 The defense framework against text attacks is composed of a masker and a purifier. The masker takes a certain proportion of the input text for masking. This process replaces k words in the input text x with [MASK] and generates n masked copies. The set of masked copies of x is X m =M(x,H(L,k,n)), where L is the number of words in x that are masked, and k = [μ×L], μ is the text masking rate, and the set H(L,k,n) will randomly sample k non-repeating elements from [1,L], and the probability of each element being selected will be related to the masking probability of the corresponding position segmentation word. M(x,H) generates n masked copies of x from the elements of the n sets in H For example, x = {The,cat,sat,on,the,mat}, H(6,2) = 2,3, then x m ={The,[MASK],[MASK],on,the,mat},

[0031] The input of the purifier is in Represents the i-th word after masking, and the output is a segmented word sequence x z =(z1,z2,...,z L ). Assuming that the i-th segmentation word is not masked, the input embedding otherwise These embedding vectors are obtained from the pre-trained BERT model. Then the output of the purifier at the i-th position is z i = argmax w∈V (P c (z i =w|x)), where V is the list of predicted candidate words. The purifier uses the Softmax function to calculate z i = The confidence level of w is where h i ∈H s , H s =(h1,h2,...,h L ) is the final output of the BERT-MLM model. W c and b is the hidden state h i The purifier finally outputs the purified sample if is a mask word [MASK], then otherwise, A complete purification operation generates n reconstructed samples X r =R(X m ).

[0032] The purifier is a sequence-to-sequence model architecture that performs multi-classification tasks. This means that for each sample, the purifier can predict multiple [MASK] tags with just one implementation. Its training process mainly includes two steps: first, construct training data with masked samples as input and original samples as output; then, the pre-trained model BERT-MLM is retrained. In addition, the soft embedding method reduces the problem of low clean word restoration caused by multi-mask input, thereby improving the accuracy of the prediction task.

[0033] This paper innovatively proposes a masking strategy based on part of speech and improves the calculation method of soft embedding, so that the purifier can successfully re-predict the segmented words that have been masked. The masker and the purifier form a defense framework against text attacks. The masker replaces a certain proportion of words in the input text with [MASK] to generate multiple masked copies. The purifier uses the Softmax function to calculate the probability distribution of different words at each position and outputs the most likely word as the prediction result. The whole process achieves a good balance between the accuracy of clean samples and the success rate of adversarial defense.

[0034] The present invention also provides a device, which includes: a data acquisition device, a processor and a memory; the data acquisition device is used to collect data; the memory is used to store one or more program instructions; the processor is used to execute one or more program instructions to execute any of the above methods.

[0035] The present invention further provides a computer-readable storage medium, wherein the computer storage medium contains one or more program instructions, and the one or more program instructions are used to execute any of the above methods.

[0036] The units, devices or modules described in the above embodiments can be implemented by computer chips or entities, or by products with certain functions. For the convenience of description, the above devices are described separately by functions divided into various modules. Of course, when implementing this application, the functions of each module can be implemented in the same or more software and / or hardware, or the modules that implement the same function can be implemented by a combination of multiple sub-modules or sub-units. The device embodiments described above are only schematic. For example, the division of the units is only a logical function division. There may be other division methods in actual implementation, such as multiple units or components can be combined or integrated into another system, or some features can be ignored or not executed. Another point is that the coupling or direct coupling or communication connection between each other shown or discussed can be through some interfaces, indirect coupling or communication connection of devices or units, which can be electrical, mechanical or other forms.

[0037] Those skilled in the art also know that, in addition to implementing the controller in a purely computer-readable program code, the controller can be made to implement the same function in the form of logic gates, switches, application-specific integrated circuits, programmable logic controllers, and embedded microcontrollers by logically programming the method steps. Therefore, such a controller can be considered as a hardware component, and the devices for implementing various functions included therein can also be considered as structures within the hardware component. Or even, the devices for implementing various functions can be considered as both software modules for implementing the method and structures within the hardware component.

[0038] The present application may be described in the general context of computer-executable instructions executed by a computer, such as program modules. Generally, program modules include routines, programs, objects, components, data structures, classes, etc. that perform specific tasks or implement specific abstract data types. The present application may also be practiced in distributed computing environments where tasks are performed by remote processing devices connected through a communication network. In a distributed computing environment, program modules may be located in local and remote computer storage media, including storage devices.

[0039] It can be known from the description of the above implementation methods that those skilled in the art can clearly understand that the present application can be implemented by means of software plus a necessary general hardware platform. Based on such an understanding, the technical solution of the present application can be essentially or partly contributed to the prior art in the form of a software product, which can be stored in a storage medium such as ROM / RAM, a magnetic disk, an optical disk, etc., and includes several instructions for enabling a computer device (which can be a personal computer, a mobile terminal, a server, or a network device, etc.) to execute the methods described in the various embodiments of the present application or certain parts of the embodiments.

[0040] The various embodiments in this specification are described in a progressive manner, and the same or similar parts between the various embodiments can be referred to each other, and each embodiment focuses on the differences from other embodiments. The present application can be used in many general or special computer system environments or configurations. For example: personal computers, server computers, handheld devices or portable devices, tablet devices, multi-processor systems, microprocessor-based systems, set-top boxes, programmable electronic devices, network PCs, minicomputers, mainframe computers, distributed computing environments including any of the above systems or devices, etc.

[0041] The specific embodiments described above further illustrate the purpose, technical solutions and beneficial effects of the present application. It should be understood that the above description is only a specific embodiment of the present application and is not intended to limit the scope of protection of the present application. Any modifications, equivalent substitutions, improvements, etc. made within the spirit and principles of the present application should be included in the scope of protection of the present application.

Claims

1. A masking strategy based on part of speech and a defense method against text attacks, characterized by: The specific steps of this method are as follows: (1) Segment and tag the input text. Use the spaCy library to segment English words and decompose the text into individual words or symbols. Then use the spaCy tagger to tag each segmentation result and determine the part of speech category of each word or symbol. (2) Determine the masking probability based on the part of speech, use the part of speech based masker to perform masking, and use the purifier to successfully re-predict the masked segmented words; (3) Use the PyTorch framework to build a model, take the masked input text as input, and the target word as output for training; use the cross entropy loss function to continuously train and optimize the model until the model converges or reaches the preset number of training rounds; After each training round, the mask and model training process is repeated to obtain the final BERT-MLM model; In step (2), the purifier uses the BERT-based part-of-speech language masking model to predict masked words and restore clean words in turn. i is the mask segmentation word w i The importance score of the masked part is calculated to enable the model to better understand the information of the masked part and improve the efficiency of data utilization. in Represents the segmentation word w i The mask probability, w m are all the masked tokens in the current mask copy, J is the loss function of the target model f, x is the input text, and f represents the target model.

2. The method for defending against text attacks based on part-of-speech masking strategy according to claim 1, characterized in that: In step (2), nouns, verbs, adjectives and adverbs are masked with different probabilities, the masking probabilities are calculated, and training is performed.

3. The method for defending against text attacks based on part-of-speech masking strategy according to claim 1, characterized in that: In step (2), the purifier calculates z based on the Softmax function i = The confidence level of w is where g i is the noise sampled from the Gumbel distribution, g i =-log(-log(u i )),u i is a random number uniformly sampled from the interval [0,1), h i ∈H s , H s =(h1,h2,...,h L ) is the final output of the BERT-MLM model, W c and b is the hidden state h i The weights and bias terms of ; The purifier finally outputs the purified sample if is a mask word [MASK], then otherwise, After a complete purification operation, n reconstructed samples X are generated. r =R(X m ).

4. A masking strategy based on part of speech and a defense system against text attacks, characterized by: The system includes: (1) A preprocessing module, which performs word segmentation and part-of-speech tagging on the input text. The spaCy library is used to perform English word segmentation, breaking the text into individual words or symbols. The spaCy tagger is then used to perform part-of-speech tagging on each word segmentation result to determine the part-of-speech category of each word or symbol. (2) Masking and purification module, which determines the masking probability according to the part-of-speech, uses the part-of-speech based masker to perform masking, and uses the purifier to successfully re-predict the masked segmented words; (3) Model training module: This module uses the PyTorch framework to build a model, takes the masked input text as input, and trains the target word as output. It uses the cross-entropy loss function to continuously train and optimize the model until the model converges or reaches the preset number of training rounds. After each training round, the mask and model training process is repeated to obtain the final BERT-MLM model. In the masking and purification processing module, the purifier uses the BERT-based part-of-speech language masking model to predict masked words and restore clean words in turn. i is the mask segmentation word w i The importance score of the masked part is calculated to enable the model to better understand the information of the masked part and improve the efficiency of data utilization. in Represents the segmentation word w i The mask probability, w m are all the masked tokens in the current mask copy, J is the loss function of the target model f, x is the input text, and f represents the target model.

5. The part-of-speech based masking strategy and defense system against text attacks as claimed in claim 4, characterized in that: In the preprocessing module, nouns, verbs, adjectives and adverbs are masked with different probabilities, the masking probabilities are calculated, and training is performed.

6. The masking strategy based on part of speech and the defense system against text attacks as claimed in claim 4, characterized in that: In the mask and purification processing module, the purifier calculates z based on the Softmax function i = The confidence level of w is where g i is the noise sampled from the Gumbel distribution, g i =-log(-log(u i )),u i is a random number uniformly sampled from the interval [0,1), h i ∈H s , H s =(h1,h2,...,h L ) is the final output of the BERT-MLM model, W c and b is the hidden state h i The weights and bias terms of ; The purifier finally outputs the purified sample if is a mask word [MASK], then otherwise, After a complete purification operation, n reconstructed samples X are generated. r =R(X m ).

7. A masking strategy based on part of speech and a defense device against text attacks, the device comprising: Data acquisition device, processor and memory; The data acquisition device is used to collect data; The memory is used to store one or more program instructions; The processor is used to execute one or more program instructions to perform any one of the methods in claims 1 to 3.

8. A computer-readable storage medium for a masking strategy based on part of speech and defense against text attacks, wherein the computer storage medium comprises one or more program instructions, and the one or more program instructions are used to execute any one of the methods in claims 1 to 3 above.