Multi-language aggressiveness detection method based on large model
Through the transformation and pre-training of the Llama2 model, combined with KMeans clustering and LoRA fine-tuning, the problem of insufficient understanding and flexibility of traditional machine learning algorithms in online violence detection is solved, and more efficient and flexible multi-language aggression detection is achieved. , suitable for offensive language detection in different fields.
Patent Information
- Application Number
- CN202410769976.9
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2024-06-14
- Publication Date
- 2024-10-11
- Estimated Expiration
- 2044-06-14
AI Technical Summary
Traditional machine learning algorithms have problems with insufficient understanding, flexibility, and slow update speed in online violence detection, resulting in the inability to meet the needs of different platforms and to quickly adapt to emerging toxic languages.
Using a multi-language aggressiveness detection method based on a large model, by loading the Llama2 model for transformation and pre-training, KMeans clustering is used to group and fuse the attention heads, and combined with the LoRA fine-tuning method, a more efficient and flexible aggressiveness detection is achieved .
It improves the accuracy and flexibility of detection, can better capture and understand the semantics of offensive language, is suitable for large-scale corpus and offensive language detection in different fields, reduces the number of parameters of the model, and improves the practical application of the model. deployment efficiency.
Smart Images

Figure CN118760749A_ABST
Abstract
Description
Technical Field
[0001] The present invention belongs to the field of NLP (Natural Language Processing) large models, and in particular relates to a multi-language aggressiveness detection method based on a large model. Background Art
[0002] At present, the use of AI (Artificial Intelligence) content detection to prevent cyber violence has been studied for several years. In 2015, it was proposed that there is a significant correlation between an individual's emotional state and harmful intent, and the use of machine learning to detect aggressive behavior in social media is considered a good indicator for detecting cyber violence. In 2017, Google's Jigsaw created Conversation AI to detect toxic comments online. Many technology giants have been incorporating algorithms into their content audits for many years, and have a set of means to identify and filter online information content. But it is obvious that these AI detection algorithms have not eradicated cyber violence. One of the reasons is that traditional machine learning algorithms cannot meet the needs of network content review. The influencing factors are as follows:
[0003] 1. Lack of understanding: Harmful language is very difficult to distinguish, and the semantic understanding ability of AI algorithms is not strong enough. They often give the same score to harmful comments and harmless comments, fail to truly filter out disrespectful comments, or give lower scores to neutral sentences, filtering out normal comments that should not be filtered, hindering the communication between bloggers and fans.
[0004] 2. Lack of flexibility: Some websites may require detection of offensive language but not rumors, while other websites may require the opposite. Traditional AI detection tools often use a universal "toxicity score" that is not flexible enough to meet the different needs of different platforms.
[0005] 3. Insufficient update speed: Many detection algorithms work using APIs, and these models are trained with large amounts of network data. They perform well on examples similar to the training data, but are likely to fail once they encounter unfamiliar toxic language and constantly coined words. Therefore, AI models lack efficient and real-time human feedback, and cannot quickly fine-tune and iterate models, resulting in poor automated detection results.
[0006] Large language models have the characteristics of intelligent emergence, pre-training, and reinforcement learning with human feedback, which greatly helps traditional methods and provides stronger language comprehension capabilities. Using general models, more accurate customized models can be quickly trained. At the same time, with the help of human feedback, better and faster detection results can be obtained by filling in the gaps.
[0007] Transformer is a standard seq2seq, or encoder-decoder structure, consisting of a series of encoders and decoders stacked together. Transformer is widely used in NLP. Usually, tasks such as text classification and sentiment analysis only require an encoder, while some generative tasks such as machine translation, dialogue analysis, and reading comprehension require a decoder to generate sequence results of the same size. Each encoder module of the Transformer model consists of a self-attention layer and a feedforward neural network, while the decoder has an additional encoder-decoder attention module compared to the encoder, which is used to establish the connection between the encoder and the decoder. These self-attention modules are the core of Transformer's success.
[0008] Autoregressive decoder inference is a serious bottleneck for the Transformer model, due to the huge memory bandwidth overhead of loading the decoder weights and all attention keys and values in each decoding step. This memory bandwidth overhead of loading keys and values can be drastically reduced by Multi-Query-Attention. However, Multi-Query-Attention may lead to a degradation in inference quality and instability in model training. And training a model alone just for accelerating model inference is not ideal. By uptraining the existing model with a pre-trained model, the Multi-Head-Attention model is converted to a Multi-Query-Attention model with a smaller computational cost, and Grouped-Query-Attention, a generalization of Multi-Query-Attention and Multi-Head-Attention, is introduced. A balance between performance and speed is achieved.
[0009] MHA (Multi-Head-Attention) is a standard multi-head attention mechanism, which contains H Query, Key and Value matrices. The weights of the Key and Value matrices of all attention heads are not shared.
[0010] MQA (Multi-Query-Attention) is a variant of multi-query attention and an attention mechanism for autoregressive decoding. Unlike MHA, MQA allows all heads to share the same Key and Value matrix, and each head only retains one Query parameter, which greatly reduces the number of parameters in the Key and Value matrices.
[0011] GQA (Grouped-Query Attention) is grouped query attention. GQA divides query heads into G groups, and each group shares a Key and Value matrix. GQA-G refers to grouped-query attention with G groups. GQA-1 has a single group, so it has a single Key and Value, which is equivalent to MQA. If GQA-H has the same number of groups as heads, it is equivalent to MHA.
[0012] GQA adopts a compromise between MHA and MQA. After training, GQA achieves a balance between performance and speed, reaching a quality close to MHA and a speed comparable to MQA. However, GQA fuses attention heads from different semantic spaces, which causes confusion in the semantic space and affects the reasoning performance of the model. Summary of the invention
[0013] In order to avoid the problem that the above-mentioned traditional machine learning algorithms cannot meet the review requirements of network content due to limitations in understanding ability, flexibility, update speed, etc., the present invention proposes a multilingual offensiveness detection method based on a large model. At the same time, the present invention proposes SQA, a method of model attention heads based on attention head similarity grouping. SQA calculates the similarity between attention heads and fuses attention heads with similar semantic spaces to obtain a more focused attention, thereby improving the performance of the model. At the same time, the method reduces the number of parameters of the model, making the model more flexible and efficient when deployed in an actual system.
[0014] To achieve the above object, the technical solution adopted by the present invention is:
[0015] A multi-language offensiveness detection method based on a large model, the multi-language offensiveness detection method based on a large model comprising:
[0016] Step 1: Build and clean a multilingual offensiveness detection dataset;
[0017] Step 2: Load the Llama2 model for transformation, and perform pre-training after the transformation to obtain a pre-trained language model. The transformation process is as follows:
[0018] Step 2.1: Load the parameters of the Llama2 model and obtain the parameters of all attention heads of the Llama2 model. The parameters of the attention heads include the weight of the key-value head and the weight of the query head.
[0019] Step 2.2: Convert the weight of each key-value header into a tensor of preset dimensions;
[0020] Step 2.3: Perform KMeans clustering on the key-value header based on the tensor;
[0021] Step 2.4: Encapsulate the KMeans clustering results into a dictionary, where the key of the dictionary is the index value corresponding to each attention head, and the value is the cluster label corresponding to each attention head after clustering;
[0022] Step 2.5: According to the dictionary obtained in step 2.4, the key-value heads in the attention heads with the same cluster label are average-pooled and fused into one key-value head;
[0023] Step 2.6: Concatenate all key-value headers obtained after average pooling to obtain the key-value header combination result;
[0024] Step 2.7: According to the number of key-value heads before average pooling, repeat the key-value head combination result obtained in step 2.6 to expand it to the original number of key-value heads of the Llama2 model, and combine the corresponding query heads to obtain the new attention head to complete the transformation;
[0025] Step 3: Based on the data set, the pre-trained language model is fine-tuned using the LoRA fine-tuning method to obtain a fine-tuned model;
[0026] Step 4: Utilize the fine-tuned model for multilingual aggression detection.
[0027] Several optional methods are also provided below, but they are not intended to be additional limitations on the above-mentioned overall solution, but are merely further supplements or preferences. Under the premise that there are no technical or logical contradictions, each optional method can be combined with the above-mentioned overall solution separately, and multiple optional methods can also be combined.
[0028] Preferably, converting the weight of each key-value header into a tensor of a preset dimension comprises:
[0029] The weight of each key-value header is increased in dimension through the unsqueeze operation of the tensor, and then transformed into the tensor shape of the final preset dimension through two view operations and one transpose operation.
[0030] Preferably, 5% of the total data of the bookcorpus dataset and the wikipedia dataset are used for pre-training, and the pre-training parameters are as follows: round train_epoch=3, the number of samples used in each iteration of the training phase train_batch_size_each_device=64, the number of samples used in the test phase eval_batch_size_each_device=64, and the gradient accumulation grad_acc=4.
[0031] Preferably, the key-value header combination result obtained in step 2.6 is repeated to expand it to the original number of key-value headers of the Llama2 model, including:
[0032] For a key-value head in the key-value head combination result, if the key-value head is obtained by average pooling the key-value heads in N attention heads with the same clustering label, the key-value head in the key-value head combination result is repeated to obtain the key-value head in the N key-value head combination results.
[0033] Preferably, the combining of corresponding query heads to obtain a new attention head includes:
[0034] For a key-value head in the key-value head combination result, if the key-value head is averagely pooled from the key-value heads in N attention heads with the same cluster label, and the key-value head is repeated to generate N key-value heads, then the query heads in the N attention heads with the same cluster label are respectively combined with a key-value head generated after the repeat operation to obtain a new attention head.
[0035] The multilingual aggressiveness detection method based on a large model provided by the present invention has the following beneficial effects compared with the prior art:
[0036] (1) High accuracy: By fine-tuning large language models, more accurate offensive language detection results can be obtained, improving the system's judgment accuracy.
[0037] (2) Powerful language understanding capabilities: Large-scale language models based on deep learning have powerful language understanding and generation capabilities, and can better capture and understand the semantics and context of offensive language.
[0038] (3) Scalability: The method of the present invention is applicable to large-scale corpora and practical application scenarios, and can cope with different fields and various types of offensive language.
[0039] (4) The KMeans clustering method is used to group the attention heads to obtain a more focused attention, which improves the performance of the model while reducing the model parameters. This solves the problem that the model is difficult to deploy in practical applications due to the large number of parameters. BRIEF DESCRIPTION OF THE DRAWINGS
[0040] Figure 1 A flowchart of a multi-language aggressiveness detection method based on a large model of the present invention;
[0041] Figure 2 Flow chart of modifying the Llama2 model for the present invention;
[0042] Figure 3A schematic diagram of the present invention performing average pooling of grouped key-value headers into a group;
[0043] Figure 4 A diagram of the method for grouping attention heads using KMeans clustering in the present invention;
[0044] Figure 5 Fine-tune the schematic for using LoRA. DETAILED DESCRIPTION
[0045] The following will be combined with the drawings in the embodiments of the present invention to clearly and completely describe the technical solutions in the embodiments of the present invention. Obviously, the described embodiments are only part of the embodiments of the present invention, not all of the embodiments. Based on the embodiments of the present invention, all other embodiments obtained by ordinary technicians in this field without creative work are within the scope of protection of the present invention.
[0046] Unless otherwise defined, all technical and scientific terms used herein have the same meaning as those commonly understood by those skilled in the art of the present invention. The terms used in the specification of the present invention herein are only for the purpose of describing specific embodiments and are not intended to limit the present invention.
[0047] like Figure 1 As shown, this embodiment provides a multi-language aggressiveness detection method based on a large model, comprising the following steps:
[0048] Step 1: Build and clean a multilingual offensive detection dataset. This example selects Chinese, English, and Korean as the dataset for instruction supervision fine-tuning. First, a large-scale corpus containing sample texts of offensive and non-offensive language is collected. These texts are then preprocessed, including word segmentation, stop word removal, tokenization, etc., and an instruction fine-tuning prompt is constructed to prepare a dataset for model fine-tuning.
[0049] Step 2: Select a large model as the basic model: This embodiment selects the Llama2 model as the large model that needs to be fine-tuned for this task, which has strong language understanding and generation capabilities. Then, the basic model is initialized and configured for fine-tuning. At the same time, the model structure is modified, such as Figure 2 As shown, the transformation process is as follows:
[0050] Step 2.1: Load the parameters of the original Llama2 model and obtain the weights of the attention key-value pairs of each layer of the Llama2 model. The attention mechanism in the original Llama2 model is MHA, so this embodiment specifically obtains the weights of the key-value header and query header of 40 layers in the Llama2 model.
[0051] Step 2.2: Transform the weights of the key-value pairs of each layer. Use the unsqueeze operation of the tensor to increase the dimension, and then use two view operations and one transpose operation to transform it into the final required tensor shape. For example, this embodiment converts the original two-dimensional tensor into a four-bit tensor to facilitate subsequent grouping operations.
[0052] Step 2.3: Perform KMeans clustering on the attention heads based on the weights of the deformed key-value pairs, where the parameter n_clusters of KMeans clustering is a hyperparameter.
[0053] Step 2.4: Process the results of KMeans clustering and encapsulate them into a dictionary. The key of the dictionary is the index value corresponding to each attention head, and the value is the cluster label corresponding to each attention head after clustering.
[0054] Step 2.5: According to the dictionary obtained in step 2.4, the key-value heads in the attention heads of the same label are average-pooled and fused into one key-value head (for the convenience of description, this embodiment is called a fused key-value head) to obtain the grouped fusion result of the attention heads.
[0055] This embodiment takes the key Key as an example to illustrate the average pooling. Figure 3 As shown, K1, K2, ... Kn represent the keys of n attention heads, d h Indicates the characteristic dimension of Key, d model Indicates the length of the sequence. The average pooling operation is used to merge n keys into one key. The value fusion process is similar.
[0056] Step 2.6: Concatenate the fused key-value headers obtained after average pooling to obtain the final key-value header combination result.
[0057] Step 2.7: Repeat the key-value header combination result obtained in step 2.6 to expand it into the original dimension, and then perform attention calculation to obtain a more focused attention.
[0058] In order to maintain the structure of the original attention mechanism, this embodiment repeats the key-value header combination result obtained in step 2.6 according to the number of key-value headers before average pooling, expands it to the original number of key-value headers of the Llama2 model, and combines the corresponding query heads to obtain new attention heads.
[0059] During the repeat operation, for a fused key-value head in the key-value head combination result, if the fused key-value head is obtained by average pooling of key-value heads in N attention heads with the same clustering label, the fused key-value head in the key-value head combination result is repeated to obtain the fused key-value head in the N key-value head combination results.
[0060] During combination, for a fused key-value head in the key-value head combination result, if the fused key-value head is averagely pooled from the key-value heads in N attention heads with the same cluster label, and the fused key-value head is repeated to generate N fused key-value heads, then the query heads in the N attention heads with the same cluster label are respectively combined with a fused key-value head generated after the repeat operation to obtain a new attention head. Figure 4 Indicates the grouping result obtained by grouping the attention heads with similar semantic spaces using the KMeans algorithm. For example, 0, 3, and 4 indicate that these three key-value heads have similar semantic spaces, so they are grouped together. The same applies to other key-value heads.
[0061] In this embodiment, the attention mechanism with a new attention head is named SQA (Similarity Query Attention), and the attention calculation formula is as follows:
[0062]
[0063] In the formula, Attention(Q,K,V) is the attention value, softmax is the softmax function, Q is the query, K is the key, V is the value, and d k is the dimension of the input information.
[0064] In order to adapt the improved Llama2 in step 2.7 to the new structure of the model, the present invention uses 5% of the overall data of the bookcorpus dataset and the wikipedia dataset for pre-training, which realizes the conversion of the model with a relatively low computational cost and improves the performance of the model. The pre-training parameters are as follows: round train_epoch = 3, the number of samples used in one forward propagation and back propagation train_batch_size_each_device = 64, the number of samples used in each evaluation eval_batch_size_each_device = 64, and the gradient accumulation grad_acc = 4. The total number of steps in the entire training process is 11667, and the time is about 22 hours.
[0065] Step 3: Fine-tune the model. In this method, the preprocessed dataset is input into the Llama2 model obtained in step 2.8 and fine-tuned using LoRA. During the fine-tuning process, the weights and parameters of the model are adjusted based on the label information of the sample to enable it to better identify and classify offensive language. Figure 5 As shown, the principle of LoRA is as follows:
[0066] (1) Add a bypass next to the original PLM (Pre-trained Language Model) to perform a dimensionality reduction and then dimensionality increase operation to simulate intrinsic rank.
[0067] (2) During training, the parameters of PLM are fixed, and only the dimension reduction matrix A and the dimension increase matrix B are trained. The input and output dimensions of the model remain unchanged, and the parameters of BA and PLM are superimposed during output.
[0068] (3) A is initialized with a random Gaussian distribution and B is initialized with a 0 matrix to ensure that the bypass matrix is still a 0 matrix at the beginning of training.
[0069] When fine-tuning the pre-trained language model for downstream tasks, it is necessary to update the pre-trained model parameters. The formula is as follows:
[0070] W0+ΔW
[0071] W0 is the parameter of the pre-trained language model after pre-training is completed, and ΔW is the parameter that needs to be updated. If it is full parameter fine-tuning, its parameter amount is W0. For LORA, only ΔW needs to be fine-tuned.
[0072] Specifically, assuming that the pre-trained matrix is W0∈R d×k , its update can be expressed as:
[0073] W0+ΔW=W0+BA,B∈R d×r ,A∈R r×k
[0074] The rank is:
[0075] r<<min(d,k)
[0076] Where d represents the size of the first dimension of the original parameter matrix W0, which represents the number of rows, and k represents the size of the second dimension of the original parameter matrix W0, which represents the number of columns.
[0077] During the training process of LoRA, W0 is fixed and only A and B are training parameters.
[0078] In the forward process, W0 and ΔW are multiplied by the same input x and added together. The formula is as follows:
[0079] h=W0x+ΔWx=W0x+BAx
[0080] Among them, h represents the output of the forward process.
[0081] Step 4: Model evaluation and optimization. Evaluate and optimize the fine-tuned model. Use another independent test set to evaluate the model and calculate the performance indicators of the model on the offensive language detection task, such as precision, recall, and F1 score. Based on the evaluation results, the model can be adjusted and optimized to further improve the performance of the fine-tuned model.
[0082] Step 5: System implementation. Apply the fine-tuned model to an actual offensive language detection system. Integrate the fine-tuned model into a usable software or hardware system that can receive input text and output a judgment result on whether the text contains offensive language. The system can be customized and optimized according to actual needs to improve real-time performance and adaptability.
[0083] The present invention discloses a method for multi-language aggression detection based on a large model. The method fine-tunes a large language model based on deep learning to enable it to accurately identify and classify the aggression of different languages, thereby providing an efficient and accurate multi-language aggression detection solution. At the same time, the KMeans clustering method is used to group the attention heads, and similar attention heads are grouped and fused to obtain a more focused attention, which improves the performance of the model while reducing the parameters of the model, making the model more flexible when deployed in actual application systems.
[0084] The technical features of the above-described embodiments may be arbitrarily combined. To make the description concise, not all possible combinations of the technical features in the above-described embodiments are described. However, as long as there is no contradiction in the combination of these technical features, they should be considered to be within the scope of this specification.
[0085] The above-mentioned embodiments only express several implementation modes of the present invention, and the description thereof is relatively specific and detailed, but it cannot be understood as limiting the scope of the invention. It should be pointed out that, for a person of ordinary skill in the art, several modifications and improvements can be made without departing from the concept of the present invention, and these all belong to the protection scope of the present invention. Therefore, the protection scope of the present invention shall be subject to the attached claims.
Claims
1. A multi-language attack detection method based on a large model, It is characterized in that The multi-language aggression detection method based on a large model includes: Step 1: Build and clean a multilingual offensiveness detection dataset; Step 2: Load the Llama2 model for transformation, and perform pre-training after the transformation to obtain a pre-trained language model. The transformation process is as follows: Step 2.1: Load the parameters of the Llama2 model and obtain the parameters of all attention heads of the Llama2 model. The parameters of the attention heads include the weight of the key-value head and the weight of the query head. Step 2.2: Convert the weight of each key-value header into a tensor of preset dimensions; Step 2.3: Perform KMeans clustering on the key-value header based on the tensor; Step 2.4: Encapsulate the KMeans clustering results into a dictionary, where the key of the dictionary is the index value corresponding to each attention head, and the value is the cluster label corresponding to each attention head after clustering; Step 2.5: According to the dictionary obtained in step 2.4, the key-value heads in the attention heads with the same cluster label are average-pooled and fused into one key-value head; Step 2.6: Concatenate all key-value headers obtained after average pooling to obtain the key-value header combination result; Step 2.7: According to the number of key-value heads before average pooling, repeat the key-value head combination result obtained in step 2.6 to expand it to the original number of key-value heads of the Llama2 model, and combine the corresponding query heads to obtain the new attention head to complete the transformation; Step 3: Based on the data set, the pre-trained language model is fine-tuned using the LoRA fine-tuning method to obtain a fine-tuned model; Step 4: Utilize the fine-tuned model for multilingual aggression detection.
2. The multi-language aggressiveness detection method based on a large model according to claim 1, It is characterized in that The step of converting the weight of each key-value header into a tensor of a preset dimension includes: The weight of each key-value header is increased in dimension through the unsqueeze operation of the tensor, and then transformed into the tensor shape of the final preset dimension through two view operations and one transpose operation.
3. The multi-language aggressiveness detection method based on a large model according to claim 1, It is characterized in that The bookcorpus dataset and 5% of the wikipedia dataset were used for pre-training, and the pre-training parameters were as follows: train_epoch=3, train_batch_size_each_device=64, eval_batch_size_each_device=64, and grad_acc=4.
4. The multi-language aggressiveness detection method based on a large model according to claim 1, It is characterized in that The key-value header combination result obtained in step 2.6 is repeated to expand it to the original number of key-value headers of the Llama2 model, including: For a key-value head in the key-value head combination result, if the key-value head is obtained by average pooling the key-value heads in N attention heads with the same clustering label, the key-value head in the key-value head combination result is repeated to obtain the key-value head in the N key-value head combination results.
5. The multi-language aggressiveness detection method based on a large model according to claim 1, It is characterized in that The corresponding query heads are combined to obtain a new attention head, including: For a key-value head in the key-value head combination result, if the key-value head is averagely pooled from the key-value heads in N attention heads with the same cluster label, and the key-value head is repeated to generate N key-value heads, then the query heads in the N attention heads with the same cluster label are respectively combined with a key-value head generated after the repeat operation to obtain a new attention head.
Citation Information
Patent Citations
Fine adjustment method and system of pre-training language model based on attention guidance mechanism
CN114925814A
Instruction data mining method and system based on LoRA embedding
CN117556251A
