# Cleaning and deduplicating web-scale text datasets



Learn how to build a scalable text cleaning pipeline using MinHash LSH and heuristic filters to prepare web-scale datasets for LLM training on Podstack.



Data · 2026-10-06 · 3 min read



Processing web-scale text—think Common Crawl or massive Discord scrapes—is the first high-stakes hurdle in training a Large Language Model (LLM). If you feed your model "garbage" (boilerplate, HTML tags, or thousands of copies of the same terms-of-service agreement), your loss curves will stagnate, and your inference results will suffer from repetitive hallucinations.

Cleaning and deduplicating at scale isn't just about regex; it’s a compute-intensive pipeline that requires massive parallelization. In this post, we’ll walk through a modern workflow for preparing high-quality pre-training data using MinHash LSH for deduplication and heuristic filtering for quality.

## The Architecture of a Cleaning Pipeline

A robust pipeline generally follows three phases:
1.  **Normalization and Heuristic Filtering:** Removing non-textual noise and low-quality documents.
2.  **Fuzzy Deduplication:** Identifying documents that are nearly identical (e.g., the same news article on different domains).
3.  **Final Formatting:** Tokenization or conversion to a high-throughput format like Parquet or WebDataset.

## Step 1: Heuristic Quality Filtering

Before running expensive deduplication algorithms, you should prune the "easy" noise. High-quality text usually has a specific distribution of characters and words. Common filters include:
*   **Symbol-to-word ratio:** If more than 10% of a document is composed of symbols (#, $, %), it’s likely code or junk metadata.
*   **Language Identification:** Use a fast model like `fastText` to drop documents that don't match your target language.
*   **Gopher-style rules:** Remove documents that are too short (under 200 characters) or too long, and those with an unusually high "stopword" density.

## Step 2: Global Deduplication with MinHash LSH

Exact deduplication (hashing a whole string) misses 90% of duplicates in web data because of small changes like timestamps or "Related Articles" sidebars. Instead, we use **MinHash Locality Sensitive Hashing (LSH)**.

The process involves:
1.  **Shingling:** Breaking text into overlapping n-grams.
2.  **MinHashing:** Converting shingles into a fixed-size signature (e.g., 128 integers).
3.  **LSH:** Grouping signatures into "bands" to find candidates that have a high Jaccard similarity.

## Implementing a GPU-Accelerated Worker

While MinHash is often done on CPUs, we can use GPUs to accelerate the signature generation and the final embedding-based semantic deduplication. Below is a conceptual worker script that processes a chunk of data, which you can deploy as a job.

```python
import os
import datasketch
from datasketch import MinHash, MinHashLSH
import pandas as pd

def process_batch(file_path):
    # Load a subset of your web-scale dataset
    df = pd.read_parquet(file_path)
    
    # 1. Heuristic Filter: Minimum length and alpha-numeric check
    df = df[df['text'].str.len() > 250]
    
    # 2. MinHash Generation
    signatures = []
    for text in df['text']:
        m = MinHash(num_perm=128)
        # Create shingles (3-grams)
        shingles = [text[i:i+3] for i in range(len(text)-2)]
        for s in shingles:
            m.update(s.encode('utf8'))
        signatures.append(m)
    
    # In a real pipeline, you would yield these signatures to a 
    # global LSH index or save them to a vector store.
    return signatures

if __name__ == "__main__":
    # Example: Processing a local shard
    results = process_batch("data_shard_001.parquet")
    print(f"Processed {len(results)} valid documents.")
```

## Practical Tips for Scale

*   **Memory Management:** When dealing with billions of documents, you cannot fit the LSH index in RAM. Use a distributed key-value store or a disk-backed storage for the LSH buckets.
*   **Semantic Deduplication:** For high-quality datasets (like fine-tuning sets), MinHash isn't enough. Use a GPU to generate embeddings (e.g., with BGE or RoBERTa) and run a cosine similarity check. This catches documents that say the same thing using different words.
*   **The "Boilerplate" Problem:** Use libraries like `trafilatura` or `resiliparse` to extract main content from HTML. Standard regex often leaves behind navigation menus that pollute your dataset.

## Running the Pipeline on Podstack

Processing terabytes of text is a classic "burst" workload. You don't want a cluster running 24/7; you want 50 GPUs for three hours, then zero. 

With **Podstack**, you can wrap your cleaning logic into a Python function and trigger it as an on-demand Job. Because Podstack bills by the second, you only pay for the exact duration of your data crunching.

First, ensure your environment is set up:
```bash
export PODSTACK_API_KEY="your_api_key_here"
```

You can then use the Podstack API to deploy your cleaning script as a job. This allows you to spin up high-memory GPU instances to handle the MinHash signatures and embedding generations without managing infrastructure:

```text
Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key.
```

By leveraging serverless GPU functions, you can scale your deduplication horizontally. One function can handle the heuristic filtering, while another—backed by a powerful GPU—handles the semantic similarity checks. This modular approach ensures that your pre-training data is pristine, leading to faster convergence and a more capable model.
