Runoob Tutorial ArchiveEnglish

AI System Architecture

AI System Architecture

You successfully ran a large model demo on your laptop, and the results were good, but when you want to turn it into a real product, problems arise:

These are the problems that AI System Architecture needs to solve.

Demos focus on whether it can run, while production systems focus on whether it can run stably, efficiently, and at a low cost.

Characteristics of production-grade AI systems: 7x24 availability, support for millions of concurrent requests, observability, scalability, disaster recovery reliability, and cost control.


Special challenges of AI systems

Compared to traditional web services, AI systems have three unique challenges.

Challenge one: Uncertain output

The output of traditional systems is deterministic—if you input 1+1, it will always return 2.

The output of AI systems is probabilistic—the same prompt might yield different results on two different generations.

This brings several questions: How to ensure output quality? How to evaluate performance? How to handle hallucinations?

Solutions usually include: output layer sampling strategies, result post-processing filtering, human feedback loops, and multi-model voting.

Challenge Two: The trade-off between latency and cost

AI inference requires significant computation, which means there is an inherent conflict between latency and cost.

Want speed? Use more GPUs, and costs skyrocket.

Want to save money? Process in queues, leading to poor user experience.

The core of a production system is finding a balance between SLA (Service Level Agreement) and cost.

Optimization directions Common technologies Effect
Model compression Quantization, pruning, distillation 2-4 times speed increase, slight accuracy decrease
Inference optimization vLLM, TensorRT, FlashAttention 3-10 times throughput increase
Architecture design Batch processing, multi-level caching Unit request cost reduced by 50%-80%

Challenge Three: Building the Data Flywheel

AI systems are not "done once launched"; they require continuous iteration.

The more users use it, the more feedback data is generated, which allows the model to be trained better, and the more users are willing to use it—this is the data flywheel.

But it's not easy to get the flywheel spinning: how to collect effective feedback? How to annotate data? How to train continuously? How to evaluate new versions?

These questions have no standard answers, but every successful AI product has its own flywheel design.


Large-scale training infrastructure

Training large models with hundreds of billions or even trillions of parameters requires supercomputing infrastructure.

GPU cluster architecture

Modern AI training clusters are typically composed of hundreds or thousands of GPUs.

Taking the H100 GPU as an example, one H100 has 80GB of memory and a computing power of 1979 TFLOPS at FP8 precision.

But a single GPU is far from enough—GPT-3 training used about 355 V100s and took 3 months.

A typical cluster topology is:

Hierarchy Device Connection method Bandwidth
Within a single machine GPU-GPU NVLink 900GB/s
Same rack Server-to-server InfiniBand 400Gb/s
Cross-rack Switch-to-switch InfiniBand Fabric 400Gb/s

The network is a bottleneck for distributed training. If the communication bandwidth is insufficient, GPU utilization may drop from 90% to 30%, spending most of the time waiting for data.

InfiniBand high-speed interconnect

Standard Ethernet is too slow; InfiniBand is used for distributed training.

InfiniBand features include: ultra-low latency (microsecond level), ultra-high bandwidth, and support for RDMA (Remote Direct Memory Access).

RDMA allows one GPU to directly read and write the GPU memory of another server without going through the operating system kernel, which is much faster.

Storage System Design

Training data is usually in the TB or even PB range, so the storage system is also very demanding.

Typical tiered storage design:

Fault tolerance and checkpointing

If a GPU fails during a training run that takes several weeks, restarting from scratch is too wasteful.

The solution isCheckpointingPeriodically save the model state to disk to recover from the latest checkpoint if an error occurs.

However, checkpoints also have costs: saving once might take several minutes and occupy tens of GB of space.

The usual strategy is to save every few hundred steps, keep the most recent few checkpoints, and automatically clean up the old ones.


Distributed training strategies

A large model cannot fit on a single GPU, so the training task needs to be split across multiple GPUs.

There are mainly three parallel strategies: data parallelism, tensor parallelism, and pipeline parallelism; combining these is 3D parallelism.

3D parallel strategy diagram

Data Parallelism

The simplest and most commonly used strategy: each GPU holds the complete model but processes different data.

For example, with 8 GPUs and a batch size of 1024, each GPU processes 128 data samples.

Forward propagation is calculated independently by each, and gradients are aggregated and averaged during backpropagation before updating the model.

The problem with data parallelism is that GPU memory remains the bottleneck—if the model is too large to fit on a single GPU, data parallelism is useless.

ZeRO Memory Optimization

ZeRO (Zero Redundancy Optimizer) is an enhanced version of data parallelism that can further save GPU memory.

In standard data parallelism, every GPU stores the complete model parameters, gradients, and optimizer states—this is very redundant.

The idea behind ZeRO is to split these states across different GPUs and communicate them when needed.

ZeRO Stages Content splitting Memory saving
ZeRO-1 Optimizer state Approximately 4 times
ZeRO-2 Optimizer state + gradients Approximately 8 times
ZeRO-3 Optimizer state + gradients + parameters Linear with the number of GPUs

Configuring ZeRO with DeepSpeed is simple:

{

 

"train_batch_size"

:

1024

,

 

"train_micro_batch_size_per_gpu"

:

16

,

 

"optimizer"

:

{

   

"type"

:

"Adam"

,

   

"params"

:

{

     

"lr"

:

0.0001

,

     

"betas"

:

[

0.9

,

0.95

]

,

     

"eps"

:

1e

8

,

     

"weight_decay"

:

0.01

   

}

 

}

,

 

"zero_optimization"

:

{

   

"stage"

:

3

,

   

"allgather_partitions"

:

true

,

   

"allgather_bucket_size"

:

2e8

,

   

"overlap_comm"

:

true

,

   

"reduce_scatter"

:

true

,

   

"reduce_bucket_size"

:

2e8

,

   

"contiguous_gradients"

:

true

,

   

"stage3_prefetch_bucket_size"

:

1e8

,

   

"stage3_param_persistence_threshold"

:

1e5

,

   

"stage3_max_live_parameters"

:

1e9

,

   

"stage3_max_reuse_distance"

:

1e9

 

}

,

 

"gradient_clipping"

:

1.0

,

 

"fp16"

:

{

   

"enabled"

:

true

,

   

"loss_scale"

:

0

,

   

"loss_scale_window"

:

1000

,

   

"initial_scale_power"

:

16

,

   

"hysteresis"

:

2

,

   

"min_loss_scale"

:

1

 

}

,

 

"checkpoint"

:

{

   

"tag"

:

"runoob-checkpoint"

,

   

"load_universal"

:

true

 

}

}

This configuration uses ZeRO-3, which can distribute the model state across all GPUs, linearly reducing VRAM usage with the number of GPUs.

Tensor Parallelism

If ZeRO is not enough, you need to use Tensor Parallelism—splitting the computation of a layer across multiple GPUs.

Matrix multiplication in a Transformer can be split by row or column:

This requires communication for each layer's computation, but it halves the memory usage.

Megatron-LM is a Tensor Parallelism library developed by NVIDIA, which is highly compatible with PyTorch.

Pipeline Parallelism

Tensor parallelism is "intra-layer splitting," and pipeline parallelism is "inter-layer splitting."

For example, a 32-layer model: GPU 0 handles the first 8 layers, GPU 1 handles the middle 8 layers, GPU 2 handles the next 8 layers, and GPU 3 handles the last 8 layers.

Data flows from GPU 0 to GPU 3, much like an assembly line in a factory.

But pipelines have a problem: bubbles—when GPU 0 starts computing, GPUs 1-3 are idle; once the data reaches GPU 1, GPU 0 is idle again.

The solution is to divide the data into "micro-batches" and feed them in like an assembly line to reduce bubble time.

3D Parallelism (DP+TP+PP)

These three strategies can be combined:

For example, with 64 GPUs, the planning can be as follows:

This is 3D parallelism—the standard configuration for modern large model training.


Data Engineering

The prerequisite for a good model is good data—data engineering accounts for over 60% of the workload in AI systems.

Data Collection and Cleaning Pipeline

Training data usually comes from multiple sources: web pages, books, code, conversations, etc.

Typical processing flow:

Data Deduplication: MinHash LSH

Directly calculating pairwise document similarity is too slow; a common method is MinHash + LSH (Locality-Sensitive Hashing).

The idea is: convert each document into a short "fingerprint"; similar documents are likely to have the same or similar fingerprints, and then group them by fingerprint.

Example

import

hashlib

import

re

from

typing

import

List

,

Set

,

Dict

,

Tuple

def

generate_shingles

(

text:

str

,

k:

int

=

5

)

Set

[

str

]

:

   

"""Generate k-shingles: a sequence of k consecutive words
For example, "I love runoob tutorial", k=2 -> {"I love", "love runoob", "runoob tutorial"}
"""

   

Simple tokenization (use professional tokenization tools in actual scenarios)

words

=

re

.

findall

(

r

'\w+'

,

text.

lower

(

)

)

shingles

=

set

(

)

   

for

i

in

range

(

len

(

words

)

1

)

:

shingle

=

' '

.

join

(

words

[

i:i+k

]

)

shingles.

add

(

shingle

)

   

return

shingles

def

minhash_signature

(

shingles: Set

[

str

]

,

num_hashes:

int

=

100

)

List

[

int

]

:

   

"""Generate MinHash signatures
Using multiple hash functions, taking the minimum for each
"""

signature

=

[

]

   

for

i

in

range

(

num_hashes

)

:

       

Use i as the seed to generate different hash functions

min_hash

=

None

       

for

shingle

in

shingles:

           

Combine shingle and i to generate a hash value

h

=

hashlib.

sha256

(

f

"{shingle}-{i}"

.

encode

(

)

)

.

hexdigest

(

)

h_int

=

int

(

h

,

16

)

           

if

min_hash

is

None

or

h_int

<

min_hash:

min_hash

=

h_int

signature.

append

(

min_hash

)

   

return

signature

def

lsh_banding

(

signature: List

[

int

]

,

bands:

int

=

20

)

List

[

str

]

:

   

"""Generate LSH keys using banding
Split the signature into multiple bands, and hash each band separately
"""

keys

=

[

]

rows_per_band

=

len

(

signature

)

// bands

   

for

i

in

range

(

bands

)

:

start

=

i * rows_per_band

end

=

start + rows_per_band

band

=

tuple

(

signature

[

start:end

]

)

       

Generate a key for this band hash

band_hash

=

hashlib.

sha256

(

str

(

band

)

.

encode

(

)

)

.

hexdigest

(

)

[

:

16

]

keys.

append

(

f

"band-{i}-{band_hash}"

)

   

return

keys

def

deduplicate_documents

(

documents: List

[

str

]

,

threshold:

float

=

0.7

)

List

[

str

]

:

   

"""Deduplicate documents using MinHash + LSH
Return the list of deduplicated documents
"""

   

Storage: LSH key -> list of document indices

buckets: Dict

[

str

,

List

[

int

]

]

=

{

}

   

Storage: Document Index -> Signature

signatures: Dict

[

int

,

List

[

int

]

]

=

{

}

   

Tag: which documents are duplicates

duplicates: Set

[

int

]

=

set

(

)

   

for

idx

,

doc

in

enumerate

(

documents

)

:

shingles

=

generate_shingles

(

doc

)

        sig

=

minhash_signature

(

shingles

)

signatures

[

idx

]

=

sig

keys

=

lsh_banding

(

sig

)

       

Check if there are similar documents

is_duplicate

=

False

       

for

key

in

keys:

           

if

key

in

buckets:

               

There are already documents in this bucket, compare signature similarity one by one

               

for

other_idx

in

buckets

[

key

]

:

other_sig

=

signatures

[

other_idx

]

                   

Calculate signature similarity (Jaccard approximation)

matches

=

sum

(

1

for

a

,

b

in

zip

(

sig

,

other_sig

)

if

a

==

b

)

similarity

=

matches /

len

(

sig

)

                   

if

similarity

=

threshold:

                       

Exceeds the threshold, considered as duplicate

is_duplicate

=

True

duplicates.

add

(

idx

)

                       

break

           

if

is_duplicate:

               

break

       

if

not

is_duplicate:

           

It is not a duplicate, add it to each bucket

           

for

key

in

keys:

               

if

key

not

in

buckets:

buckets

[

key

]

=

[

]

buckets

[

key

]

.

append

(

idx

)

   

Return non-duplicate documents

   

return

[

doc

for

idx

,

doc

in

enumerate

(

documents

)

if

idx

not

in

duplicates

]

============================================

Test runoob data deduplication

============================================

if

name

==

"main"

:

    documents

=

[

       

"Welcome to runoob tutorials, a good place to learn programming."

,

       

"Welcome to runoob tutorials, a great place to learn programming."

,

 

Highly similar

       

"Python is a concise and elegant language, suitable for beginners."

,

       

"Python is a concise and elegant programming language, very suitable for beginners."

,

 

Highly similar

       

"Machine learning allows computers to learn patterns from data."

,

       

"This is a completely different article."

,

   

]

   

print

(

f

"Before deduplication: {len(documents)} documents"

)

    deduplicated

=

deduplicate_documents

(

documents

,

threshold

=

0.6

)

   

print

(

f

"After deduplication: {len(deduplicated)} documents\n"

)

   

print

(

"Retained documents:"

)

   

for

i

,

doc

in

enumerate

(

deduplicated

)

:

       

print

(

f

"[{i}] {doc}"

)

Output:

Before deduplication: 6 documents

After deduplication: 4 documents

Retained documents:

[0] Welcome to runoob tutorials, a good place to learn programming.

[1] Python is a concise and elegant language, suitable for beginners.

[2] Machine learning allows computers to learn patterns from data.

[3] This is a completely different article.

In actual production, more efficient implementations (such as the datasketch library) are used, but the core idea is the same.

Data format: WebDataset

Small datasets can be stored arbitrarily, but TB-level datasets require a specialized format.

WebDataset is a commonly used one: it packages files into tar archives, with each tar containing thousands of samples, supporting random and sequential reading.

The advantages are:


Data flywheel design

The data flywheel is the moat of AI products—the more users, the more data, the better the model, the more users.

User feedback data collection

Feedback has two types: explicit and implicit:

Explicit feedback has high quality but low quantity; implicit feedback has high quantity but high noise.

A good feedback system combines both—use explicit feedback to train the reward model, and use implicit feedback for A/B testing.

Automatic Data Labeling

Manual labeling is too expensive and slow; the current trend is "using models to label models."

Common strategies:

Continuous training strategy

Models are not "trained once and done"; the world is changing, and models must change with it.

A typical continuous training workflow:

Be mindful of "catastrophic forgetting" during continuous training—training too much on new data may cause the model to forget previous capabilities. The solution is to maintain a "replay buffer" and mix new and old data during each training session.


Enterprise AI platform architecture

A complete enterprise AI platform usually includes the following components.

Model registration and version management

More models mean more management hassle—a centralized model registry is needed.

The registry must record:

MLflow, Weights & Biases, and Hugging Face Hub are common tools.

Feature Store

Many AI applications require feature engineering—such as user profiles, historical behavior, and contextual information.

Feature Store is a feature management system that solves several problems:

The typical architecture is: batch computation offline using Spark or Flink, and low-latency reading online using Redis or Cassandra.

Online/offline inference service

Inference has two scenarios with different architectures:

Scenario Latency requirement Architecture Example
Online Inference Millisecond level Real-time API + Batch Processing Chatbots, Search
Offline Inference Hourly/Daily level Batch Job Queue Content Moderation, Report Generation

Online inference services need to consider:

Full-link monitoring

It is difficult to troubleshoot AI system issues—observability is required.

Several dimensions of monitoring:

Classic combination: Prometheus + Grafana for metrics, ELK for logs, Jaeger for tracing.


Evaluation benchmark system

How to know if the model has improved or degraded? A set of evaluation systems is needed.

General capability benchmarks

Benchmarks commonly used in academia:

Benchmark Test content Typical tasks
MMLU Multi-task language understanding 57 multiple-choice subjects
HumanEval Code generation 164 programming problems
MBPP Code Generation 974 Python Questions
TruthfulQA Factuality 817 Questions to Test Hallucination
GSM8K Mathematical Reasoning 8000 elementary math problems

Chinese benchmark

English benchmark good does not equal Chinese good, a Chinese dedicated benchmark is needed:

Custom business evaluation set

Public benchmarks are a foundation, but your own business evaluation set is more important.

How to build:

The business evaluation set is your "gold standard"—it is more important than any public benchmark.


Multi-tenant AI service

If you are building a ToB product, multi-tenancy is an unavoidable topic.

Tenant isolation

There are several levels of isolation:

Isolation levels Resources Advantages Disadvantages
Physical isolation Dedicated GPU machine Fully isolated, secure High cost
K8s isolation Independent Pod/Namespace Balancing cost and security Requires scheduling
Logical isolation Shared resources, permission control Lowest cost Has leakage risk

The usual strategy is: physical isolation for large customers, logical isolation for small and medium customers.

Model sharing and fine-tuning management

A common requirement for multi-tenancy: train a proprietary model using my data.

Architecturally, it needs to support:

This can save a large amount of VRAM—no need to load the full model for every tenant.

Billing and quotas

AI service costs are high, so billing needs to be granular:


Disaster recovery and high availability

Enterprise-grade systems cannot go down—high availability design is required.

Multi-Availability Zone deployment

The most basic requirement: cross-Availability Zone (AZ) deployment.

For example:

The goal is: if one AZ fails, the service does not interrupt, and data is not lost.

Model snapshot and rollback

New version models might have issues—quick rollback is needed.

Strategy:

Degradation and rate limiting

What to do if traffic suddenly increases? Cannot just hang, need a plan:

Core principle: Graceful degradation, not complete unavailability.