主頁 >  其他 > 怎么讓英文大預言模型支持中文?(一)構建自己的tokenization

怎么讓英文大預言模型支持中文?(一)構建自己的tokenization

2023-06-25 07:49:18 其他

代碼地址:https://github.com/taishan1994/sentencepiece_chinese_bpe

Part1前言

目前,大語言模型呈爆發式的增長,其中,基于llama家族的模型占據了半壁江山,而原始的llama模型對中文的支持不太友好,接下來本文將講解如何去擴充vocab里面的詞以對中文進行token化,

Part2資料預處理

對斗破蒼穹語料進行預處理,每一行為一句或多句話,

with open("data/《斗破蒼穹》.txt""r", encoding="utf-8"as fp:
    data = fp.read().strip().split("\n")
sentences = []

for d in data:
    d = d.strip()
    if "===" in d or len(d) == 0 or d == "《斗破蒼穹》來自:":
        continue
    sentences.append(d)

with open("data/corpus.txt""w", encoding="utf-8"as fp:
    fp.write("\n".join(sentences))

最終得到corpus.txt,

Part3sentencepiece

首先,我們需要去構建中文的詞庫,一般的,目前比較主流的是使用sentencepiece訓練中文詞庫,安裝指令也很簡單:pip install sentencepiece,然后,我們準備好語料,這里我們使用的語料是斗破蒼穹小說,

直接看代碼:

import sentencepiece as spm
spm.SentencePieceTrainer.train(
    input='data/corpus.txt',
    model_prefix='tokenizer',
    vocab_size=50000,
    user_defined_symbols=['foo''bar'],
    character_coverage=1.0,
    model_type="bpe",
)

這里講下每個引數的作用:

  • input:指定輸入文本檔案的路徑或者是一個目錄,可以指定多個輸入檔案或目錄,其中每一行可以是一句話或者多句話,
  • tokenizer:保存的模型的名稱前綴,
  • vocab_size:設定的詞表大小,
  • user_defined_symbols:用于指定用戶自定義的符號,這些符號將會被視為單獨的 Token,不會被拆分成子詞,這個引數的作用是將一些用戶定義的特殊符號作為一個整體加入到生成的詞表中,以便于后續的模型使用,這里我們簡單進行了測驗,
  • model_type: 指定模型的型別,有三種可選引數:unigram, bpe, char. word,
  • character_coverage指定覆寫字符的數量,可以理解為限制字符集的大小,默認值為 1.0,即覆寫全部字符,
  • unk_id: 指定未登錄詞的 ID 號,即在詞表中為未登錄詞分配一個整數 ID,默認值為 0,
  • bos_id: 指定句子開頭符號的 ID 號,即在詞表中為句子開頭符號分配一個整數 ID,默認值為 1,
  • eos_id: 指定句子結束符號的 ID 號,即在詞表中為句子結束符號分配一個整數 ID,默認值為 2,
  • pad_id: 指定填充符號的 ID 號,即在詞表中為填充符號分配一個整數 ID,默認值為 -1,即不使用填充符號,

運行后會得到tokenizer.model和tokenizer.vocab兩個檔案,

我們來看看tokenizer.vocab里面是什么:

<unk> 0
<s> 0
</s> 0
foo 0
bar 0
蕭炎 -0
.. -1
▁“ -2
也是 -3
便是 -4
了一 -5
,” -6

除了一些特殊符號外,還有我們自定義的foo和bar,其余的一些詞是BPE訓練得到,具體什么是BPE演算法這里不作展開了,

Part4怎么使用transformers庫加載sentencepiece模型

直接看代碼:

import os

os.environ["PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION"] = "python"
from transformers import LlamaTokenizer
from sentencepiece import sentencepiece_model_pb2 as sp_pb2_model
import sentencepiece as spm
from tokenization import ChineseTokenizer

chinese_sp_model_file = "sentencepisece_tokenizer/tokenizer.model"

# load
chinese_sp_model = spm.SentencePieceProcessor()
chinese_sp_model.Load(chinese_sp_model_file)

chinese_spm = sp_pb2_model.ModelProto()
chinese_spm.ParseFromString(chinese_sp_model.serialized_model_proto())

## Save
output_dir = './transformers_tokenizer/chinese/'
os.makedirs(output_dir, exist_ok=True)
with open(output_dir + 'chinese.model''wb'as f:
    f.write(chinese_spm.SerializeToString())
tokenizer = ChineseTokenizer(vocab_file=output_dir + 'chinese.model')

tokenizer.save_pretrained(output_dir)
print(f"Chinese tokenizer has been saved to {output_dir}")

# Test
chinese_tokenizer = ChineseTokenizer.from_pretrained(output_dir)
print(tokenizer.all_special_tokens)
print(tokenizer.all_special_ids)
print(tokenizer.special_tokens_map)
text = '''白日依山盡,黃河入海流,欲窮千里目,更上一層樓,
The primary use of LLaMA is research on large language models, including'''

print("Test text:\n", text)
print(f"Tokenized by Chinese-LLaMA tokenizer:{chinese_tokenizer.tokenize(text)}")

結果:

Chinese tokenizer has been saved to ./transformers_tokenizer/chinese/
['<s>''</s>''<unk>']
[120]
{'bos_token''<s>''eos_token''</s>''unk_token''<unk>'}
Test text:
 白日依山盡,黃河入海流,欲窮千里目,更上一層樓,
The primary use of LLaMA is research on large language models, including
Tokenized by Chinese-LLaMA tokenizer:['▁''白日''依''山''盡'',''黃''河''入''海''流'',''欲''窮''千里''目'',''更''上一層''樓'',''▁''T''h''e''▁''p''r''i''m''a''r''y''▁''u''s''e''▁''o''f''▁''LL''a''MA''▁i''s''▁''r''e''s''e''a''r''ch''▁''o''n''▁''l''a''r''g''e''▁''l''an''g''u''a''g''e''▁''m''o''d''e''l''s'',''▁i''n''c''lu''d''i''ng']

其中ChineseTokenizer這里參考了llama模型里面使用的方法,并稍微做些修改:

# coding=utf-8
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
#
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
# and OPT implementations in this library. It has been modified from its
# original forms to accommodate minor architectural differences compared
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Tokenization classes for LLaMA."""
import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
from transformers.utils import logging


logger = logging.get_logger(__name__)

VOCAB_FILES_NAMES = {"vocab_file""tokenizer.model"}

# PRETRAINED_VOCAB_FILES_MAP = {
#     "vocab_file": {
#         "hf-internal-testing/llama-tokenizer": "https://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer.model",
#     },
#     "tokenizer_file": {
#         "hf-internal-testing/llama-tokenizer": "https://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer_config.json",
#     },
# }
# PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
#     "hf-internal-testing/llama-tokenizer": 2048,
# }


class ChineseTokenizer(PreTrainedTokenizer):
    """
    Construct a Llama tokenizer. Based on byte-level Byte-Pair-Encoding.

    Args:
        vocab_file (`str`):
            Path to the vocabulary file.
    """


    vocab_files_names = VOCAB_FILES_NAMES
    # pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
    # max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
    model_input_names = ["input_ids""attention_mask"]

    def __init__(
        self,
        vocab_file,
        unk_token="<unk>",
        bos_token="<s>",
        eos_token="</s>",
        pad_token=None,
        sp_model_kwargs: Optional[Dict[str, Any]] = None,
        add_bos_token=True,
        add_eos_token=False,
        clean_up_tokenization_spaces=False,
        **kwargs,
    )
:

        self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
        bos_token = AddedToken(bos_token, lstrip=False, rstrip=Falseif isinstance(bos_token, str) else bos_token
        eos_token = AddedToken(eos_token, lstrip=False, rstrip=Falseif isinstance(eos_token, str) else eos_token
        unk_token = AddedToken(unk_token, lstrip=False, rstrip=Falseif isinstance(unk_token, str) else unk_token
        pad_token = AddedToken(pad_token, lstrip=False, rstrip=Falseif isinstance(pad_token, str) else pad_token
        super().__init__(
            bos_token=bos_token,
            eos_token=eos_token,
            unk_token=unk_token,
            pad_token=pad_token,
            add_bos_token=add_bos_token,
            add_eos_token=add_eos_token,
            sp_model_kwargs=self.sp_model_kwargs,
            clean_up_tokenization_spaces=clean_up_tokenization_spaces,
            **kwargs,
        )
        self.vocab_file = vocab_file
        self.add_bos_token = add_bos_token
        self.add_eos_token = add_eos_token
        self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
        self.sp_model.Load(vocab_file)

    def __getstate__(self):
        state = self.__dict__.copy()
        state["sp_model"] = None
        return state

    def __setstate__(self, d):
        self.__dict__ = d
        self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
        self.sp_model.Load(self.vocab_file)

    @property
    def vocab_size(self):
        """Returns vocab size"""
        return self.sp_model.get_piece_size()

    def get_vocab(self):
        """Returns vocab as a dict"""
        vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
        vocab.update(self.added_tokens_encoder)
        return vocab

    def _tokenize(self, text):
        """Returns a tokenized string."""
        return self.sp_model.encode(text, out_type=str)

    def _convert_token_to_id(self, token):
        """Converts a token (str) in an id using the vocab."""
        return self.sp_model.piece_to_id(token)

    def _convert_id_to_token(self, index):
        """Converts an index (integer) in a token (str) using the vocab."""
        token = self.sp_model.IdToPiece(index)
        return token

    def convert_tokens_to_string(self, tokens):
        """Converts a sequence of tokens (string) in a single string."""
        current_sub_tokens = []
        out_string = ""
        prev_is_special = False
        for i, token in enumerate(tokens):
            # make sure that special tokens are not decoded using sentencepiece model
            if token in self.all_special_tokens:
                if not prev_is_special and i != 0:
                    out_string += " "
                out_string += self.sp_model.decode(current_sub_tokens) + token
                prev_is_special = True
                current_sub_tokens = []
            else:
                current_sub_tokens.append(token)
                prev_is_special = False
        out_string += self.sp_model.decode(current_sub_tokens)
        return out_string

    def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
        """
        Save the vocabulary and special tokens file to a directory.

        Args:
            save_directory (`str`):
                The directory in which to save the vocabulary.

        Returns:
            `Tuple(str)`: Paths to the files saved.
        """

        if not os.path.isdir(save_directory):
            logger.error(f"Vocabulary path ({save_directory}) should be a directory")
            return
        out_vocab_file = os.path.join(
            save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
        )

        if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
            copyfile(self.vocab_file, out_vocab_file)
        elif not os.path.isfile(self.vocab_file):
            with open(out_vocab_file, "wb"as fi:
                content_spiece_model = self.sp_model.serialized_model_proto()
                fi.write(content_spiece_model)

        return (out_vocab_file,)

    def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
        bos_token_id = [self.bos_token_id] if self.add_bos_token else []
        eos_token_id = [self.eos_token_id] if self.add_eos_token else []

        output = bos_token_id + token_ids_0 + eos_token_id

        if token_ids_1 is not None:
            output = output + bos_token_id + token_ids_1 + eos_token_id

        return output

    def get_special_tokens_mask(
        self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
    )
 -> List[int]:

        """
        Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
        special tokens using the tokenizer `prepare_for_model` method.

        Args:
            token_ids_0 (`List[int]`):
                List of IDs.
            token_ids_1 (`List[int]`, *optional*):
                Optional second list of IDs for sequence pairs.
            already_has_special_tokens (`bool`, *optional*, defaults to `False`):
                Whether or not the token list is already formatted with special tokens for the model.

        Returns:
            `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
        """

        if already_has_special_tokens:
            return super().get_special_tokens_mask(
                token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
            )

        bos_token_id = [1if self.add_bos_token else []
        eos_token_id = [1if self.add_eos_token else []

        if token_ids_1 is None:
            return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
        return (
            bos_token_id
            + ([0] * len(token_ids_0))
            + eos_token_id
            + bos_token_id
            + ([0] * len(token_ids_1))
            + eos_token_id
        )

    def create_token_type_ids_from_sequences(
        self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
    )
 -> List[int]:

        """
        Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
        sequence pair mask has the following format:

        ```
        0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
        | first sequence    | second sequence |
        ```

        if token_ids_1 is None, only returns the first portion of the mask (0s).

        Args:
            token_ids_0 (`List[int]`):
                List of ids.
            token_ids_1 (`List[int]`, *optional*):
                Optional second list of IDs for sequence pairs.

        Returns:
            `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
        """

        bos_token_id = [self.bos_token_id] if self.add_bos_token else []
        eos_token_id = [self.eos_token_id] if self.add_eos_token else []

        output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)

        if token_ids_1 is not None:
            output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)

        return output

不難發現其實里面使用了一些sentencepiece里面的函式,

Part5怎么合并英文詞表和中文詞表?

直接看代碼:

import os

os.environ["PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION"] = "python"
from transformers import LlamaTokenizer
from sentencepiece import sentencepiece_model_pb2 as sp_pb2_model
import sentencepiece as spm

llama_tokenizer_dir = "transformers_tokenizer/llama/tokenizer.model"
chinese_sp_model_file = "sentencepisece_tokenizer/tokenizer.model"

# load
llama_tokenizer = LlamaTokenizer.from_pretrained(llama_tokenizer_dir)
chinese_sp_model = spm.SentencePieceProcessor()
chinese_sp_model.Load(chinese_sp_model_file)

llama_spm = sp_pb2_model.ModelProto()
llama_spm.ParseFromString(llama_tokenizer.sp_model.serialized_model_proto())
chinese_spm = sp_pb2_model.ModelProto()
chinese_spm.ParseFromString(chinese_sp_model.serialized_model_proto())

# print number of tokens
print(len(llama_tokenizer), len(chinese_sp_model))
print(llama_tokenizer.all_special_tokens)
print(llama_tokenizer.all_special_ids)
print(llama_tokenizer.special_tokens_map)

## Add Chinese tokens to LLaMA tokenizer
llama_spm_tokens_set = set(p.piece for p in llama_spm.pieces)
print(len(llama_spm_tokens_set))
print(f"Before:{len(llama_spm_tokens_set)}")
for p in chinese_spm.pieces:
    piece = p.piece
    if piece not in llama_spm_tokens_set:
        new_p = sp_pb2_model.ModelProto().SentencePiece()
        new_p.piece = piece
        new_p.score = 0
        llama_spm.pieces.append(new_p)
print(f"New model pieces: {len(llama_spm.pieces)}")

## Save
output_sp_dir = 'transformers_tokenizer/llama_chinese'
output_hf_dir = 'transformers_tokenizer/llama_chinese'  # the path to save Chinese-LLaMA tokenizer
os.makedirs(output_sp_dir, exist_ok=True)
with open(output_sp_dir + '/chinese_llama.model''wb'as f:
    f.write(llama_spm.SerializeToString())
tokenizer = LlamaTokenizer(vocab_file=output_sp_dir + '/chinese_llama.model')

tokenizer.save_pretrained(output_hf_dir)
print(f"Chinese-LLaMA tokenizer has been saved to {output_hf_dir}")

# Test
llama_tokenizer = LlamaTokenizer.from_pretrained(llama_tokenizer_dir)
chinese_llama_tokenizer = LlamaTokenizer.from_pretrained(output_hf_dir)
print(tokenizer.all_special_tokens)
print(tokenizer.all_special_ids)
print(tokenizer.special_tokens_map)
text = '''白日依山盡,黃河入海流,欲窮千里目,更上一層樓,
The primary use of LLaMA is research on large language models, including'''

print("Test text:\n", text)
print(f"Tokenized by LLaMA tokenizer:{llama_tokenizer.tokenize(text)}")
print(f"Tokenized by Chinese-LLaMA tokenizer:{chinese_llama_tokenizer.tokenize(text)}")

核心部分是這一塊:

for p in chinese_spm.pieces:
    piece = p.piece
    if piece not in llama_spm_tokens_set:
        new_p = sp_pb2_model.ModelProto().SentencePiece()
        new_p.piece = piece
        new_p.score = 0
        llama_spm.pieces.append(new_p)

也就是將原始詞表中沒有的新加入進去,

最后看一下結果:

32000 50000
['<s>''</s>''<unk>']
[120]
{'bos_token''<s>''eos_token''</s>''unk_token''<unk>'}
32000
Before:32000
New model pieces: 81163
Chinese-LLaMA tokenizer has been saved to transformers_tokenizer/llama_chinese
['<s>''</s>''<unk>']
[120]
{'bos_token''<s>''eos_token''</s>''unk_token''<unk>'}
Test text:
 白日依山盡,黃河入海流,欲窮千里目,更上一層樓,
The primary use of LLaMA is research on large language models, including
Tokenized by LLaMA tokenizer:['▁''白''日''<0xE4>''<0xBE>''<0x9D>''山''<0xE5>''<0xB0>''<0xBD>'',''黃''河''入''海''流'',''<0xE6>''<0xAC>''<0xB2>''<0xE7>''<0xA9>''<0xB7>''千''里''目'',''更''上''一''<0xE5>''<0xB1>''<0x82>''<0xE6>''<0xA5>''<0xBC>'',''<0x0A>''The''▁primary''▁use''▁of''▁L''La''MA''▁is''▁research''▁on''▁large''▁language''▁models'',''▁including']
Tokenized by Chinese-LLaMA tokenizer:['▁白''日''依''山''盡'',''黃''河''入''海''流'',''欲''窮''千里''目'',''更''上一層''樓'',''<0x0A>''The''▁primary''▁use''▁of''▁L''La''MA''▁is''▁research''▁on''▁large''▁language''▁models'',''▁including']

會發現再加入了我們定義的詞表后確實能夠對中文進行分詞了,

Part6怎么使用修改后的詞表?

如果我們重新從頭開始訓練,那么其實使用起來很簡單:

config = AutoConfig.from_pretrained(...)
tokenizer = LlamaTokenizer.from_pretrained(...)
model = LlamaForCausalLM.from_pretrained(..., config=config)
model_vocab_size = model.get_output_embeddings().weight.size(0)
model.resize_token_embeddings(len(tokenizer))

但是如果我們想要保留原始模型embedding的引數,那么我們可以這么做:

  • 1、找到新詞表和舊詞表id之間的映射關系,
  • 2、將模型里面新詞表里面包含的舊詞表用原始模型的embedding替換,
  • 3、如果新詞在舊詞表里面沒有出現就進行相應的初始化再進行賦值,比如transformers庫中的llama是這么進行初始化的:
 def _init_weights(self, module):
        std = self.config.initializer_range
        if isinstance(module, nn.Linear):
            module.weight.data.normal_(mean=0.0, std=std)
            if module.bias is not None:
                module.bias.data.zero_()
        elif isinstance(module, nn.Embedding):
            module.weight.data.normal_(mean=0.0, std=std)
            if module.padding_idx is not None:
                module.weight.data[module.padding_idx].zero_()

具體怎么做可以參考一下這個:https://github.com/yangjianxin1/LLMPruner

Part7總結

到這里為止,我們已經學會了:

  • 1、使用sentencepiece訓練一個中文的詞表,
  • 2、使用transformers加載sentencepiece模型,
  • 3、怎么合并中英文的詞表,并使用transformers使用合并后的詞表,
  • 4、在模型中怎么使用新詞表,

Part8參考

https://github.com/ymcui/Chinese-LLaMA-Alpaca

https://github.com/yangjianxin1/LLMPruner

https://github.com/huggingface/transformers

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/555868.html

標籤:其他

上一篇:【技識訓累】演算法中的貪心演算法【三】

下一篇:返回列表

標籤雲
其他(161534) Python(38244) JavaScript(25513) Java(18251) C(15238) 區塊鏈(8272) C#(7972) AI(7469) 爪哇(7425) MySQL(7265) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5875) 数组(5741) R(5409) Linux(5347) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4606) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2437) ASP.NET(2404) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) .NET技术(1984) HtmlCss(1971) 功能(1967) Web開發(1951) C++(1942) python-3.x(1918) 弹簧靴(1913) xml(1889) PostgreSQL(1881) .NETCore(1863) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 網閘典型架構簡述

    網閘架構一般分為兩種:三主機的三系統架構網閘和雙主機的2+1架構網閘。 三主機架構分別為內端機、外端機和仲裁機。三機無論從軟體和硬體上均各自獨立。首先從硬體上來看,三機都用各自獨立的主板、記憶體及存盤設備。從軟體上來看,三機有各自獨立的作業系統。這樣能達到完全的三機獨立。對于“2+1”系統,“2”分為 ......

    uj5u.com 2020-09-10 02:00:44 more
  • 如何從xshell上傳檔案到centos linux虛擬機里

    如何從xshell上傳檔案到centos linux虛擬機里及:虛擬機CentOs下執行 yum -y install lrzsz命令,出現錯誤:鏡像無法找到軟體包 前言 一、安裝lrzsz步驟 二、上傳檔案 三、遇到的問題及解決方案 總結 前言 提示:其實很簡單,往虛擬機上安裝一個上傳檔案的工具 ......

    uj5u.com 2020-09-10 02:00:47 more
  • 一、SQLMAP入門

    一、SQLMAP入門 1、判斷是否存在注入 sqlmap.py -u 網址/id=1 id=1不可缺少。當注入點后面的引數大于兩個時。需要加雙引號, sqlmap.py -u "網址/id=1&uid=1" 2、判斷文本中的請求是否存在注入 從文本中加載http請求,SQLMAP可以從一個文本檔案中 ......

    uj5u.com 2020-09-10 02:00:50 more
  • Metasploit 簡單使用教程

    metasploit 簡單使用教程 浩先生, 2020-08-28 16:18:25 分類專欄: kail 網路安全 linux 文章標簽: linux資訊安全 編輯 著作權 metasploit 使用教程 前言 一、Metasploit是什么? 二、準備作業 三、具體步驟 前言 Msfconsole ......

    uj5u.com 2020-09-10 02:00:53 more
  • 游戲逆向之驅動層與用戶層通訊

    驅動層代碼: #pragma once #include <ntifs.h> #define add_code CTL_CODE(FILE_DEVICE_UNKNOWN,0x800,METHOD_BUFFERED,FILE_ANY_ACCESS) /* 更多游戲逆向視頻www.yxfzedu.com ......

    uj5u.com 2020-09-10 02:00:56 more
  • 北斗電力時鐘(北斗授時服務器)讓網路資料更精準

    北斗電力時鐘(北斗授時服務器)讓網路資料更精準 北斗電力時鐘(北斗授時服務器)讓網路資料更精準 京準電子科技官微——ahjzsz 近幾年,資訊技術的得了快速發展,互聯網在逐漸普及,其在人們生活和生產中都得到了廣泛應用,并且取得了不錯的應用效果。計算機網路資訊在電力系統中的應用,一方面使電力系統的運行 ......

    uj5u.com 2020-09-10 02:01:03 more
  • 【CTF】CTFHub 技能樹 彩蛋 writeup

    ?碎碎念 CTFHub:https://www.ctfhub.com/ 筆者入門CTF時時剛開始刷的是bugku的舊平臺,后來才有了CTFHub。 感覺不論是網頁UI設計,還是題目質量,賽事跟蹤,工具軟體都做得很不錯。 而且因為獨到的金幣制度的確讓人有一種想去刷題賺金幣的感覺。 個人還是非常喜歡這個 ......

    uj5u.com 2020-09-10 02:04:05 more
  • 02windows基礎操作

    我學到了一下幾點 Windows系統目錄結構與滲透的作用 常見Windows的服務詳解 Windows埠詳解 常用的Windows注冊表詳解 hacker DOS命令詳解(net user / type /md /rd/ dir /cd /net use copy、批處理 等) 利用dos命令制作 ......

    uj5u.com 2020-09-10 02:04:18 more
  • 03.Linux基礎操作

    我學到了以下幾點 01Linux系統介紹02系統安裝,密碼啊破解03Linux常用命令04LAMP 01LINUX windows: win03 8 12 16 19 配置不繁瑣 Linux:redhat,centos(紅帽社區版),Ubuntu server,suse unix:金融機構,證券,銀 ......

    uj5u.com 2020-09-10 02:04:30 more
  • 05HTML

    01HTML介紹 02頭部標簽講解03基礎標簽講解04表單標簽講解 HTML前段語言 js1.了解代碼2.根據代碼 懂得挖掘漏洞 (POST注入/XSS漏洞上傳)3.黑帽seo 白帽seo 客戶網站被黑帽植入劫持代碼如何處理4.熟悉html表單 <html><head><title>TDK標題,描述 ......

    uj5u.com 2020-09-10 02:04:36 more
最新发布
  • 怎么讓英文大預言模型支持中文?(一)構建自己的tokenization

    代碼地址:https://github.com/taishan1994/sentencepiece_chinese_bpe Part1前言 目前,大語言模型呈爆發式的增長,其中,基于llama家族的模型占據了半壁江山。而原始的llama模型對中文的支持不太友好,接下來本文將講解如何去擴充vocab里 ......

    uj5u.com 2023-06-25 07:49:18 more
  • 【技識訓累】演算法中的貪心演算法【三】

    博客推行版本更新,成果積累制度,已經寫過的博客還會再次更新,不斷地琢磨,高質量高數量都是要追求的,工匠精神是學習必不可少的精神。因此,大家有何建議歡迎在評論區踴躍發言,你們的支持是我最大的動力,你們敢投,我就敢肝 ......

    uj5u.com 2023-06-25 07:48:47 more
  • AtCoder Beginner Contest 307

    ## [A - Weekly Records (abc307 A)](https://atcoder.jp/contests/abc307/tasks/abc307_a) ### 題目大意 給定$n$周每天的散步量,求每周七天的散步量的和。 ### 解題思路 累計求和即可。 神奇的代碼 ```cpp ......

    uj5u.com 2023-06-25 07:48:42 more
  • 淺談OpenCV的多物件匹配影像的實作,以及如何匹配半透明控制元件,不

    # 淺談OpenCV的多物件匹配透明影像的實作,以及如何匹配半透明控制元件 ### 引子 > 1. OpenCV提供的templateMatch只負責將(相關性等)計算出來,并不會直接提供目標的對應坐標,一般來說我們直接遍歷最高的相關度,就可以得到匹配度最高的坐標。但是這樣一般只能得到一個坐標。 > 2 ......

    uj5u.com 2023-06-25 07:42:42 more
  • C++ 核心指南之資源管理(上)

    C++ 核心指南(C++ Core Guidelines)是由 Bjarne Stroustrup、Herb Sutter 等頂尖 C++ 專家創建的一份 C++ 指南、規則及最佳實踐。旨在幫助大家正確、高效地使用“現代 C++”。 這份指南側重于介面、資源管理、記憶體管理、并發等 High-leve ......

    uj5u.com 2023-06-25 07:42:27 more
  • 空 - 三眼烏鴉

    一款純凈版內網探測工具,解決某些工具內網探測速率慢、服務爆破誤報率高以及socks流量代理出問題且工具落地又被秒的困擾 ......

    uj5u.com 2023-06-25 07:39:45 more
  • 跨域攻擊的方法介紹

    # 跨域攻擊的方法介紹 [TOC] ## 一、內網中的域林 很多大型企業都擁有自己的內網,一般通過域林進行共享資源。根據不同職能區分的部門,從邏輯上以主域和子域進行區分,以方便統一管理。在物理層,通常使用防火墻將各個子公司及各個部門劃分為不同的區域。 ## 二、跨域攻擊方法 1、常規滲透方法(利用w ......

    uj5u.com 2023-06-25 07:39:40 more
  • K8S安裝記錄

    https://kubernetes.io/zh-cn/docs/setup/production-environment/container-runtimes/ https://kubernetes.io/docs/setup/production-environment/tools/kubead ......

    uj5u.com 2023-06-24 07:58:59 more
  • 「大學」回首填報高考志愿

    ## $Before$ 我一時興起想寫的。$23$ 年高考結束了,應該快出分了吧(大概),回想當時自己填報志愿,好像挺難的,又好像很簡單。 ## 回首 高考分數給了我一個驚喜,想到我高三的答辯般的表現,這成績著實令我吃驚。 當時,我的志愿專業比較明確,軟體工程或者計算機科學與技術(群友說軟工是學費更 ......

    uj5u.com 2023-06-24 07:58:45 more
  • DVWA靶場之SQL注入通關詳解

    原理 SQL注入通過將惡意的SQL代碼插入到應用程式后臺的SQL陳述句中,以獲取未授權的訪問權限或者竊取應用程式中的敏感資訊。通常,SQL注入攻擊的目標是Web應用程式,因為Web應用程式通常需要與資料庫進行互動,并且大多數Web應用程式使用的是SQL語言。 存在原因 Web應用程式沒有對用戶輸入的數 ......

    uj5u.com 2023-06-24 07:58:13 more