数据来源、分词器、MinHash去重、质量分类、Llama3 Pipeline、污染检测
大模型训练数据的质量和多样性直接决定模型能力。现代大模型的数据来源主要包括以下几类:
| 数据来源 | 占比(典型) | 信息密度 | 质量 | 代表数据集 |
|---|---|---|---|---|
| 网页爬取 | 60-80% | 低-中 | 参差不齐 | CommonCrawl, RefinedWeb |
| 代码仓库 | 5-15% | 高 | 高 | GitHub, StarCoderData |
| 书籍/论文 | 5-10% | 高 | 高 | Books3, arXiv, S2ORC |
| 对话数据 | 3-8% | 中 | 中-高 | ShareGPT, OpenAssistant |
| 百科知识 | 2-5% | 高 | 高 | Wikipedia, Wikidata |
| 合成数据 | 5-15% | 可变 | 可变 | 模型生成, 回译 |
| 专有数据 | 可变 | 高 | 高 | 内部数据, 标注数据 |
CommonCrawl是全球最大的公开网页爬取数据集,每月发布数十TB数据。其处理流程是大模型数据pipeline的核心:
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
字节对编码(Byte Pair Encoding, BPE)是大模型最常用的分词算法。其核心思想是从字符级开始,迭代合并最高频的字符对,直到达到目标词表大小。
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
SentencePiece是Google开发的分词库,支持BPE和Unigram两种算法。与纯BPE不同,SentencePiece直接在原始Unicode字符上操作,不依赖空格分词,因此对中文、日文等无空格语言更友好。
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)}")
| 分词器 | 算法 | 中文支持 | OOV处理 | 压缩率 | 代表模型 |
|---|---|---|---|---|---|
| BPE | 贪心合并 | 需预分词 | 字符级回退 | 高 | GPT-2/3/4 |
| SentencePiece-BPE | BPE | 原生 | 字节回退 | 高 | Llama, T5 |
| SentencePiece-Unigram | 概率分词 | 原生 | 字节回退 | 中-高 | ALBERT, XLNet |
| WordLevel | 词典查找 | 需预分词 | UNK token | 低 | 早期BERT |
| WordPiece | 贪心最长匹配 | 需预分词 | 字符级 | 中 | BERT, DistilBERT |
| Tiktoken | BPE(快速) | 字节级 | 无OOV | 高 | GPT-4, o1 |
# 分词效率对比实验
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}")
训练数据中的重复内容会导致模型记忆而非泛化,增加过拟合风险。研究表明,即使10%的重复数据也可能显著降低模型性能。去重是大模型数据pipeline的关键步骤。
MinHash通过随机哈希函数估计Jaccard相似度。对于集合A和B,MinHash的碰撞概率等于Jaccard相似度:Pr[min(π(A)) = min(π(B))] = J(A,B),其中π是随机排列。
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}")
LSH(Locality-Sensitive Hashing)将相似的签名映射到相同桶中,避免O(N²)的两两比较。通过将签名分成多个band,每个band独立哈希,相似文档有更高概率落入同一桶。
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
质量分类器是大模型数据筛选的核心组件。通常使用fastText训练二分类器,区分高质量文本(如Wikipedia、书籍)和低质量文本(随机网页)。
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)
除了fastText,还可以使用预训练语言模型作为质量分类器。例如,用一个小的BERT模型在人工标注的数据上微调,获得更精准的质量判断。
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
Llama 3使用了15T tokens的训练数据,其数据处理pipeline代表了当前最先进的实践:
| 阶段 | 操作 | 数据量变化 | 关键技术 |
|---|---|---|---|
| 1. 数据收集 | Web crawl + 代码 + 多语种 | ~100TB | CommonCrawl, GitHub |
| 2. HTML提取 | WARC -> 纯文本 | ~50TB | trafilatura, resiliparse |
| 3. 语言识别 | 过滤非目标语言 | ~40TB | fastText langid |
| 4. 质量过滤 | 分类器+规则过滤 | ~15TB | fastText, 启发式规则 |
| 5. 安全过滤 | PII+毒性+CSAM | ~14TB | 正则, 分类器 |
| 6. 去重 | 精确+模糊去重 | ~8TB | MinHash+LSH |
| 7. 分词 | BPE编码 | ~15T tokens | SentencePiece |
| 8. 数据混合 | 按比例采样 | ~15T tokens | DoReMi/人工配比 |
# 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%}")
训练数据中包含测试集数据(数据污染)会导致评估结果虚高。检测方法包括:
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
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
分词器对不同语言的压缩效率差异巨大。英文通常每token约4字符,而中文每token约1-2字符,这意味着相同语义内容用中文表示需要更多token。
| 语言 | 字符/token | 字节/token | 相对效率 | 原因 |
|---|---|---|---|---|
| 英文 | ~4.0 | ~4.0 | 1.0x (基线) | BPE对英文优化好 |
| 中文 | ~1.5 | ~4.5 | ~0.4x | UTF-3字节+词表覆盖不足 |
| 日文 | ~1.3 | ~3.9 | ~0.3x | 混合脚本+字符多 |
| 韩文 | ~1.4 | ~4.2 | ~0.35x | 组合字符 |
| 代码 | ~3.5 | ~3.5 | ~0.9x | 特殊符号多 |
| 阿拉伯文 | ~2.0 | ~4.0 | ~0.5x | RTL+连写 |
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}")
词表大小是分词器的关键超参数。更大的词表可以更好地表示罕见词和多语言文本,但增加了embedding参数量和softmax计算量。
# 词表大小对模型参数的影响
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}%")
大规模数据去重通常采用多级策略:文档级去重(精确匹配+模糊匹配)、段落级去重(去除重复段落)、n-gram去重(检测局部重复)。
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
相同内容的不同语言翻译版本也应去重,以避免模型偏好某种语言。跨语种去重使用多语言句子嵌入计算语义相似度。
| 维度 | 指标 | 计算方法 | 阈值 |
|---|---|---|---|
| 信息密度 | 熵率 | 字符级Shannon熵 | >3.5 bits/char |
| 语言流畅性 | 困惑度 | 小模型PPL | <100 |
| 词汇多样性 | TTR | 类型/Token比 | >0.3 |
| 结构完整性 | 句子比例 | 有效句子/总行数 | >0.7 |
| 内容独特性 | 重复率 | n-gram重复比例 | <0.1 |
| 事实可靠性 | 分类器分 | 质量分类器 | >0.8 |
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))
个人身份信息(PII)检测是数据安全的关键环节。需要检测和移除的PII类型包括:邮箱、电话号码、社保号、信用卡号、IP地址、物理地址等。
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))
# 使用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))
大模型数据需要严格的版本管理,确保训练可复现。常用工具包括DVC(Data Version Control)和LakeFS,支持TB级数据的版本追踪和分支管理。
| 阶段 | 检查项 | 通过标准 |
|---|---|---|
| 采集 | URL覆盖率 | >95%目标域名 |
| 提取 | 文本提取准确率 | >90%正文正确 |
| 语言识别 | 语言分类准确率 | >98%主要语言 |
| 质量过滤 | 高质量保留率 | 10-30%原始数据 |
| 去重 | 重复率 | <1%剩余重复 |
| PII移除 | PII残留率 | <0.01% |
| 分词 | token效率 | 符合预期范围 |
| 混合 | 领域分布 | 符合目标配比 |
数据工程是迭代过程:训练小模型→评估→识别数据问题→改进pipeline→重新训练。每轮迭代应关注模型在各类数据上的表现差异,针对性改进数据质量。
# 数据迭代工作流
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
| 参数 | 典型值 | 影响 |
|---|---|---|
| 词表大小 | 32K-128K | 更大→更好覆盖, 更多参数 |
| 初始字符集 | UTF-8字节 | 保证可表示所有文本 |
| 合并次数 | =词表大小-256 | 决定词表规模 |
| 训练数据量 | 10-100MB | 足够统计频率即可 |
| 正则预处理 | 分词模式 | 影响合并边界 |
多语言分词器需要平衡不同语言的token效率。常见策略:按语言比例采样训练数据,确保低资源语言有足够合并机会;或为每种语言分配固定词表配额。
# 多语言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)