大模型架构原理知识库 · 第10/22篇

第十章 数据工程深度解析

数据来源、分词器、MinHash去重、质量分类、Llama3 Pipeline、污染检测

生成日期:2026年11月6日 · 基于最新论文与行业实践 · 返回目录

1. 大模型数据来源全景

1.1 数据来源分类

大模型训练数据的质量和多样性直接决定模型能力。现代大模型的数据来源主要包括以下几类:

数据来源占比(典型)信息密度质量代表数据集
网页爬取60-80%低-中参差不齐CommonCrawl, RefinedWeb
代码仓库5-15%高高GitHub, StarCoderData
书籍/论文5-10%高高Books3, arXiv, S2ORC
对话数据3-8%中中-高ShareGPT, OpenAssistant
百科知识2-5%高高Wikipedia, Wikidata
合成数据5-15%可变可变模型生成, 回译
专有数据可变高高内部数据, 标注数据

1.2 CommonCrawl处理流程

CommonCrawl是全球最大的公开网页爬取数据集,每月发布数十TB数据。其处理流程是大模型数据pipeline的核心:

CommonCrawl数据处理Pipeline WARC提取 ~50TB/月 HTML解析 trafilatura 语言识别 fastText 质量过滤 分类器+规则 安全过滤 PII+毒性 去重 MinHash+LSH 数据混合 按比例采样 分词 BPE/SentencePiece 打包 二进制格式 训练就绪 ~2-5TB 从50TB原始数据到2-5TB训练数据, 保留率约5-10% 每步都可能丢弃30-70%的数据
Python
import re
from trafilatura import extract

def process_warc_record(record):
    """处理单个WARC记录"""
    # 1. HTML解析: 提取正文
    text = extract(record.content, include_comments=False,
                   include_tables=True, favor_recall=True)
    if not text or len(text) < 200:
        return None
    # 2. 语言识别
    lang = detect_language(text)
    if lang != "en":
        return None
    # 3. 质量过滤
    if not quality_filter(text):
        return None
    # 4. PII过滤
    text = remove_pii(text)
    # 5. 归一化
    text = normalize_text(text)
    return {"text": text, "url": record.url, "lang": lang}

def quality_filter(text):
    """基于规则的质量过滤"""
    words = text.split()
    # 长度检查
    if len(words) < 50 or len(words) > 100000:
        return False
    # 平均词长检查
    avg_word_len = sum(len(w) for w in words) / len(words)
    if avg_word_len < 3 or avg_word_len > 10:
        return False
    # 特殊字符比例
    special_ratio = sum(1 for c in text if not c.isalnum() and not c.isspace()) / len(text)
    if special_ratio > 0.3:
        return False
    # 重复行检查
    lines = text.split("\n")
    unique_lines = set(lines)
    if len(unique_lines) / len(lines) < 0.5:
        return False
    return True

2. 分词器对比与实现

2.1 BPE分词算法

字节对编码(Byte Pair Encoding, BPE)是大模型最常用的分词算法。其核心思想是从字符级开始,迭代合并最高频的字符对,直到达到目标词表大小。

Python
class BPETokenizer:
    """BPE分词器完整实现"""
    def __init__(self, vocab_size=32000):
        self.vocab_size = vocab_size
        self.merges = []  # 合并规则列表
        self.vocab = {}   # token -> id

    def train(self, texts, num_merges=10000):
        """从语料训练BPE合并规则"""
        # 初始化: 每个字符是一个token
        word_freqs = {}
        for text in texts:
            words = text.split()
            for word in words:
                tokens = tuple(word) + ("</w>",)
                word_freqs[tokens] = word_freqs.get(tokens, 0) + 1

        for _ in range(num_merges):
            # 统计相邻token对的频率
            pair_freqs = {}
            for word, freq in word_freqs.items():
                for i in range(len(word) - 1):
                    pair = (word[i], word[i+1])
                    pair_freqs[pair] = pair_freqs.get(pair, 0) + freq
            if not pair_freqs:
                break
            # 选择最高频对
            best_pair = max(pair_freqs, key=pair_freqs.get)
            self.merges.append(best_pair)
            # 合并所有出现该对的word
            new_word_freqs = {}
            for word, freq in word_freqs.items():
                new_word = list(word)
                i = 0
                while i < len(new_word) - 1:
                    if (new_word[i], new_word[i+1]) == best_pair:
                        new_word[i] = new_word[i] + new_word[i+1]
                        del new_word[i+1]
                    i += 1
                new_word_freqs[tuple(new_word)] = freq
            word_freqs = new_word_freqs

    def encode(self, text):
        """编码文本为token序列"""
        words = text.split()
        tokens = []
        for word in words:
            word_tokens = list(word) + ["</w>"]
            for merge in self.merges:
                i = 0
                while i < len(word_tokens) - 1:
                    if (word_tokens[i], word_tokens[i+1]) == merge:
                        word_tokens[i] = word_tokens[i] + word_tokens[i+1]
                        del word_tokens[i+1]
                    i += 1
            tokens.extend(word_tokens)
        return tokens

2.2 SentencePiece分词

SentencePiece是Google开发的分词库,支持BPE和Unigram两种算法。与纯BPE不同,SentencePiece直接在原始Unicode字符上操作,不依赖空格分词,因此对中文、日文等无空格语言更友好。

Python
import sentencepiece as spm

# 训练SentencePiece模型
spm.SentencePieceTrainer.train(
    input="corpus.txt",
    model_prefix="spm_model",
    vocab_size=32000,
    character_coverage=0.9995,
    model_type="bpe",  # 或 "unigram"
    # 特殊token
    pad_id=0, unk_id=1, bos_id=2, eos_id=3,
    pad_piece="<pad>", unk_piece="<unk>",
    bos_piece="<s>", eos_piece="</s>",
    # 数字和URI处理
    split_by_unicode_script=True,
    split_by_whitespace=False,
    split_by_number=True,
    max_sentence_length=4192,
    # 字节回退 (处理OOV)
    byte_fallback=True,
)

# 使用训练好的模型
sp = spm.SentencePieceProcessor()
sp.load("spm_model.model")
text = "大模型架构原理深度解析"
tokens = sp.encode(text)
pieces = sp.encode(text, out_type="str")
print(f"原文: {text}")
print(f"Token IDs: {tokens}")
print(f"Token pieces: {pieces}")
print(f"解码: {sp.decode(tokens)}")

2.3 分词器效率对比

分词器算法中文支持OOV处理压缩率代表模型
BPE贪心合并需预分词字符级回退高GPT-2/3/4
SentencePiece-BPEBPE原生字节回退高Llama, T5
SentencePiece-Unigram概率分词原生字节回退中-高ALBERT, XLNet
WordLevel词典查找需预分词UNK token低早期BERT
WordPiece贪心最长匹配需预分词字符级中BERT, DistilBERT
TiktokenBPE(快速)字节级无OOV高GPT-4, o1
Python
# 分词效率对比实验
import tiktoken

# GPT-4的cl100k_base分词器
enc = tiktoken.get_encoding("cl100k_base")

test_texts = [
    "The quick brown fox jumps over the lazy dog.",
    "大模型架构原理深度解析:从Transformer到Mamba",
    "def fibonacci(n): return n if n <= 1 else fibonacci(n-1) + fibonacci(n-2)",
    "α β γ δ ε ζ η θ ι κ λ μ ν ξ ο π ρ σ τ υ φ χ ψ ω",
]

print(f"{'文本类型':>12} {'字符数':>8} {'Token数':>8} {'压缩率':>8} {'字节/Token':>10}")
for text in test_texts:
    tokens = enc.encode(text)
    n_chars = len(text)
    n_tokens = len(tokens)
    n_bytes = len(text.encode("utf-8"))
    compression = n_chars / n_tokens
    bytes_per_token = n_bytes / n_tokens
    label = "英文" if text.isascii() else ("代码" if "def" in text else ("中文" if "大" in text else "希腊文"))
    print(f"{label:>12} {n_chars:>8} {n_tokens:>8} {compression:>7.2f} {bytes_per_token:>9.2f}")

3. MinHash+LSH去重完整实现

3.1 去重的必要性

训练数据中的重复内容会导致模型记忆而非泛化,增加过拟合风险。研究表明,即使10%的重复数据也可能显著降低模型性能。去重是大模型数据pipeline的关键步骤。

3.2 MinHash算法原理

MinHash通过随机哈希函数估计Jaccard相似度。对于集合A和B,MinHash的碰撞概率等于Jaccard相似度:Pr[min(π(A)) = min(π(B))] = J(A,B),其中π是随机排列。

Python
import hashlib
import numpy as np

class MinHash:
    """MinHash签名生成器"""
    def __init__(self, num_perm=128, seed=42):
        self.num_perm = num_perm
        # 生成随机哈希函数参数: h(x) = (a*x + b) % prime
        rng = np.random.RandomState(seed)
        self.prime = (1 << 61) - 1  # Mersenne prime
        self.a = rng.randint(1, self.prime, num_perm)
        self.b = rng.randint(0, self.prime, num_perm)

    def hash_token(self, token):
        """将token映射到大整数"""
        return int(hashlib.md5(token.encode()).hexdigest(), 16)

    def compute_signature(self, tokens):
        """计算token集合的MinHash签名"""
        token_hashes = [self.hash_token(t) for t in tokens]
        signature = np.full(self.num_perm, self.prime, dtype=np.int64)
        for h in token_hashes:
            # 对每个哈希函数计算min值
            perm_hashes = (self.a * h + self.b) % self.prime
            signature = np.minimum(signature, perm_hashes)
        return signature

    def estimate_jaccard(self, sig1, sig2):
        """从签名估计Jaccard相似度"""
        return np.mean(sig1 == sig2)

# 使用示例
mh = MinHash(num_perm=128)
doc1 = "the quick brown fox jumps over the lazy dog".split()
doc2 = "the quick brown fox jumps over the lazy cat".split()
doc3 = "a completely different document about machine learning".split()
sig1 = mh.compute_signature(doc1)
sig2 = mh.compute_signature(doc2)
sig3 = mh.compute_signature(doc3)
print(f"J(doc1, doc2) ≈ {mh.estimate_jaccard(sig1, sig2):.3f}")
print(f"J(doc1, doc3) ≈ {mh.estimate_jaccard(sig1, sig3):.3f}")

3.3 LSH索引加速

LSH(Locality-Sensitive Hashing)将相似的签名映射到相同桶中,避免O(N²)的两两比较。通过将签名分成多个band,每个band独立哈希,相似文档有更高概率落入同一桶。

Python
class LSHIndex:
    """LSH索引用于快速近似最近邻搜索"""
    def __init__(self, num_perm=128, num_bands=32,
                 threshold=0.8):
        self.num_perm = num_perm
        self.num_bands = num_bands
        self.rows_per_band = num_perm // num_bands
        self.threshold = threshold
        self.buckets = {}  # band_idx -> {hash: [doc_ids]}

    def _band_hash(self, signature, band_idx):
        """计算一个band的哈希值"""
        start = band_idx * self.rows_per_band
        end = start + self.rows_per_band
        return hash(tuple(signature[start:end]))

    def insert(self, doc_id, signature):
        """将文档插入LSH索引"""
        for band_idx in range(self.num_bands):
            h = self._band_hash(signature, band_idx)
            key = (band_idx, h)
            if key not in self.buckets:
                self.buckets[key] = []
            self.buckets[key].append(doc_id)

    def query(self, signature):
        """查询候选重复文档"""
        candidates = set()
        for band_idx in range(self.num_bands):
            h = self._band_hash(signature, band_idx)
            key = (band_idx, h)
            if key in self.buckets:
                candidates.update(self.buckets[key])
        return candidates

# 完整去重pipeline
def deduplicate(documents, threshold=0.8):
    """完整去重流程"""
    mh = MinHash(num_perm=128)
    lsh = LSHIndex(num_perm=128, num_bands=32, threshold=threshold)
    signatures = {}
    # 第一遍: 计算签名并构建索引
    for doc_id, text in enumerate(documents):
        tokens = set(text.lower().split())  # shingles
        sig = mh.compute_signature(tokens)
        signatures[doc_id] = sig
        lsh.insert(doc_id, sig)
    # 第二遍: 查找并标记重复
    to_remove = set()
    for doc_id in range(len(documents)):
        if doc_id in to_remove:
            continue
        candidates = lsh.query(signatures[doc_id])
        for cand_id in candidates:
            if cand_id <= doc_id:
                continue
            sim = mh.estimate_jaccard(signatures[doc_id], signatures[cand_id])
            if sim >= threshold:
                to_remove.add(cand_id)
    return [doc for i, doc in enumerate(documents) if i not in to_remove], to_remove

4. 质量分类器训练

4.1 基于fastText的质量分类

质量分类器是大模型数据筛选的核心组件。通常使用fastText训练二分类器,区分高质量文本(如Wikipedia、书籍)和低质量文本(随机网页)。

Python
import fasttext
import os

def prepare_training_data(high_quality_docs, low_quality_docs, output_path):
    """准备fastText格式的训练数据"""
    with open(output_path, "w") as f:
        for doc in high_quality_docs:
            # 高质量标记为__label__1
            text = doc.replace("\n", " ").strip()
            f.write(f"__label__1 {text}\n")
        for doc in low_quality_docs:
            text = doc.replace("\n", " ").strip()
            f.write(f"__label__0 {text}\n")

def train_quality_classifier(train_path, model_path="quality_model.bin"):
    """训练fastText质量分类器"""
    model = fasttext.train_supervised(
        input=train_path,
        epoch=25,
        lr=0.1,
        wordNgrams=2,
        dim=100,
        minCount=3,
        bucket=2000000,
        loss="softmax",
        verbose=2,
    )
    model.save_model(model_path)
    return model

def filter_by_quality(model, text, threshold=0.5):
    """使用分类器过滤文本"""
    label, probs = model.predict(text.replace("\n", " "), k=2)
    # 获取高质量概率
    for l, p in zip(label, probs):
        if l == "__label__1":
            return p >= threshold
    return False

# 使用示例
# model = train_quality_classifier("train_data.txt")
# is_high_quality = filter_by_quality(model, some_text, threshold=0.8)

4.2 基于ML的高级质量分类

除了fastText,还可以使用预训练语言模型作为质量分类器。例如,用一个小的BERT模型在人工标注的数据上微调,获得更精准的质量判断。

Python
import torch
import torch.nn as nn
from transformers import AutoModel, AutoTokenizer

class QualityClassifier(nn.Module):
    """基于预训练模型的质量分类器"""
    def __init__(self, model_name="bert-base-uncased"):
        super().__init__()
        self.encoder = AutoModel.from_pretrained(model_name)
        self.classifier = nn.Linear(self.encoder.config.hidden_size, 2)
        self.dropout = nn.Dropout(0.1)

    def forward(self, input_ids, attention_mask):
        outputs = self.encoder(input_ids, attention_mask=attention_mask)
        cls_output = outputs.last_hidden_state[:, 0]  # [CLS] token
        logits = self.classifier(self.dropout(cls_output))
        return logits

def train_quality_model(train_texts, train_labels, epochs=3):
    """训练质量分类器"""
    tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
    model = QualityClassifier()
    optimizer = torch.optim.AdamW(model.parameters(), lr=2e-5)
    criterion = nn.CrossEntropyLoss()
    for epoch in range(epochs):
        for batch_texts, batch_labels in get_batches(train_texts, train_labels):
            inputs = tokenizer(batch_texts, padding=True, truncation=True,
                             max_length=512, return_tensors="pt")
            logits = model(inputs["input_ids"], inputs["attention_mask"])
            loss = criterion(logits, batch_labels)
            loss.backward()
            optimizer.step()
            optimizer.zero_grad()
    return model

5. Llama 3数据Pipeline详解

5.1 Llama 3数据处理流程

Llama 3使用了15T tokens的训练数据,其数据处理pipeline代表了当前最先进的实践:

阶段操作数据量变化关键技术
1. 数据收集Web crawl + 代码 + 多语种~100TBCommonCrawl, GitHub
2. HTML提取WARC -> 纯文本~50TBtrafilatura, resiliparse
3. 语言识别过滤非目标语言~40TBfastText langid
4. 质量过滤分类器+规则过滤~15TBfastText, 启发式规则
5. 安全过滤PII+毒性+CSAM~14TB正则, 分类器
6. 去重精确+模糊去重~8TBMinHash+LSH
7. 分词BPE编码~15T tokensSentencePiece
8. 数据混合按比例采样~15T tokensDoReMi/人工配比

5.2 数据混合配比

Python
# Llama 3数据混合配比 (近似)
llama3_mixture = {
    "web_english": 0.50,
    "web_other_langs": 0.25,
    "code": 0.10,
    "books": 0.05,
    "wikipedia": 0.04,
    "arxiv": 0.02,
    "conversations": 0.03,
    "synthetic": 0.01,
}

print("Llama 3 数据混合配比:")
for source, ratio in sorted(llama3_mixture.items(), key=lambda x: -x[1]):
    bar = "█" * int(ratio * 50)
    print(f"  {source:20s}: {ratio:5.1%} {bar}")
print(f"  {'总计':20s}: {sum(llama3_mixture.values()):5.1%}")

6. 数据污染检测与数据增强

6.1 数据污染检测

训练数据中包含测试集数据(数据污染)会导致评估结果虚高。检测方法包括:

Python
def detect_contamination(train_data, eval_data, threshold=0.8):
    """检测训练数据中的评估集污染"""
    mh = MinHash(num_perm=256)
    lsh = LSHIndex(num_perm=256, num_bands=64)
    # 构建评估数据索引
    eval_sigs = {}
    for i, text in enumerate(eval_data):
        tokens = set(text.lower().split())
        sig = mh.compute_signature(tokens)
        eval_sigs[i] = sig
        lsh.insert(i, sig)
    # 检查训练数据
    contamination = []
    for j, text in enumerate(train_data):
        tokens = set(text.lower().split())
        sig = mh.compute_signature(tokens)
        candidates = lsh.query(sig)
        for cand in candidates:
            sim = mh.estimate_jaccard(sig, eval_sigs[cand])
            if sim >= threshold:
                contamination.append((j, cand, sim))
                break
    return contamination

6.2 数据增强策略

Python
def back_translate(text, src_lang="en", tgt_lang="fr"):
    """回译增强: 原文 -> 译文 -> 回译文"""
    translated = translate(text, src_lang, tgt_lang)
    back_translated = translate(translated, tgt_lang, src_lang)
    return back_translated

def paraphrase_augment(text, model, n_variants=3):
    """使用模型生成改写"""
    prompts = [f"Paraphrase: {text}" for _ in range(n_variants)]
    variants = [model.generate(p, temperature=0.7) for p in prompts]
    return variants

def synthetic_data_gen(prompt, model, n_samples=1000):
    """合成数据生成"""
    samples = []
    for _ in range(n_samples):
        output = model.generate(prompt, temperature=0.8, top_p=0.95)
        samples.append(output)
    return samples

7. Token化效率深度分析

7.1 不同语言的Token效率

分词器对不同语言的压缩效率差异巨大。英文通常每token约4字符,而中文每token约1-2字符,这意味着相同语义内容用中文表示需要更多token。

语言字符/token字节/token相对效率原因
英文~4.0~4.01.0x (基线)BPE对英文优化好
中文~1.5~4.5~0.4xUTF-3字节+词表覆盖不足
日文~1.3~3.9~0.3x混合脚本+字符多
韩文~1.4~4.2~0.35x组合字符
代码~3.5~3.5~0.9x特殊符号多
阿拉伯文~2.0~4.0~0.5xRTL+连写
Python
import tiktoken
enc = tiktoken.get_encoding("cl100k_base")

# 多语言token效率对比
test_cases = {
    "English": "The transformer architecture has revolutionized natural language processing.",
    "Chinese": "Transformer架构彻底改变了自然语言处理领域。",
    "Japanese": "Transformerアーキテクチャは自然言語処理を革命しました。",
    "Korean": "Transformer 아키텍처는 자연어 처리를 혁신했습니다.",
    "Code": "def transformer(x): return attention(x) + ffn(x)",
    "Arabic": "لقد أحدثت بنية المحول ثورة في معالجة اللغة الطبيعية.",
}

print(f"{'语言':>10} {'字符数':>6} {'字节数':>6} {'Token数':>7} {'字符/Token':>10} {'字节/Token':>10}")
for lang, text in test_cases.items():
    n_chars = len(text)
    n_bytes = len(text.encode("utf-8"))
    n_tokens = len(enc.encode(text))
    print(f"{lang:>10} {n_chars:>6} {n_bytes:>6} {n_tokens:>7} {n_chars/n_tokens:>9.2f} {n_bytes/n_tokens:>9.2f}")

7.2 词表大小的影响

词表大小是分词器的关键超参数。更大的词表可以更好地表示罕见词和多语言文本,但增加了embedding参数量和softmax计算量。

Python
# 词表大小对模型参数的影响
def vocab_impact(vocab_size, d_model=4096):
    """计算词表对参数量的影响"""
    # embedding + lm_head (通常tied)
    embed_params = vocab_size * d_model  # 如果tied则只一份
    # softmax计算量正比于vocab_size
    softmax_flops_per_token = vocab_size * d_model
    return embed_params, softmax_flops_per_token

print(f"{'词表大小':>10} {'Embedding参数':>15} {'占70B模型比':>12}")
total_params = 70e9
for vs in [32000, 64000, 100000, 128000, 256000]:
    ep, sf = vocab_impact(vs)
    print(f"{vs:>10} {ep/1e6:>12.1f}M {ep/total_params*100:>10.2f}%")

8. 高级去重策略

8.1 多级去重

大规模数据去重通常采用多级策略:文档级去重(精确匹配+模糊匹配)、段落级去重(去除重复段落)、n-gram去重(检测局部重复)。

Python
def multi_level_dedup(documents):
    """多级去重策略"""
    # Level 1: 精确去重 (URL + 内容hash)
    seen_hashes = set()
    after_exact = []
    for doc in documents:
        h = hash(doc["text"])
        if h not in seen_hashes:
            seen_hashes.add(h)
            after_exact.append(doc)
    # Level 2: 模糊去重 (MinHash+LSH, Jaccard > 0.8)
    after_fuzzy, _ = deduplicate(after_exact, threshold=0.8)
    # Level 3: 段落级去重
    after_para = [dedup_paragraphs(doc) for doc in after_fuzzy]
    # Level 4: n-gram去重 (检测局部重复)
    after_ngram = [dedup_ngrams(doc, n=13) for doc in after_para]
    return after_ngram

def dedup_ngrams(doc, n=13, threshold=0.5):
    """检测并去除高频n-gram重复"""
    tokens = doc["text"].split()
    ngram_counts = {}
    for i in range(len(tokens) - n + 1):
        ngram = tuple(tokens[i:i+n])
        ngram_counts[ngram] = ngram_counts.get(ngram, 0) + 1
    # 如果某n-gram出现过多, 标记为低质量
    max_count = max(ngram_counts.values()) if ngram_counts else 0
    if max_count > 3:
        return None  # 丢弃重复文档
    return doc

8.2 跨语种去重

相同内容的不同语言翻译版本也应去重,以避免模型偏好某种语言。跨语种去重使用多语言句子嵌入计算语义相似度。

9. 数据质量评估指标

9.1 质量评估维度

维度指标计算方法阈值
信息密度熵率字符级Shannon熵>3.5 bits/char
语言流畅性困惑度小模型PPL<100
词汇多样性TTR类型/Token比>0.3
结构完整性句子比例有效句子/总行数>0.7
内容独特性重复率n-gram重复比例<0.1
事实可靠性分类器分质量分类器>0.8
Python
import math
from collections import Counter

def assess_quality(text):
    """综合质量评估"""
    scores = {}
    # 1. 信息熵
    char_freq = Counter(text)
    total = len(text)
    entropy = -sum((c/total) * math.log2(c/total) for c in char_freq.values())
    scores["entropy"] = entropy
    # 2. 词汇多样性 (Type-Token Ratio)
    words = text.lower().split()
    ttr = len(set(words)) / len(words) if words else 0
    scores["ttr"] = ttr
    # 3. 平均句长
    sentences = [s for s in text.split(".") if len(s.split()) > 2]
    avg_sent_len = sum(len(s.split()) for s in sentences) / len(sentences) if sentences else 0
    scores["avg_sent_len"] = avg_sent_len
    # 4. 重复行比例
    lines = text.split("\n")
    unique_ratio = len(set(lines)) / len(lines) if lines else 0
    scores["unique_ratio"] = unique_ratio
    # 5. 综合评分
    quality_score = (
        0.3 * min(entropy / 4.5, 1.0) +
        0.2 * min(ttr / 0.5, 1.0) +
        0.2 * min(avg_sent_len / 20, 1.0) +
        0.3 * unique_ratio
    )
    scores["overall"] = quality_score
    return scores

# 示例评估
high_q = "The transformer architecture, introduced in 2017, uses self-attention to process input sequences. It has become the dominant architecture for NLP tasks."
low_q = "click here click here click here buy now buy now click here click here special offer"
print("高质量文本:", assess_quality(high_q))
print("低质量文本:", assess_quality(low_q))

10. PII检测与安全过滤

10.1 PII类型与检测

个人身份信息(PII)检测是数据安全的关键环节。需要检测和移除的PII类型包括:邮箱、电话号码、社保号、信用卡号、IP地址、物理地址等。

Python
import re

class PIIDetector:
    """PII检测与移除"""
    def __init__(self):
        self.patterns = {
            "email": re.compile(r'\b[\w.+-]+@[\w-]+\.[\w.-]+\b'),
            "phone": re.compile(r'\b(?:\+?1[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}\b'),
            "ssn": re.compile(r'\b\d{3}-\d{2}-\d{4}\b'),
            "credit_card": re.compile(r'\b(?:\d[ -]*?){13,16}\b'),
            "ip": re.compile(r'\b(?:\d{1,3}\.){3}\d{1,3}\b'),
            "url": re.compile(r'https?://[^\s]+'),
        }

    def detect(self, text):
        """检测所有PII"""
        found = {}
        for pii_type, pattern in self.patterns.items():
            matches = pattern.findall(text)
            if matches:
                found[pii_type] = matches
        return found

    def remove(self, text, replacement="[REDACTED]"):
        """移除所有PII"""
        for pattern in self.patterns.values():
            text = pattern.sub(replacement, text)
        return text

detector = PIIDetector()
test = "Contact john@example.com or call 555-123-4567. IP: 192.168.1.1"
print("检测到:", detector.detect(test))
print("清理后:", detector.remove(test))

11. 数据Pipeline工程实践

11.1 分布式数据处理

Python
# 使用Apache Beam/Spark进行分布式数据处理
import apache_beam as beam

def run_pipeline(input_pattern, output_path):
    """分布式数据处理pipeline"""
    with beam.Pipeline() as p:
        (p
         | "Read" >> beam.io.ReadFromText(input_pattern)
         | "ParseHTML" >> beam.Map(parse_html)
         | "FilterLang" >> beam.Filter(filter_language)
         | "QualityScore" >> beam.Map(score_quality)
         | "FilterQuality" >> beam.Filter(lambda x: x["score"] > 0.5)
         | "RemovePII" >> beam.Map(remove_pii)
         | "Dedup" >> beam.GroupByKey() | beam.Map(dedup_group)
         | "Write" >> beam.io.WriteToText(output_path))

11.2 数据版本管理

大模型数据需要严格的版本管理,确保训练可复现。常用工具包括DVC(Data Version Control)和LakeFS,支持TB级数据的版本追踪和分支管理。

附录A. 数据工程最佳实践

A.1 数据Pipeline检查清单

阶段检查项通过标准
采集URL覆盖率>95%目标域名
提取文本提取准确率>90%正文正确
语言识别语言分类准确率>98%主要语言
质量过滤高质量保留率10-30%原始数据
去重重复率<1%剩余重复
PII移除PII残留率<0.01%
分词token效率符合预期范围
混合领域分布符合目标配比

A.2 数据迭代策略

数据工程是迭代过程:训练小模型→评估→识别数据问题→改进pipeline→重新训练。每轮迭代应关注模型在各类数据上的表现差异,针对性改进数据质量。

Python
# 数据迭代工作流
def data_iteration(raw_data, model_fn, eval_fn, n_iters=5):
    """数据迭代优化流程"""
    data = raw_data
    for i in range(n_iters):
        # 1. 处理数据
        processed = process_pipeline(data)
        # 2. 训练小模型
        model = model_fn(processed)
        # 3. 评估, 识别弱项
        eval_results = eval_fn(model)
        weak_areas = identify_weaknesses(eval_results)
        # 4. 针对性改进pipeline
        data = improve_pipeline(raw_data, weak_areas)
        print(f"Iter {i+1}: loss={eval_results['loss']:.3f}, "
              f"weak={weak_areas}")
    return model, data

附录B. 分词器训练实践

B.1 BPE训练超参数

参数典型值影响
词表大小32K-128K更大→更好覆盖, 更多参数
初始字符集UTF-8字节保证可表示所有文本
合并次数=词表大小-256决定词表规模
训练数据量10-100MB足够统计频率即可
正则预处理分词模式影响合并边界

B.2 多语言分词器设计

多语言分词器需要平衡不同语言的token效率。常见策略:按语言比例采样训练数据,确保低资源语言有足够合并机会;或为每种语言分配固定词表配额。

Python
# 多语言BPE训练数据采样
def sample_multilingual(data_by_lang, target_ratio, total_size):
    """按目标比例采样多语言数据"""
    samples = {}
    for lang, data in data_by_lang.items():
        n = int(total_size * target_ratio.get(lang, 0.01))
        if len(data) > n:
            import random
            samples[lang] = random.sample(data, n)
        else:
            samples[lang] = data  # 数据不足, 全用
    return samples

# GPT-4o多语言词表配比 (估计)
ratios = {"en": 0.40, "zh": 0.15, "ja": 0.08, "ko": 0.05,
          "code": 0.15, "other": 0.17}
print("词表配比:", ratios)
数据处理Pipeline流程 爬取 提取 过滤 去重 分词 训练
数据质量分布: 长尾效应 高质量(10%) 低质量(90%)