How Large Language Models Work: A Full Pipeline from Data to Deployment
This article walks through the full pipeline behind large language models, starting from training data and ending at real-world usage. It explains data collection from raw HTML, language distribution imbalance, quality filtering and deduplication, and tokenization with Byte Pair Encoding. It also covers how pretraining, instruction tuning, and retrieval augmentation turn a text continuation model into a practical assistant, along with engineering practices and common pitfalls to avoid.
1. Why Understanding LLMs Starts with Data
When developers first work with large language models, their attention usually goes to parameter counts, inference APIs, and how to call them. A more fundamental fact often gets overlooked: every capability a model has comes from its training corpus. A model does not generate knowledge out of nowhere. It compresses the text traces humans have left behind into a parameter distribution, then continues writing the most probable fragments based on that distribution. To truly understand how an LLM is built and used, you have to follow the chain of where data comes from, how it gets cleaned, and how the model actually sees it.
That chain breaks down into four stages:
- Data collection: acquiring raw text from public web pages, code hosting platforms, encyclopedias, and documentation.
- Data cleaning and filtering: removing noise, low-quality content, and non-body elements, while balancing language distribution.
- Deduplication and privacy handling: eliminating duplicate and near-duplicate content to reduce memorization and leakage risk.
- Tokenization: converting text into token sequences and numeric IDs for model computation.
Steps three and four are the most underestimated, yet they directly determine training efficiency and the boundaries of a model’s language capabilities.
2. Data Collection: From Raw HTML to Usable Text
Early corpus construction often relied on ready-made datasets, but in engineering practice the more common approach is to write your own crawling pipeline and fetch the raw HTML source of a page directly (the structured text you see in browser developer tools), rather than simply copying the rendered visible text.
The reason is that rendered text has already lost a great deal of structural information, while the raw markup preserves clues such as heading hierarchy, paragraph boundaries, list relationships, and code block markers. These clues are essential for downstream main-content extraction.
A simplified extraction flow usually includes the following checks:
# Illustrative code: demonstrates the extraction idea only, not a specific product APIdef extract_main_text(html: str) -> str:# 1. Parse the structure and locate the content container (body area, article tags, etc.)# 2. Remove noise nodes: navigation, ads, footer, sidebar, recommendation slots# 3. Keep substantive content: headings, paragraphs, lists, code blocks# 4. Normalize whitespace and output plain textreturn normalize(clean_boilerplate(parse(html)))
Beyond web pages, code hosting sites are another important source. This data is valuable, but licensing must be handled: not all public code may be freely used for training. In practice, you typically need to identify a repository’s license declaration and exclude or down-weight non-compliant sources.
3. Language Distribution: Why Models Get Lopsided
The proportion of different languages in raw corpora is highly uneven. English content is enormous on the internet, Chinese content is rich but relatively concentrated, and other languages are far sparser. If you train directly on the raw proportions, the model naturally performs better on high-share languages and noticeably worse on low-share ones. This is the so-called capability imbalance.
There are three common mitigation approaches:
- Sampling weights: up-sample low-resource languages and moderately down-sample high-resource ones.
- Corpus supplementation: deliberately add high-quality bilingual aligned text, encyclopedias, and textbook-style content.
- Tokenizer optimization: ensure the vocabulary reasonably covers common characters and words in target languages, avoiding a single character being split into too many fragments.
It is worth stressing that sampling weights can only mitigate the problem, not create something from nothing. If high-quality corpus for a language is extremely scarce, the model’s reasoning and generation ability in that language will still be limited. Set expectations for this in advance during selection and acceptance testing.
4. Quality Filtering and Strict Deduplication
A striking reality of internet content is how repetitive it is: the same story is reposted across many sites, the same passage is quoted over and over, and templated pages are generated in bulk. If a model repeatedly learns the same fragments, training compute is wasted on redundant information, corpus diversity drops, and mechanical memorization of specific text gets worse.
Deduplication is usually performed at multiple granularities:
- Exact deduplication: compute a hash on normalized text and directly drop identical samples.
- Near deduplication: use locality-sensitive hashing or n-gram similarity to identify highly similar samples caused by rewrites, reposts, and template concatenation.
- Paragraph-level deduplication: remove repeated paragraphs within and across documents, keeping the first occurrence or the higher-quality copy.
Beyond duplication, quality filtering also considers features such as: too low a body-text ratio, too high a garbled-text ratio, an excess of symbols and emojis, leftover template placeholders, and obviously machine-concatenated content. Quality scoring generally combines rules with a lightweight classifier, doing coarse filtering first and fine filtering later to control overall compute cost.
5. Tokenization: Text as the Model Sees It
A model cannot process natural language characters directly; it only accepts integer sequences. So text must first be split into tokens, then mapped to numeric IDs. A token can be a whole word, part of a word, or even a single space or punctuation mark.
The mainstream approach in the industry today is Byte Pair Encoding (BPE) and its variants. The core idea is very intuitive: start from the smallest units and repeatedly merge the most frequent adjacent pair.
The training process can be summarized as:
- Initialize the base vocabulary: include all single characters, bytes, and common symbols, each assigned an ID.
- Count the frequency of adjacent units across the whole corpus and find the most frequent pair.
- Merge that pair into a new token, add it to the vocabulary, and assign a new ID.
- Repeat merging until the vocabulary reaches a preset target size (for example, tens of thousands).
The direct benefit of merging is that high-frequency expressions can be represented with a single token, making sequences shorter and inference faster. At the same time, because the base layer keeps single bytes, any rare word, misspelling, or newly coined term can be broken down and represented, so nothing fails to encode.
Initial: you / hel / lo / worldMerge 1: you / hello / worldMerge 2: you / hello worldResult: the original sentence takes just 2 tokens
Understanding tokenization has a direct impact on practice:
- Context length is measured in tokens, not characters, and the “cost per character” differs across Chinese, English, and code.
- Billing and rate limits are usually counted in tokens, so compressing a prompt really means reducing token count.
- Vocabulary design feeds back into language capability; languages with insufficient coverage get split too finely, and quality drops accordingly.
To get an intuitive feel for how splitting works, you can use a public online tokenizer visualization demo page: enter a piece of mixed Chinese-English text and observe the difference in token counts for the same meaning across languages.
6. From Training to Usage: How Capabilities Get Invoked
After corpus governance and tokenization, the model enters the pretraining stage, learning to predict the probability distribution of the next token. It is then aligned through instruction fine-tuning and human feedback, transforming from “continuing text” into “following instructions to complete tasks.” On the usage side, retrieval augmentation is often added: external knowledge is chunked, vectorized, and stored in a vector retrieval service, and relevant fragments are recalled and stitched into the prompt before answering, which helps mitigate stale knowledge and hallucination.
For engineering deployment, a stable pipeline often includes: an access layer for authentication and rate limiting, a cache layer to reuse high-frequency results, logging services and monitoring alerts to track latency and failure rates, object storage to hold corpora and evaluation samples, and a container platform to run batch cleaning and evaluation jobs. These all fall under general cloud capability categories and can be freely combined to fit your own architecture.
7. Practical Advice and Common Pitfalls
- Don’t look only at model size: corpus quality and deduplication strength often affect final results more than parameter differences.
- Don’t assume a token equals a character: capacity planning and cost accounting should be measured in tokens.
- Don’t ignore licensing and privacy: both training and retrieval corpora should undergo source compliance review and sensitive-information redaction.
- Don’t skip evaluation: build an evaluation set covering target languages and business scenarios, so you can quantify the benefit of each data change.
In summary, the “birth” of a large language model is essentially a data engineering pipeline: collection determines breadth of sources, cleaning determines signal-to-noise ratio, deduplication determines diversity, and tokenization determines how the model sees language. Only after making these four steps solid does it make sense to talk about model selection and prompt engineering, and only then can you achieve stable, controllable application results.
