Split View: LLM 학습 데이터 전처리 완전 가이드 — 웹 크롤부터 토큰 패킹까지, 최신 논문과 함께
LLM 학습 데이터 전처리 완전 가이드 — 웹 크롤부터 토큰 패킹까지, 최신 논문과 함께
- 들어가며 — 모델 품질의 8할이 결정되는 곳
- 전체 파이프라인 조감도
- ① 본문 추출 — HTML에서 진짜 글만
- ② 언어 식별 — 빠르고 조용한 관문
- ③ 품질 필터링 — 휴리스틱에서 분류기로
- ④ 중복 제거 — 가장 효과 대비 저평가된 단계
- ⑤·⑥ PII·독성, 그리고 오염 제거
- ⑦ 토크나이즈와 시퀀스 패킹 — 마지막 공정
- SFT 데이터는 다르게 — 소수 정예의 세계
- 도구 상자 — 직접 다 만들 필요 없다
- 흐름을 바꾼 논문들 — 읽기 순서 추천
- 마치며
- 참고 자료
들어가며 — 모델 품질의 8할이 결정되는 곳
AI 모델 개발 생애주기에서 "쓰레기 1TB보다 좋은 데이터 1GB"라고 썼습니다. 이 글은 그 문장의 실행편입니다 — 인터넷의 원시 텍스트가 학습 가능한 토큰이 되기까지 실제로 거치는 공정을, 각 단계의 도구와 그 단계를 정립한 논문과 함께 걷습니다. 최근 몇 년의 흥미로운 발견은, 프런티어 랩들의 격차가 모델 아키텍처보다 바로 이 파이프라인에서 벌어진다는 것입니다(FineWeb·DCLM 논문이 이를 공개 데이터로 증명했습니다).
전체 파이프라인 조감도
수집(CommonCrawl 등)
→ ① 본문 추출 (HTML → 텍스트)
→ ② 언어 식별
→ ③ 품질 필터링 (휴리스틱 → 모델 분류기)
→ ④ 중복 제거 (정확 → 근사 MinHash)
→ ⑤ PII·독성 처리
→ ⑥ 벤치마크 오염 제거 (decontamination)
→ ⑦ 토크나이즈 + 시퀀스 패킹
→ 학습
순서에도 이유가 있습니다 — 싼 필터를 앞에, 비싼 필터를 뒤에 두어 비싼 연산(분류기, MinHash)이 처리할 문서 수를 줄입니다. 각 단계를 봅시다.
① 본문 추출 — HTML에서 진짜 글만
사전학습 데이터의 원천은 대부분 CommonCrawl(웹 전체의 주기적 크롤 아카이브)입니다. 여기서 첫 갈림길이 나옵니다: 미리 추출된 WET 텍스트를 쓸 것인가, 원시 WARC(HTML)에서 직접 추출할 것인가. RefinedWeb과 FineWeb의 공통 결론은 WARC에서 trafilatura 같은 추출기로 직접 뽑는 쪽이 품질이 확연히 좋다는 것입니다 — WET에는 내비게이션 메뉴, 쿠키 배너, 푸터 같은 보일러플레이트가 잔뜩 섞여 있기 때문입니다. 본문 추출의 품질이 이후 모든 단계의 상한선을 정합니다.
② 언어 식별 — 빠르고 조용한 관문
fastText 계열의 언어 분류기로 문서 언어를 판별하고 대상 언어(예: 한국어 데이터셋이면 ko)만 남깁니다. 단순해 보이지만 함정이 있습니다 — 짧은 문서·코드 혼합 문서에서 오판이 잦고, 저자원 언어일수록 이 관문에서 좋은 데이터가 함께 버려집니다. 다국어 모델을 만든다면 언어별 임계값을 따로 튜닝하는 것이 정석입니다.
③ 품질 필터링 — 휴리스틱에서 분류기로
두 세대의 기법이 겹쳐 쓰입니다.
휴리스틱 규칙(Gopher rules 계열) — 문서 길이, 평균 단어 길이, 기호/단어 비율, 불릿·해시태그 비율, "lorem ipsum" 포함 여부 같은 통계 규칙 수십 개로 명백한 쓰레기를 걸러냅니다. Gopher 논문이 정립했고 거의 모든 파이프라인이 변형해 씁니다.
모델 기반 분류기 — 최근의 승부처입니다. FineWeb-Edu는 LLM에게 "이 문서의 교육적 가치"를 채점시킨 라벨로 작은 분류기를 학습시켜 고품질 부분집합을 골라냈고, DCLM은 좋은 데이터(instruct 스타일)로 학습한 fastText 분류기 하나가 정교한 파이프라인 조합을 이길 수 있음을 보였습니다. 교훈: "품질"의 정의를 데이터가 아니라 분류기를 학습시키는 기준으로 옮기면, 파이프라인이 단순해지면서 성능은 올라갑니다.
여기서 주의 하나 — 필터는 항상 분포를 편향시킵니다. 교육적 가치 필터는 구어체·소수 방언·창작 텍스트를 깎아냅니다. 무엇을 버리고 있는지 샘플을 눈으로 보는 습관이 필터 튜닝의 절반입니다.
④ 중복 제거 — 가장 효과 대비 저평가된 단계
웹 크롤의 상당량은 중복입니다(미러 사이트, 보일러플레이트, 재게시). 중복은 학습에서 특정 텍스트를 사실상 여러 에폭 돌리는 효과를 내 암기와 벤치마크 오염을 부풀리고, 계산을 낭비합니다.
- 정확 중복 제거: 문서(또는 문단) 해시로 완전 일치를 제거합니다. 싸고 확실합니다.
- 근사 중복 제거 — MinHash LSH: "거의 같은" 문서를 잡는 표준 기법입니다. 문서를 n-gram 집합(shingle)으로 만들고, MinHash 서명으로 자카드 유사도를 근사한 뒤, LSH 밴딩으로 비교 쌍을 후보군으로 좁힙니다 — 수십억 문서에서도 전수 비교 없이 동작하는 이유입니다.
- 라인 수준 중복 제거: 여러 문서에 반복되는 라인(내비게이션 텍스트 등)을 제거합니다. RefinedWeb이 강조한 기법입니다.
흥미로운 반전도 있습니다 — FineWeb은 크롤 스냅샷 전체를 가로질러 과격하게 중복 제거하는 것보다 스냅샷별 중복 제거가 더 나은 결과를 냈다고 보고했습니다. 중복 제거조차 "많을수록 좋다"가 아니라 측정하며 조절할 대상입니다.
⑤·⑥ PII·독성, 그리고 오염 제거
PII 처리: 이메일·전화번호·IP 같은 패턴은 정규식으로 탐지해 제거하거나 플레이스홀더로 치환합니다(Dolma 툴킷이 이 단계의 좋은 공개 구현입니다). 법무 검토가 사치가 아니라는 이야기는 모델 개발 편에서 한 그대로입니다.
벤치마크 오염 제거(decontamination): 평가 셋(MMLU, GSM8K 등)의 문항이 학습 데이터에 섞여 있으면 벤치마크 점수가 능력 없이 오릅니다. 평가 셋의 n-gram과 겹치는 학습 문서를 제거하는 것이 표준 절차이고, 양자화 편에서 말한 "새 모델 점수를 볼 때의 의심"이 바로 이 단계의 부재를 향합니다. 자체 평가 셋을 만들었다면 그것도 오염 제거 목록에 넣어야 합니다 — eval-first 원칙의 데이터판입니다.
⑦ 토크나이즈와 시퀀스 패킹 — 마지막 공정
정제된 문서는 토크나이저(BPE 계열)로 토큰 ID가 되고, 고정 길이 시퀀스로 잘려 학습기에 들어갑니다. 여기서 실무 요점 두 가지:
- 시퀀스 패킹: 문서들이 시퀀스 길이보다 짧으면 패딩이 낭비됩니다. 여러 문서를 EOS 토큰으로 이어 붙여 시퀀스를 꽉 채우는 패킹이 표준이고, 문서 경계를 넘는 어텐션을 막는 마스킹을 함께 쓰는 구현이 늘고 있습니다.
- 셔플과 혼합 비율: 도메인별(웹/코드/논문/다국어) 혼합 비율은 그 자체가 하이퍼파라미터입니다. 학습 후반에 고품질 데이터 비중을 올리는 커리큘럼(annealing)도 FineWeb 계열 실험에서 효과가 보고된 기법입니다.
SFT 데이터는 다르게 — 소수 정예의 세계
파인튜닝(SFT) 데이터는 사전학습과 문법이 다릅니다. 수천~수만 건의 세계이므로 건별 품질이 전부입니다.
- 응답의 정확성·형식 일관성을 사람이(또는 강한 모델이 1차로) 검수하고,
- 지시문 다양성을 확보하고(같은 패턴 1만 개보다 다른 패턴 1천 개),
- 채팅 템플릿(역할 마커)을 학습·추론에서 정확히 일치시키고 — 템플릿 불일치는 조용한 성능 저하의 단골 원인입니다,
- 사전학습과 마찬가지로 중복·오염 제거를 합니다(특히 벤치마크 문항이 SFT 셋에 섞이는 사고가 잦습니다).
도구 상자 — 직접 다 만들 필요 없다
도구 만든 곳 한 줄 소개
────────────────── ──────────── ─────────────────────────────────
datatrove HuggingFace FineWeb을 만든 파이프라인 라이브러리
Dolma toolkit AI2 필터·dedup·PII 태거 모음 (Dolma 데이터셋의 공정)
NeMo Curator NVIDIA GPU 가속 대규모 큐레이션 (분산 MinHash 등)
trafilatura 오픈소스 HTML 본문 추출의 사실상 표준
fastText Meta 언어 식별·경량 품질 분류기
수백 GB 수준까지는 datatrove나 Dolma 툴킷으로 충분하고, TB급 GPU 가속이 필요해지면 NeMo Curator가 후보가 됩니다. 파이프라인을 분산 학습 클러스터 위에서 돌리는 것도 흔한 조합입니다.
흐름을 바꾼 논문들 — 읽기 순서 추천
- The Pile (2020) — "다양한 고품질 소스의 혼합"이라는 공개 데이터셋의 원형.
- Gopher/MassiveText (2021) — 휴리스틱 품질 규칙의 정립.
- RefinedWeb (2023) — "웹 데이터만으로도 큐레이션 잘하면 충분하다"는 반전 + 추출·라인 dedup 강조.
- Dolma (2024) — 3조 토큰 공정의 완전 공개 — 툴킷까지.
- FineWeb / FineWeb-Edu (2024) — 15조 토큰 + 단계별 절제(ablation) 실험 공개, 교육 가치 분류기의 위력.
- DCLM (2024) — 데이터 큐레이션을 벤치마크화 — 좋은 분류기 하나의 힘.
이 여섯 편을 순서대로 읽으면 "왜 지금의 표준 파이프라인이 이 모양인가"가 역사로 이해됩니다.
마치며
데이터 전처리는 화려하지 않지만, 이 공정의 각 단계가 모델의 상한선을 하나씩 정합니다 — 추출이 원료의 순도를, 필터가 분포를, dedup이 암기를, 오염 제거가 평가의 정직함을, 패킹이 계산 효율을. 그리고 전 단계를 관통하는 습관은 하나입니다: 버려지는 것과 남는 것의 샘플을 계속 눈으로 볼 것. 파이프라인은 코드지만, 품질 감각은 결국 사람의 것입니다.
참고 자료
- Gao et al. (2020), "The Pile: An 800GB Dataset of Diverse Text"
- Rae et al. (2021), "Scaling Language Models: Gopher" (MassiveText 규칙)
- Penedo et al. (2023), "The RefinedWeb Dataset for Falcon LLM"
- Soldaini et al. (2024), "Dolma: an Open Corpus of Three Trillion Tokens"
- Penedo et al. (2024), "The FineWeb Datasets"
- Li et al. (2024), "DataComp-LM (DCLM)"
- datatrove (GitHub) · Dolma toolkit · NeMo Curator
The Complete Guide to LLM Training Data Preprocessing — From Web Crawls to Token Packing, with the Latest Papers
- Introduction — Where 80% of Model Quality Is Decided
- A Bird's-Eye View of the Full Pipeline
- ① Text Extraction — Only the Real Content from HTML
- ② Language Identification — A Fast, Quiet Gate
- ③ Quality Filtering — From Heuristics to Classifiers
- ④ Deduplication — The Most Underrated Stage for Its Impact
- ⑤·⑥ PII, Toxicity, and Decontamination
- ⑦ Tokenization and Sequence Packing — The Final Step
- SFT Data Is Different — A Small, Elite World
- The Toolbox — No Need to Build Everything Yourself
- The Papers That Changed the Field — A Recommended Reading Order
- Closing Thoughts
- References
Introduction — Where 80% of Model Quality Is Decided
In the AI model development lifecycle post, I wrote that "1GB of good data beats 1TB of garbage." This post is the hands-on companion to that sentence — we walk through the process raw internet text actually goes through to become trainable tokens, along with the tools for each stage and the papers that established it. One of the most interesting findings of recent years is that the gap between frontier labs opens up in this very pipeline, more than in model architecture (the FineWeb and DCLM papers proved it with open data).
A Bird's-Eye View of the Full Pipeline
Collection (CommonCrawl, etc.)
→ ① Text extraction (HTML → text)
→ ② Language identification
→ ③ Quality filtering (heuristics → model classifier)
→ ④ Deduplication (exact → near, MinHash)
→ ⑤ PII & toxicity handling
→ ⑥ Benchmark decontamination
→ ⑦ Tokenization + sequence packing
→ Training
The order is deliberate — cheap filters go first and expensive ones last, so the costly operations (classifiers, MinHash) see fewer documents. Let's look at each stage.
① Text Extraction — Only the Real Content from HTML
Most pretraining data originates from CommonCrawl (a periodic crawl archive of the entire web). The first fork in the road appears here: do you use the pre-extracted WET text, or extract directly from the raw WARC (HTML)? The shared conclusion of RefinedWeb and FineWeb is that extracting directly from WARC with a tool like trafilatura gives distinctly better quality — WET files are packed with boilerplate such as navigation menus, cookie banners, and footers. The quality of text extraction sets the ceiling for every stage that follows.
② Language Identification — A Fast, Quiet Gate
A fastText-family language classifier determines each document's language, and only the target language is kept (e.g., ko for a Korean dataset). It looks simple, but there are traps — misclassification is frequent on short documents and documents that mix code with text, and the lower-resource the language, the more good data gets thrown away at this gate. If you are building a multilingual model, tuning thresholds per language is the standard move.
③ Quality Filtering — From Heuristics to Classifiers
Two generations of techniques are used together.
Heuristic rules (the Gopher rules family) — dozens of statistical rules, such as document length, mean word length, symbol-to-word ratio, bullet and hashtag ratios, and whether the text contains "lorem ipsum", weed out the obvious garbage. The Gopher paper established them, and almost every pipeline uses some variant.
Model-based classifiers — the recent battleground. FineWeb-Edu trained a small classifier on labels produced by having an LLM grade each document's "educational value" and used it to select a high-quality subset, and DCLM showed that a single fastText classifier trained on good data (instruct-style) can beat sophisticated pipeline combinations. The lesson: shift the definition of "quality" from the data itself to the criterion you train the classifier on, and the pipeline gets simpler while performance goes up.
One caution here — filters always bias the distribution. An educational-value filter shaves off colloquial language, minority dialects, and creative writing. The habit of eyeballing samples of what you are throwing away is half of filter tuning.
④ Deduplication — The Most Underrated Stage for Its Impact
A substantial share of any web crawl is duplicates (mirror sites, boilerplate, reposts). Duplicates effectively run certain texts for multiple epochs during training, which inflates memorization and benchmark contamination and wastes compute.
- Exact deduplication: remove perfect matches by hashing documents (or paragraphs). Cheap and reliable.
- Near deduplication — MinHash LSH: the standard technique for catching "almost identical" documents. Turn each document into a set of n-grams (shingles), approximate Jaccard similarity with MinHash signatures, then use LSH banding to narrow the comparison pairs down to candidates — which is why it works on billions of documents without comparing everything against everything.
- Line-level deduplication: remove lines that repeat across many documents (navigation text and so on). A technique RefinedWeb emphasized.
There is an interesting twist as well — FineWeb reported that per-snapshot deduplication produced better results than aggressively deduplicating across all crawl snapshots. Even deduplication is not "the more the better" — it is something to measure and tune.
⑤·⑥ PII, Toxicity, and Decontamination
PII handling: patterns such as emails, phone numbers, and IP addresses are detected with regular expressions, then removed or replaced with placeholders (the Dolma toolkit is a good open implementation of this stage). Legal review not being a luxury is exactly what I said in the model development post.
Benchmark decontamination: if items from evaluation sets (MMLU, GSM8K, and so on) are mixed into the training data, benchmark scores go up without any real capability. Removing training documents that overlap with evaluation-set n-grams is the standard procedure, and the "skepticism when reading a new model's scores" from the quantization post is aimed precisely at the absence of this stage. If you built your own evaluation set, it belongs on the decontamination list too — the data-side version of the eval-first principle.
⑦ Tokenization and Sequence Packing — The Final Step
Cleaned documents become token IDs via a tokenizer (BPE family) and are cut into fixed-length sequences for the trainer. Two practical points here:
- Sequence packing: when documents are shorter than the sequence length, padding is wasted. Packing — concatenating multiple documents with EOS tokens to fill each sequence — is the standard, and a growing number of implementations pair it with masking that blocks attention across document boundaries.
- Shuffling and mixture ratios: the per-domain mixture (web/code/papers/multilingual) is itself a hyperparameter. Curriculum schemes (annealing) that raise the share of high-quality data late in training are another technique whose benefits were reported in FineWeb-line experiments.
SFT Data Is Different — A Small, Elite World
Fine-tuning (SFT) data follows a different grammar than pretraining. It is a world of thousands to tens of thousands of examples, so per-example quality is everything.
- Have humans (or a strong model as a first pass) review responses for accuracy and format consistency,
- Ensure instruction diversity (one thousand different patterns beat ten thousand of the same one),
- Match the chat template (role markers) exactly between training and inference — template mismatch is a classic cause of silent performance degradation,
- Deduplicate and decontaminate just as in pretraining (benchmark items slipping into SFT sets is an especially frequent accident).
The Toolbox — No Need to Build Everything Yourself
Tool Made by One-line description
────────────────── ──────────── ─────────────────────────────────
datatrove HuggingFace The pipeline library that built FineWeb
Dolma toolkit AI2 Filters, dedup, PII taggers (the Dolma dataset process)
NeMo Curator NVIDIA GPU-accelerated curation at scale (distributed MinHash, etc.)
trafilatura Open source The de facto standard for HTML text extraction
fastText Meta Language ID and lightweight quality classifiers
Up to the hundreds-of-gigabytes range, datatrove or the Dolma toolkit is plenty; once you need TB-scale GPU acceleration, NeMo Curator becomes the candidate. Running the pipeline on top of a distributed training cluster is also a common combination.
The Papers That Changed the Field — A Recommended Reading Order
- The Pile (2020) — the archetype of open datasets as "a mixture of diverse, high-quality sources."
- Gopher/MassiveText (2021) — established the heuristic quality rules.
- RefinedWeb (2023) — the twist that "curated web data alone is enough," plus the emphasis on extraction and line-level dedup.
- Dolma (2024) — a three-trillion-token process fully in the open — toolkit included.
- FineWeb / FineWeb-Edu (2024) — 15 trillion tokens plus published stage-by-stage ablation experiments, and the power of the educational-value classifier.
- DCLM (2024) — turned data curation into a benchmark — the power of one good classifier.
Read these six in order, and you will understand as history why today's standard pipeline looks the way it does.
Closing Thoughts
Data preprocessing is not glamorous, but each stage of this process sets one of the model's ceilings — extraction sets the purity of the raw material, filtering the distribution, dedup the memorization, decontamination the honesty of your evaluation, and packing the compute efficiency. And a single habit runs through every stage: keep looking, with your own eyes, at samples of what gets discarded and what remains. The pipeline is code, but the sense of quality ultimately belongs to people.
References
- Gao et al. (2020), "The Pile: An 800GB Dataset of Diverse Text"
- Rae et al. (2021), "Scaling Language Models: Gopher" (MassiveText rules)
- Penedo et al. (2023), "The RefinedWeb Dataset for Falcon LLM"
- Soldaini et al. (2024), "Dolma: an Open Corpus of Three Trillion Tokens"
- Penedo et al. (2024), "The FineWeb Datasets"
- Li et al. (2024), "DataComp-LM (DCLM)"
- datatrove (GitHub) · Dolma toolkit · NeMo Curator