Runoob Tutorial ArchiveEnglish

How AI Works

How AI Works

You might ask: I just want to use AI, why should I understand how it works?

The logic is simple: if you know where AI's capabilities come from, you can use it better.


Intuitive understanding of neural networks

The core of modern AI is neural networks, a name derived from the structure of neurons in the human brain.

Analogy of brain neurons

The human brain has about 86 billion neurons that are interconnected and transmit signals; each neuron receives input from other neurons, processes it, and then outputs it to other neurons; the learning process is the process of adjusting these connection strengths.

Artificial neural networks draw inspiration from this idea but make significant simplifications.

Three-layer basic structure

A typical neural network is divided into three layers: input layer, hidden layer, and output layer.

Basic structure diagram of a neural network

We will use identifying whether an image is a cat or a dog as an example:

6874747 733a f f6d697 6f 5674a6b5 587563386f67 e676966

Hierarchy Function In this example
Input layer Receives raw data Each pixel and color information of the image
Hidden layer Extracts features layer by layer Edges -> textures -> organs like ears and eyes
Output layer Provide the final result "Probability of being a cat 85%", "Probability of being a dog 15%"

Each layer has many neurons, each neuron receives the output of the previous layer, performs a simple calculation, and passes it to the next layer.

The amazing thing is: these features are not designed by humans, but are learned by the model from the data.

A simple neuron

Let's show what a neuron does with a few lines of Python code:

Instance

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

The basic calculation logic of an artificial neuron

No complex math, just weighted sum + activation

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

def

simple_neuron

(

inputs:

list

,

weights:

list

,

bias:

float

)

float

:

   

"""
A very simple neuron
inputs: Input values (from the previous layer's neurons)
weights: Weights (the importance of each input, learned during training)
bias: Bias (the threshold, learned during training)
"""

   

Step 1: Weighted sum

   

Multiply each input by its corresponding weight, and then sum them up

weighted_sum

=

0.0

   

for

input_value

,

weight

in

zip

(

inputs

,

weights

)

:

weighted_sum +

=

input_value * weight

   

Add bias

weighted_sum +

=

bias

   

Step 2: Activation function (to make the output non-linear)

   

Here we use the simplest ReLU: negative numbers become 0, positive numbers remain unchanged

output

=

max

(

0.0

,

weighted_sum

)

   

return

output

Simulation: a neuron that determines "is this a cat's ear"

Input: [pointiness, height position, has fur]

inputs

=

[

0.8

,

0.9

,

0.7

]

 

These three features are quite obvious

Weights: learned after training (in the runoob example, we assume these values have been learned)

weights

=

[

0.5

,

0.4

,

0.3

]

Bias: Threshold

bias

=

0.6

result

=

simple_neuron

(

inputs

,

weights

,

bias

)

print

(

f

"Neuron output: {result:.3f}"

)

print

(

f

"Judgment: {'Possibly cat ears' if result > 0 else 'Not very likely'}"

)

Output: Neuron output: 0.660

Output: Judgment: Possibly cat ears

What this neuron does is simple: it sums the weighted inputs, passes them through an activation function, and outputs a result.

But when thousands of such neurons are connected, with each layer learning different features, the whole system generates astonishing intelligence.

Remember this intuition: Neural network = many simple computational units connected together, learning by adjusting connection weights.


Training vs Inference: Two Different Stages

The lifecycle of AI is divided into two completely different stages: training and inference.

Understanding the difference between these two stages can help you understand many things—for example, why training is so expensive while inference is relatively cheap.

Training: Letting AI Learn

Training is a process like this: showing the model a large amount of data, allowing it to continuously adjust its parameters until its predictions become increasingly accurate.

For example, training a model to recognize cats and dogs:

The training phase requires massive computing power and data. A large model might require thousands of GPUs to train for several months, costing millions of dollars.

Inference: Let the AI use

Inference is a process like this: using a trained model, providing new input, and obtaining an output.

You send a message to ChatGPT, and it replies to you—this is inference.

You take a photo with your phone to identify a plant—this is also inference.

Characteristics of inference are:

Comparison of the two

Dimension Training Inference
Goal Learn knowledge and adjust weights Apply learned knowledge and provide answers
Data volume Requires massive amounts of data Single input is sufficient
Computing power requirements Extremely high (thousands of GPUs) Low (single GPU or mobile phone)
Cost Extremely high (millions of dollars) Low (a few cents per time)
Frequency A few times or dozens of times Millions of times per second
Who will do it Companies like OpenAI, Anthropic Ordinary users or applications

To put it another way: training is like "studying hard for ten years," and inference is like "taking an exam."

Reading requires a lot of time and energy, but once you learn, doing the exercises is fast.

When you use ChatGPT, you are doing "inference"—the model does not "learn" or "get smarter" because of your conversation. Its knowledge is cut off at the time of training completion.


Introduction to the Transformer architecture

In 2017, Google published a paper titled "Attention Is All You Need," which proposed the Transformer architecture.

This paper changed the entire field of AI. Today's large language models are almost all based on the Transformer.

Why is the Transformer so important?

Before the Transformer, RNN or LSTM were used to process sequential data (such as sentences).

Their problem was that they could only process word by word, making it difficult to capture long-range dependencies.

For example, in the sentence: "I left my wallet in a cafe in Beijing, and when I went back to look for it the next day, ____ was still there." — if you fill in "it" in the blank, you know "it" refers to the "wallet" because you remembered the preceding content.

When an old model processed "was still there," it might have already forgotten the existence of the "wallet."

The breakthrough of the Transformer is that it can see the entire sentence at once and, through the attention mechanism, know which words to focus on.

Encoder and Decoder

A complete Transformer is divided into two parts:

Components Function Typical application scenarios
Encoder Understand the input and convert text into vector representations Text classification, sentiment analysis, semantic search
Decoder Generates output text based on understanding Writing, translation, dialogue generation

Some models only use Encoder (e.g., BERT), some only use Decoder (e.g., GPT), and some use both (e.g., T5).

GPT series, Claude, and Llama are all "decoder-only" architectures—their strength is generating fluent text.


What is the attention mechanism?

Attention is the core of Transformer and the key to its ability to process long texts.

Analogy: Attention when a person reads

When you read a sentence, you don't spend the same amount of effort on every word.

For example, in "It has a long tail and triangular ears"—when you see "it," you focus on "tail" and "ears" to determine what animal it is.

The attention mechanism does this: it dynamically decides which words in the input to focus on based on the current processing position.

Attention mechanism diagram

Animation demonstration:

The large model is thinking

…

Each step does only one thing: guess the next word based on the preceding text.

▌

Candidate words for the next character

Top-5 probability

step0

Selected:—

How attention is calculated

Simply put, each word generates three vectors:

Calculate the similarity between the Query at each position and the Key at all positions to get the attention weights, and then use these weights to perform a weighted sum over the Values to get the output at this position.

You don't need to remember the details, just remember this intuition: Attention = assigning a weight to each word in the sentence to indicate its importance to the current position.

Why is attention so important

Attention brings several key advantages:

For example, when translating "It has a long tail" into Chinese, you can see that when the model produces the pronoun for "It", the attention is mainly focused on "tail".


Pre-training and fine-tuning

Large models today usually adopt a two-stage training: pre-training + fine-tuning.

Pre-training: Learning general knowledge from massive data

Pre-training is like this: finding a large amount of text from the internet (Wikipedia, books, web pages, code, etc.) and having the model do one thing—predict the next word.

This process has no specific task; it just lets the model broadly learn language, knowledge, logic, code, etc.

Pre-training is the most expensive part: lots of data, large computing power, and long time.

Fine-tuning: Optimizing for specific tasks

Although the model is knowledgeable after pre-training, it might not be obedient.

You ask it a question, and it might keep talking instead of answering directly.

You ask it to write code, and it might write half of it and then start writing something else.

Fine-tuning is further training the model using high-quality conversational data to teach it:

Understand with an analogy

Pre-training gives the model knowledge, and fine-tuning makes the model usable.

This is why some large models are smart but difficult to use, while others are average but easy to use—the difference is often in the fine-tuning.


Why do AIs hallucinate?

Hallucination is one of the most famous problems in AI: it fabricates non-existent facts, names, papers, or data in a serious manner.

Understanding from the perspective of probabilistic prediction

To understand hallucination, first return to the most fundamental way AI works:

It is not verifying facts, but predicting the next most likely word.

You ask: Who invented the telephone? — It knows that the sequence Alexander Graham Bell is most likely to appear.

But you ask: Who invented the runoob tutorial? — The training data may not have this information, but it will fabricate a plausible-sounding name based on statistical patterns.

It does not know what it does not know — it only knows that these words have the highest probability of appearing at this position.

Common causes of hallucinations

Cause Explanation Example
Insufficient training data This topic is rare in the training data, and the model has not learned it well Asking a very niche professional question
Knowledge cutoff Events that happened after the training data cutoff, which the model does not know Asking "What happened in 2025" (assuming the model was trained in 2024)
Source confusion Mixing information from multiple sources and making mistakes "Zhang San wrote paper A" (actually Li Si wrote it, but Zhang San and Li Si often appear together)
Overfitting Memorizing noise during training and treating it as fact Fabricating non-existent citations

How to reduce the impact of hallucinations

As a user, you can do the following:

Remember: even if what AI says sounds real, it might be fabricated. Always be skeptical for high-risk decisions.