Debug School

rakesh kumar
rakesh kumar

Posted on • Edited on

“AI and LLM Foundations for Developers: From Machine Learning to Transformers, Tokens, Embeddings, and RAG

What are we trying to understand?
Machine Learning
Deep Learning
Neural Networks
Generative AI
Large Language Model (LLM)
Transformer
Attention
Tokens and Tokenization
Context Window
Inference
Temperature
Top-p and Sampling
Deterministic vs Probabilistic Software
Embeddings
Hallucination
Pretraining
Prompting
Fine-tuning
RAG
Prompting vs RAG vs Fine-tuning
The complete LLM request lifecycle
Main Difference Between All the Concepts

What are we trying to understand?

As a traditional developer, you're accustomed to this:

Input
  ↓
Your Code
  ↓
Business Rules
  ↓
Database/API
  ↓
Predictable Output
Enter fullscreen mode Exit fullscreen mode

For example:

if age >= 18:
    return "Adult"
else:
    return "Minor"
Enter fullscreen mode Exit fullscreen mode

Same input → same logic → same output.

An LLM application behaves differently:

User Input
    ↓
Prompt / Instructions
    ↓
Tokenization
    ↓
LLM
    ↓
Probabilistic Generation
    ↓
Validation
    ↓
Application
Enter fullscreen mode Exit fullscreen mode

Understanding why that middle part behaves differently is the purpose of Week 1.

Machine Learning

Definition

Machine Learning (ML) is a way of creating software where the system learns patterns from data instead of you manually programming every decision rule.

Traditional programming:

Rules + Data
     ↓
 Program
     ↓
 Output
Enter fullscreen mode Exit fullscreen mode

Machine learning:

Historical Data + Expected Outputs
              ↓
           Training
              ↓
            Model
              ↓
        New Data → Prediction
Enter fullscreen mode Exit fullscreen mode

Example

Suppose MotoShare wants to predict whether a booking is potentially fraudulent.

Traditional approach:

if booking_amount > 100000:
    suspicious = True
Enter fullscreen mode Exit fullscreen mode

But fraud can depend on:

booking amount
user history
vehicle
location
booking frequency
payment behavior
account age
device
Enter fullscreen mode Exit fullscreen mode

ML learns patterns among these features.

Purpose

Learn ML because LLMs themselves are machine-learning models.

You don't need to become a classical ML expert first, but you should understand:

data
training
model
prediction/inference
features
evaluation
Enter fullscreen mode Exit fullscreen mode

Deep Learning

Definition

Deep learning is a branch of machine learning that uses multi-layer neural networks to learn complicated patterns from large amounts of data.

Artificial Intelligence
        │
        └── Machine Learning
                │
                └── Deep Learning
                        │
                        └── Generative AI
                                │
                                └── LLMs
Enter fullscreen mode Exit fullscreen mode

Why do we need it?

Traditional ML can work very well for structured problems such as:

Price prediction
Fraud detection
Spam detection
Customer churn
Enter fullscreen mode Exit fullscreen mode

Deep learning is particularly powerful for unstructured/high-dimensional information:

Text
Images
Audio
Video
Language
Enter fullscreen mode Exit fullscreen mode

Backend analogy

Think of ML as an application and a neural network as one possible implementation engine.

You don't need to understand every transistor inside your CPU to write Laravel/Python applications.

Likewise, you don't initially need the mathematics behind every neural-network operation to build LLM systems.

Neural Networks

Definition

A neural network is a collection of connected mathematical units that transforms inputs through learned parameters called weights.

Very simplified:


INPUT
  ↓
Layer
  ↓
Layer
  ↓
Layer
  ↓
OUTPUT
Enter fullscreen mode Exit fullscreen mode

During training:

Input
 ↓
Prediction
 ↓
Compare with expected result
 ↓
Calculate error
 ↓
Adjust weights
 ↓
Repeat millions/billions of times
Enter fullscreen mode Exit fullscreen mode

Backend analogy

Imagine an enormous configurable function:

output = model(input, billions_of_learned_parameters)

Except developers didn't manually write all those parameters.

They were learned during training.

Why learn this?

Because terms such as:

7B model
70B model
parameters
weights
training
fine-tuning
Enter fullscreen mode Exit fullscreen mode

will otherwise be confusing later.

Generative AI

Definition

Generative AI produces new content based on patterns learned during training.

It can generate:

Text
Code
Images
Audio
Video
Structured data
Enter fullscreen mode Exit fullscreen mode

Traditional ML vs Generative AI

Traditional ML might answer:

Input:
"This vehicle is excellent."

Output:
Positive
Enter fullscreen mode Exit fullscreen mode

Generative AI could answer:

"Write a professional description
for this vehicle."

→

"Experience comfortable city travel
with this well-maintained..."
Enter fullscreen mode Exit fullscreen mode

The second system generates content.

Purpose

Agentic AI is primarily built around generative models that can reason over instructions, produce responses and increasingly invoke tools.

Large Language Model (LLM)

Definition

An LLM is a large neural network trained on huge amounts of text to predict and generate sequences of tokens.

One crucial mental model:

An LLM is fundamentally predicting what token should come next.
Enter fullscreen mode Exit fullscreen mode

Suppose the input is:

The capital of India is
Enter fullscreen mode Exit fullscreen mode

Possible next tokens could have probabilities resembling:

Delhi       0.91
Mumbai      0.03
India       0.02
Kolkata     0.01
Enter fullscreen mode Exit fullscreen mode

The generation process continues:

Input
 ↓
Predict next token
 ↓
Append token
 ↓
Predict next token
 ↓
Append token
 ↓
Enter fullscreen mode Exit fullscreen mode

Why learn this?

This explains many things you'll encounter:

temperature
hallucination
tokens
context windows
prompt engineering
sampling
Enter fullscreen mode Exit fullscreen mode

Transformer

This is one of the most important Week 1 concepts.

Definition

A Transformer is a neural-network architecture designed to process sequences while determining relationships between different parts of the input.

Modern LLMs are largely built using transformer architectures.

Why was it important?

Consider:

Ashwani deposited ₹10,000 into the bank.
He withdrew ₹2,000 the next day.
How much money remains?
Enter fullscreen mode Exit fullscreen mode

The model needs relationships among:

Ashwani
He
₹10,000
₹2,000
bank
withdraw
Enter fullscreen mode Exit fullscreen mode

Transformers help model those relationships.

Simplified architecture

For Week 1, remember:

Transformer = architecture; 
LLM = a language model commonly built using transformer architecture.
Enter fullscreen mode Exit fullscreen mode

Attention

Definition

Attention allows the model to determine which parts of the available context are relevant when processing another part.

Consider:

Raj put his laptop inside his bag
because he was traveling.

What was inside the bag?
Enter fullscreen mode Exit fullscreen mode

For answering the question, important relationships include:

bag ← laptop
Enter fullscreen mode Exit fullscreen mode

Less important information may include:

traveling
Enter fullscreen mode Exit fullscreen mode

Conceptually:

          "bag"

               │
       Attention relationships
        ↙      ↓       ↘
     Raj    laptop   traveling
             ↑
         highly relevant
Enter fullscreen mode Exit fullscreen mode

Backend analogy

Think of attention loosely as dynamic relevance selection.

A backend developer might explicitly select:

SELECT relevant_columns
FROM data
WHERE condition = ...
Enter fullscreen mode Exit fullscreen mode

Attention learns which parts of context matter instead of using your manually written SQL condition.

Why learn it?

Later it helps you understand:

context
RAG
long documents
prompt placement
agent memory
Enter fullscreen mode Exit fullscreen mode

Tokens and Tokenization

This is extremely important for production AI.

Definition

LLMs don't directly process text as human-readable words.

Text is converted into tokens.

"AI is powerful"

       ↓ Tokenizer

[token1, token2, token3, ...]
Enter fullscreen mode Exit fullscreen mode

A token might represent:

a word
part of a word
punctuation
whitespace-related units
Enter fullscreen mode Exit fullscreen mode

So:

Characters ≠ Words ≠ Tokens
Enter fullscreen mode Exit fullscreen mode

Why do tokens matter?

Because they affect:

API cost
context limits
latency
maximum output
Enter fullscreen mode Exit fullscreen mode

Conceptually:

Cost ≈
(input tokens × input price)
+
(output tokens × output price)
Enter fullscreen mode Exit fullscreen mode

Backend analogy

Tokens are somewhat like payload size.

You already care about:

HTTP request size
memory
DB query size
response size
Enter fullscreen mode Exit fullscreen mode

With LLMs you additionally care about:

token budget
Enter fullscreen mode Exit fullscreen mode

Context Window

Definition

The context window is the amount of tokenized information a model can consider within a request/conversation context.

It can contain more than just the latest user message.

Context Window
│
├── System instructions
├── Developer instructions
├── Conversation history
├── User message
├── Retrieved RAG documents
├── Tool results
└── Generated tokens
Enter fullscreen mode Exit fullscreen mode

Important misconception

Context is not permanent memory.

If you have:

Message 1
Message 2
Message 3
...
Message 5000

Enter fullscreen mode Exit fullscreen mode

you cannot assume the model permanently remembers everything.

Applications often manage this using:

truncation
summarization
RAG
external memory
sliding windows
databases
Enter fullscreen mode Exit fullscreen mode

Why learn it?

Agents often maintain long-running conversations and tool results.

Bad context management produces:


high cost
high latency
lost information
context overflow
poor responses
Enter fullscreen mode Exit fullscreen mode

Inference

Definition

Training teaches the model.

Inference uses the trained model.

TRAINING

Huge dataset
    ↓
Training process
    ↓
Learn weights
    ↓
Trained model
Enter fullscreen mode Exit fullscreen mode

INFERENCE

Your prompt
    ↓
Trained model
    ↓
Generated response
Enter fullscreen mode Exit fullscreen mode

When your FastAPI application calls an LLM API, you're normally performing inference, not training.

Backend analogy

Think:

Training ≈ building/compiling/preparing the capability

Inference ≈ executing that capability for a request
Enter fullscreen mode Exit fullscreen mode

It's not a perfect analogy, but useful initially.

Temperature

Definition

Temperature controls how much variation is allowed during token selection.

Conceptually:

Temperature ↓
More predictable

Temperature ↑
More variation
Enter fullscreen mode Exit fullscreen mode

Example:

Prompt:
Give me a slogan for MotoShare.
Enter fullscreen mode Exit fullscreen mode

Low temperature might repeatedly produce similar direct answers.

Higher temperature may produce more diverse alternatives.

When should you use low temperature?

Tasks requiring consistency:

classification
data extraction
structured output
business decisions
API workflows
Enter fullscreen mode Exit fullscreen mode

Higher temperature?

Creative tasks:

marketing copy
brainstorming
story ideas
slogans
Enter fullscreen mode Exit fullscreen mode

But temperature does not magically turn the model into a truth engine.

Top-p and Sampling

The model may assign probabilities to candidate next tokens.

Example:

Delhi       70%
Mumbai      10%
Kolkata      7%
Chennai      5%
Enter fullscreen mode Exit fullscreen mode

Sampling determines how the next token is selected from that probability distribution.

Temperature and top-p influence this selection.

For Week 1:

Temperature
    ↓
changes probability sharpness/variation

Top-p
    ↓
limits selection to a probability mass

Sampling
    ↓
select next token

Next token
Enter fullscreen mode Exit fullscreen mode

You don't need the detailed mathematics yet.

Deterministic vs Probabilistic Software

This is a major mindset change for backend developers.

Traditional backend:

2 + 2
 ↓
4
Enter fullscreen mode Exit fullscreen mode

You expect the same result every time.

LLM:

"Write a vehicle description."
             ↓
            LLM
       ↙      ↓       ↘
Response A Response B Response C
Enter fullscreen mode Exit fullscreen mode

Therefore:


Traditional software

Input → Rules → Output


AI software

Input
 ↓
Prompt
 ↓
Probabilistic Model
 ↓
Possible Output
 ↓
VALIDATION
 ↓
Application
Enter fullscreen mode Exit fullscreen mode

Why this matters for Agentic AI

An agent may decide:

Which tool?
What arguments?
Do I need another tool?
Is the task complete?
Enter fullscreen mode Exit fullscreen mode

Therefore you cannot treat model output like trusted deterministic code.

Embeddings

This will become extremely important when you learn RAG.

Definition

An embedding converts information such as text into a numerical vector representing aspects of its semantic meaning.

"Rent a bike"
      ↓
Embedding model
      ↓
[0.13, -0.82, 0.44, ...]
Enter fullscreen mode Exit fullscreen mode

Consider:

A = "I want to rent a car."

B = "I need a vehicle for hire."

C = "Python supports decorators."
Enter fullscreen mode Exit fullscreen mode

Semantically:

Similarity(A, B) → HIGH
Similarity(A, C) → LOW

Enter fullscreen mode Exit fullscreen mode

even though A and B don't contain exactly the same words.

Backend analogy

Traditional search:

WHERE description LIKE '%car rental%'
Enter fullscreen mode Exit fullscreen mode

Semantic search:

Query
 ↓
Embedding
 ↓
Vector similarity search
 ↓
Semantically related documents
Enter fullscreen mode Exit fullscreen mode

Where will you use this?

Later:

RAG
semantic search
recommendations
document retrieval
knowledge bases
similarity matching
Enter fullscreen mode Exit fullscreen mode

Hallucination

Definition

Hallucination occurs when an LLM generates information that appears plausible but is unsupported, incorrect or fabricated.

Example:

User:
"What is the rental price of this vehicle?"

Context:
No price provided.

Bad model:
"The rental price is ₹1,500/day."
Enter fullscreen mode Exit fullscreen mode

The model created information that wasn't available.

Why?

Remember:

LLM
 ≠
database

LLM
 ≠
truth engine

LLM
 =
probabilistic language model
Enter fullscreen mode Exit fullscreen mode

Production solution

Never rely solely on:

"Please don't hallucinate."
Enter fullscreen mode Exit fullscreen mode

Instead build:

User question
      ↓
Retrieve trusted data
      ↓
Provide context
      ↓
LLM
      ↓
Structured output
      ↓
Validation
      ↓
Business rules
Enter fullscreen mode Exit fullscreen mode

This leads directly to RAG.

Pretraining

Definition

Pretraining is the large-scale initial training process through which an LLM learns language patterns and broad knowledge from huge datasets.

Massive dataset
      ↓
Pretraining
      ↓
General-purpose model
Enter fullscreen mode Exit fullscreen mode

As an application developer, you usually do not pretrain an LLM yourself.

It's extremely expensive.

Prompting

You provide instructions and context at inference time without changing the model's underlying trained weights.


Existing Model
     +
Prompt
     +
Context
     ↓
Response
Enter fullscreen mode Exit fullscreen mode

Example:

Classify this MotoShare enquiry into:

BOOKING
PAYMENT
CANCELLATION
OTHER

Enter fullscreen mode Exit fullscreen mode

No model training required.

Start here first

For most application problems:

Prompting
   ↓
Structured Output
   ↓
RAG
   ↓
Fine-tuning if justified
Enter fullscreen mode Exit fullscreen mode

Don't jump directly to fine-tuning.

Fine-tuning

Definition

Fine-tuning further trains an existing model using a specialized dataset to influence its behavior or capabilities for a particular task/domain.

Base Model
    ↓
Specialized training examples
    ↓
Fine-tuned Model
Enter fullscreen mode Exit fullscreen mode

Don't confuse this with RAG

Fine-tuning
    ↓
changes model behavior/weights

RAG
    ↓
supplies external information at runtime
Enter fullscreen mode Exit fullscreen mode

If the problem is:

"The AI doesn't know today's MotoShare vehicle inventory."
Enter fullscreen mode Exit fullscreen mode

Fine-tuning is generally the wrong solution.

You want:

Database / Search
        ↓
Retrieve current vehicles
        ↓
LLM
Enter fullscreen mode Exit fullscreen mode

RAG

RAG = Retrieval-Augmented Generation.
Enter fullscreen mode Exit fullscreen mode

Definition

RAG retrieves relevant information from an external source and supplies that information to an LLM as context before generation.

User Question
      ↓
Create/Search representation
      ↓
Knowledge Base / Vector DB
      ↓
Relevant Documents
      ↓
Prompt + Documents
      ↓
LLM
      ↓
Answer
Enter fullscreen mode Exit fullscreen mode

Why?

Your database may know:

Vehicle availability
Rental price
Booking policy
Cancellation policy
Enter fullscreen mode Exit fullscreen mode

The LLM shouldn't invent these.

Retrieve them.

Then let the LLM reason/generate using them.

Prompting vs RAG vs Fine-tuning

The complete LLM request lifecycle

Here is the architecture you should remember:

                React Application
                          │
                          │ HTTP
                          ▼
                  ┌───────────────┐
                  │    FastAPI    │
                  └───────┬───────┘
                          │
                    Validate Input
                          │
                          ▼
                 Build Instructions
                          │
                          ▼
                System + User Prompt
                          │
                          ▼
                   TOKENIZATION
                          │
                          ▼
                ┌──────────────────┐
                │  Context Window  │
                │                  │
                │ System Prompt    │
                │ User Prompt      │
                │ History          │
                │ RAG Context      │
                │ Tool Results     │
                └────────┬─────────┘
                         │
                         ▼
                  Transformer / LLM
                         │
                  ┌──────┴──────┐
                  │ Attention   │
                  │ Neural Net  │
                  │ Parameters  │
                  └──────┬──────┘
                         │
                         ▼
                 Next-token scores
                         │
                         ▼
             Temperature / Sampling
                         │
                         ▼
                  Select Token
                         │
                         ▼
               Generate Next Token
                         │
                    repeat...
                         │
                         ▼
                   Model Output
                         │
                         ▼
                Pydantic Validation
                         │
                 ┌───────┴────────┐
                 │                │
              Valid            Invalid
                 │                │
                 ▼                ▼
           Business Logic    Retry / Reject
                 │
                 ▼
             FastAPI Response
                 │
                 ▼
                React
Enter fullscreen mode Exit fullscreen mode

How everything connects

The entire Week 1 can be reduced to this mental model:

            AI
                     │
              Machine Learning
                     │
               Deep Learning
                     │
              Neural Networks
                     │
                Transformer
                     │
                    LLM
                     │
        ┌────────────┼─────────────┐
        │            │             │
      Tokens      Attention    Embeddings
        │            │             │
        └────────────┼─────────────┘
                     │
               Context Window
                     │
                   Prompt
                     │
                 Inference
                     │
        Temperature + Sampling
                     │
               Generated Output
                     │
              Possible Hallucination
                     │
                  Validation
                     │
             Production Application
Enter fullscreen mode Exit fullscreen mode

What you need to know before moving forward

Don't memorize definitions. You should be able to explain these relationships:

ML → Deep Learning → Neural Network → Transformer → LLM
Enter fullscreen mode Exit fullscreen mode

and:

Text → Tokens → Context → Transformer → probabilities → sampling → tokens → response → validation
Enter fullscreen mode Exit fullscreen mode

and finally:

Prompting = give instructions

RAG = give external/current knowledge

Fine-tuning = modify model behavior through additional training

Pretraining = create the general model capability
Enter fullscreen mode Exit fullscreen mode

Main Difference Between All the Concepts

chatgpt
differences
differences

Top comments (0)