Blogs and Insights

Thoughts, tutorials, and practical lessons on AI engineering, machine learning, and building useful software.

← Back to all blogs

Deep Learning · ML Engineering

Neural Networks, Explained from First Principles: Perceptrons, Backpropagation, PyTorch, and Tuning

How does a neural network actually learn? Start with one neuron, follow three numerical training updates, build a multilayer network in PyTorch, and learn how to tune and optimize it.

Scope: This article focuses on perceptrons and fully connected feedforward neural networks (multilayer perceptrons, or MLPs). It deliberately does not cover CNNs, RNNs, or Transformers. Numerical tables labeled illustrative are teaching examples, not reported experiment results.

The big idea: learning is a repeated correction

A neural network is not a collection of mysterious rules. It is a mathematical function with adjustable parameters—primarily weights and biases. During training, it makes a prediction, measures how far that prediction is from the correct answer, and adjusts its parameters to improve future predictions.

The essential cycle is:

Input features
      ↓
Linear layers (weights + biases)
      ↓
Activation functions
      ↓
Prediction (forward pass)
      ↓
Loss function: how wrong was it?
      ↓
Backpropagation: compute gradients
      ↓
Optimizer: update weights and biases
      ↺ Repeat with more training data

There are three distinct jobs worth remembering:

  • The loss function measures prediction error.
  • Backpropagation calculates how changing each trainable parameter would affect that error.
  • The optimizer uses those gradients to update the parameters.

Keeping those jobs separate makes almost every later training concept easier to understand.

1. From one perceptron to one prediction

Start with a single artificial neuron. It takes input values, multiplies them by weights, adds a bias, and applies an activation function.

For two features:

Here, and are inputs, and determine how strongly those inputs contribute, is a learned offset, and is the activation function.

Let's calculate a simple example:

Value Number
First input, 1
Second input, 0
First weight, 0.6
Second weight, −0.2
Bias, −0.3

With the classic perceptron's step activation—output 1 when , otherwise 0—the result is 1.

x1, x2 = 1, 0
w1, w2 = 0.6, -0.2
bias = -0.3

z = x1 * w1 + x2 * w2 + bias
output = 1 if z >= 0 else 0

print(z, output)  # 0.3 1

This simple model introduces the ingredients of larger networks. One important distinction: the classic perceptron uses a step function, whereas modern networks generally use activations suitable for gradient-based training.

2. What changes when we add layers?

A feedforward neural network connects many neurons in successive layers. Information moves from the input toward the output:

  • Input features describe an example, such as house size, bedrooms, and property age.
  • Hidden layers learn intermediate transformations.
  • The output layer produces the value or score required by the task.

Consider this small PyTorch model:

import torch.nn as nn

model = nn.Sequential(
    nn.Linear(3, 8),  # Three inputs → eight hidden neurons
    nn.ReLU(),        # Nonlinear activation
    nn.Linear(8, 4),  # Eight neurons → four
    nn.ReLU(),
    nn.Linear(4, 1),  # Four neurons → one output
)

Its architecture is 3 → 8 → 4 → 1. It has two hidden layers, with 8 and 4 neurons. The ReLU() operations are activations, not extra groups of neurons.

Each nn.Linear layer has weights and biases. For a layer with inputs and outputs, the trainable-parameter count is .

Layer Calculation Parameters
Linear(3, 8) 32
Linear(8, 4) 36
Linear(4, 1) 5
Total 73

The network is not specifically a house-price model. Its purpose depends on the training data, target, output design, and loss function. Three numerical inputs and one output could describe house-price regression, a student's predicted score, delivery time, or a binary-classification logit.

Why not just stack linear layers?

If there are no nonlinear activations between them, a stack of linear layers is still equivalent to one linear transformation. Activations allow the network to represent more complex relationships.

Common choices are:

Activation What it does Typical role
ReLU Hidden layers
Sigmoid Maps values into (0, 1) Convert binary logits to probabilities
Tanh Maps values into (−1, 1) Some hidden-layer designs
Softmax Converts a vector of logits to class probabilities Multiclass predictions

An important PyTorch detail: BCEWithLogitsLoss expects a raw logit, so do not put a sigmoid immediately before that loss. Likewise, CrossEntropyLoss normally receives raw multiclass logits, not probabilities already passed through softmax. For ordinary regression, the final linear layer often has no activation.

3. Forward pass, loss, and backpropagation

A forward pass is simply the computation that produces a prediction. With one linear neuron:

The prediction is compared with the actual target through a loss function.

For regression, a common choice is mean squared error (MSE):

If an actual value is 10 and the prediction is 8, the squared error for that one example is .

Problem Common loss PyTorch example
Predict a continuous number Mean squared error nn.MSELoss()
Predict one of two classes Binary cross-entropy from logits nn.BCEWithLogitsLoss()
Predict one of several classes Multiclass cross-entropy nn.CrossEntropyLoss()

The loss tells us how wrong the prediction is, but it does not update the model. To change parameters, we need gradients.

Backpropagation applies the chain rule of calculus to calculate how the loss depends on each weight and bias. For one neuron with squared-error loss,

we get:

These derivatives are gradients. A basic stochastic gradient descent (SGD) optimizer updates the parameters using a learning rate :

In PyTorch, loss.backward() computes the gradients and optimizer.step() applies the update. The learning rate determines the scale of that update: excessively small updates can make training slow, while excessively large ones can overshoot or destabilize it.

4. Watch a neuron learn: three real numerical iterations

The formulas become clearer when we follow the same neuron through three updates. Use a single training example and deliberately simple starting values:

Setting Value
Input 1
Actual target 2
Initial weight 0
Initial bias 0
Learning rate 0.1
Loss
Optimizer SGD

Iteration 1. Starting with and :

Both gradients are . Applying SGD:

Iteration 2. With , the next prediction is 0.8. Loss falls to 1.44, both gradients are , and the updated weight and bias become 0.64.

Iteration 3. With , the next prediction is 1.28. Loss falls to 0.5184, both gradients are , and the parameters become 0.784.

Iteration Prediction before update Loss before update Weight after update Bias after update
1 0.00 4.0000 0.400 0.400
2 0.80 1.4400 0.640 0.640
3 1.28 0.5184 0.784 0.784

After the third update, the next prediction—before another update—would be , with squared error .

That progression is the heart of training: predict → calculate loss → compute gradients → update parameters → predict again. The weight and bias happen to change equally here because ; for other inputs their gradients can differ.

You can reproduce every number without installing any machine-learning library:

x = 1.0
y = 2.0
weight = 0.0
bias = 0.0
learning_rate = 0.1

for iteration in range(1, 4):
    prediction = weight * x + bias
    loss = (y - prediction) ** 2

    grad_weight = 2 * (prediction - y) * x
    grad_bias = 2 * (prediction - y)

    weight -= learning_rate * grad_weight
    bias -= learning_rate * grad_bias

    print(
        f"Iteration {iteration}: prediction={prediction:.2f}, "
        f"loss={loss:.4f}, weight={weight:.3f}, bias={bias:.3f}"
    )

This is a deliberately controlled teaching example with one data point. Real training uses many examples and must be evaluated on data not used to fit the model.

5. Translating the learning cycle into PyTorch

The PyTorch equivalent of that learning loop is short:

# Assumes model, train_loader, loss_fn, and optimizer are defined.
for epoch in range(num_epochs):
    model.train()

    for X_batch, y_batch in train_loader:
        optimizer.zero_grad()                 # Clear previous gradients
        predictions = model(X_batch)         # Forward pass
        loss = loss_fn(predictions, y_batch) # Measure error
        loss.backward()                      # Compute gradients
        optimizer.step()                     # Update weights and biases

Four terms are easy to confuse:

Term Meaning
Parameter A learned value, such as a weight or bias
Hyperparameter A chosen setting, such as learning rate or layer width
Batch The examples processed for one optimizer update
Epoch One full pass through the training dataset

An iteration usually means one optimizer update. With 1,000 training examples and batch size 100, one epoch typically contains 10 iterations.

A small, complete example: learning XOR

XOR has the targets 0, 1, 1, 0 for the binary input pairs (0,0), (0,1), (1,0), and (1,1). One classic linear perceptron cannot learn that pattern, but a multilayer network with a nonlinear activation can.

import torch
from torch import nn

torch.manual_seed(0)

X = torch.tensor([
    [0., 0.],
    [0., 1.],
    [1., 0.],
    [1., 1.],
])
y = torch.tensor([[0.], [1.], [1.], [0.]])

model = nn.Sequential(
    nn.Linear(2, 8),
    nn.Tanh(),
    nn.Linear(8, 1),
)

loss_fn = nn.BCEWithLogitsLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.05)

for epoch in range(1000):
    optimizer.zero_grad()
    logits = model(X)
    loss = loss_fn(logits, y)
    loss.backward()
    optimizer.step()

model.eval()
with torch.no_grad():
    probabilities = torch.sigmoid(model(X))
    print(probabilities)

Notice that the model returns logits and sigmoid is applied after training, for interpretation. This four-example exercise demonstrates training mechanics, not real-world generalization: it evaluates the same examples used for learning.

6. How many hidden layers and neurons should a network have?

In PyTorch you can define deeper models simply by adding layers:

model = nn.Sequential(
    nn.Linear(3, 64),
    nn.ReLU(),
    nn.Linear(64, 32),
    nn.ReLU(),
    nn.Linear(32, 16),
    nn.ReLU(),
    nn.Linear(16, 8),
    nn.ReLU(),
    nn.Linear(8, 1),
)

That architecture is 3 → 64 → 32 → 16 → 8 → 1 and contains four hidden layers. You choose the depth and width, but more layers are not automatically better. Larger models can express more complex patterns while also consuming more computation and potentially fitting noise in the training data.

There is no universal formula for the ideal layer count. Start with a reasonable small model, compare validation results, and increase capacity only when the evidence supports it.

A useful practical distinction:

  • Underfitting: Both training and validation performance remain poor; investigate the data, feature quality, optimization setup, and model capacity.
  • Overfitting: Training loss improves while validation performance worsens; investigate regularization, data quality, model size, and when to stop training.

The training set teaches the model. A validation set helps select model settings. A separate test set, held back from tuning, is used for the final performance assessment.

7. The hyperparameters that actually matter

Hyperparameter tuning means selecting settings that govern the model's structure and training process. The network learns its weights and biases; you choose or search over settings such as layer widths and learning rate.

Area Hyperparameter What it controls Illustrative starting choices
Architecture Hidden layers Network depth 1–4 in small experiments
Architecture Hidden units Neurons per layer 8, 16, 32, 64, 128
Architecture Activation Nonlinearity ReLU, Tanh, GELU
Training Learning rate Parameter-update scale 0.01, 0.001, 0.0001
Training Optimizer Update algorithm SGD, Adam, AdamW
Training Batch size Examples per update 16, 32, 64, 128
Training Epochs Maximum complete data passes 50, 100, 200
Training Loss function Which error to minimize MSE, BCE-with-logits, cross-entropy
Regularization Dropout Fraction of activations dropped during training 0.1, 0.2, 0.3
Regularization Weight decay Penalty/discouragement for large weights 0.0001 as an experiment
Stability Gradient clipping Limit gradient magnitude max_norm=1.0 when needed
Training control Early-stopping patience Bad validation epochs tolerated before stopping 5–10
Training control Scheduler patience Bad epochs before an LR adjustment 2–3
Evaluation Validation split Data reserved for tuning/monitoring 0.2 as a simple starting point
Reproducibility Random seed Helps reproduce initialization and shuffling 42

These are examples to test, not universal defaults. Some settings (such as class weights, label smoothing, and probability thresholds) apply particularly to classification tasks rather than continuous regression. Normalization layers such as BatchNorm or LayerNorm are additional architecture choices when appropriate.

Dropout: reducing dependence on particular activations

model = nn.Sequential(
    nn.Linear(3, 32),
    nn.ReLU(),
    nn.Dropout(0.2),
    nn.Linear(32, 16),
    nn.ReLU(),
    nn.Linear(16, 1),
)

nn.Dropout(0.2) randomly zeroes approximately 20% of the activations on each training pass. It may reduce overfitting by discouraging dependence on particular activations. Too much dropout can make a small model underfit.

Use model.train() during training. model.eval() turns dropout off for validation and inference. PyTorch handles the training-time scaling internally.

Weight decay and gradient clipping serve different purposes

optimizer = torch.optim.AdamW(
    model.parameters(),
    lr=0.001,
    weight_decay=0.0001,
)

# In a training step, after loss.backward():
# torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)

Weight decay is a regularization technique. Gradient clipping is primarily a training-stability measure; it is not an interchangeable cure for overfitting.

8. A learning-rate scheduler is not early stopping

As training progresses, the learning rate that worked initially might become too large for fine adjustments. A scheduler can reduce it when a monitored metric stops improving.

A common PyTorch choice is ReduceLROnPlateau:

optimizer = torch.optim.Adam(model.parameters(), lr=0.001)

scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
    optimizer,
    mode="min",     # Lower validation loss is better
    factor=0.5,     # Halve the learning rate
    patience=3,
    min_lr=1e-6,
)

# After computing validation loss at the end of each epoch:
# scheduler.step(val_loss)

A sequence of reductions might be 0.001 → 0.0005 → 0.00025, but only when the plateau condition is met; these are not changes that automatically happen every three epochs.

One subtle detail: With PyTorch's ReduceLROnPlateau, patience=3 means it tolerates three bad epochs and normally reduces the learning rate when the bad-epoch count exceeds three—typically on the fourth bad epoch. If the goal is a reduction right after the third consecutive bad epoch, patience=2 is a closer match to that behavior.

Early stopping does something different: it ends training when validation results fail to improve sufficiently. A typical setup might have scheduler patience 3 and early-stopping patience 10, giving the scheduler time to make an adjustment before training stops.

Feature Learning-rate scheduler Early stopping
Watches validation performance Often Often
Changes the learning rate Yes No
Stops training No Yes
Useful when Progress plateaus but further improvement may be possible Continued training no longer seems useful

When implementing early stopping, track the best validation metric, count consecutive insufficient improvements, and save the best model weights for restoration. A min_delta threshold defines what counts as meaningful improvement. The scheduler may use its own different threshold rules.

9. Tuning architectures: grid search, random search, and Optuna

Neural-network tuning follows the same general logic as GridSearchCV and RandomizedSearchCV in scikit-learn: choose trial configurations, train on training data, compare on validation data, and select the best configuration.

Approach Strategy Tradeoff
Grid search Try every specified combination Simple, but gets expensive as choices multiply
Random search Sample combinations Covers larger spaces within a fixed trial budget
Optuna Adaptively suggest configurations Flexible for conditional choices and neural-network experiments

For example, Optuna can choose the number of hidden layers and neurons per layer:

import optuna
import torch.nn as nn


def objective(trial):
    n_layers = trial.suggest_int("layers", 1, 4)
    n_units = trial.suggest_categorical("units", [8, 16, 32, 64])

    modules = []
    in_features = 3

    for _ in range(n_layers):
        modules += [nn.Linear(in_features, n_units), nn.ReLU()]
        in_features = n_units

    modules.append(nn.Linear(in_features, 1))
    candidate = nn.Sequential(*modules)

    # Your own training/validation function must be implemented.
    return train_and_evaluate(candidate)


study = optuna.create_study(direction="minimize")
study.optimize(objective, n_trials=30)
print(study.best_params)

This Optuna snippet is an integration pattern, not standalone runnable code: train_and_evaluate is intentionally undefined. It must train the candidate and return a validation loss. For scikit-learn-style wrappers around PyTorch, skorch is another possibility; SciKeras is for Keras rather than native PyTorch networks.

Avoid using the final test set to pick your hyperparameters. Otherwise it becomes another validation set, and the reported final result is less meaningful.

10. Quantization: optimizing the trained model

Training and deployment have different concerns. After you have a useful model, you may want to reduce its memory footprint or improve inference performance. Quantization represents some weights and/or activations using lower-precision formats, such as INT8 rather than FP32.

Representation Bits per value Approximate raw storage for 1 million values
FP32 32 4 MB
FP16 / BF16 16 2 MB
INT8 8 1 MB
INT4 4 0.5 MB

FP16 and BF16 are lower-precision floating-point formats, not integer quantization. These storage figures omit scales, metadata, packing, padding, and other implementation overhead.

Three useful quantization terms:

  • Post-training quantization (PTQ): Apply quantization after training.
  • Quantization-aware training (QAT): Simulate quantization effects during training so the model can adapt.
  • Dynamic quantization: Quantize some values dynamically during inference, depending on the backend and method.

A version-dependent illustration of weight-only INT8 with torchao looks like this:

from torchao.quantization import quantize_, Int8WeightOnlyConfig

# 'model' must already be trained; backend/version compatibility varies.
model.eval()
quantize_(model, Int8WeightOnlyConfig())

That example is not guaranteed to work on every torchao version or hardware backend and does not imply all activations run in INT8. Benchmark inference accuracy, memory, and latency on the actual target device before accepting a quantized model.

Also, the earlier 3 → 8 → 4 → 1 network has only 73 trainable parameters: reducing their precision saves almost nothing in absolute terms. Quantization becomes more compelling when model size and deployment constraints justify it. The underlying principle also appears in LLM quantization, though methods such as GPTQ and AWQ are more specialized.

11. A complete training example: fit a small regression network

The following self-contained educational example ties together layers, nonlinearities, batch training, validation, dropout, AdamW, gradient clipping, a plateau scheduler, and early stopping. It creates synthetic data with three features and one continuous target; it does not download a real dataset or call an external API.

For clarity, this version separates training, validation, and test data, and restores the best validation checkpoint before evaluating the held-out test set.

import copy
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset

torch.manual_seed(42)

# Synthetic nonlinear regression: three features, one target.
X = torch.randn(1000, 3)
y = (
    2.0 * X[:, :1]
    - 1.5 * X[:, 1:2]
    + 0.8 * X[:, 2:3].square()
    + 0.1 * torch.randn(1000, 1)
)

# Keep the test set separate from the training/tuning decisions.
indices = torch.randperm(len(X))
train_idx = indices[:800]
val_idx = indices[800:900]
test_idx = indices[900:]

train_loader = DataLoader(
    TensorDataset(X[train_idx], y[train_idx]),
    batch_size=32,
    shuffle=True,
)
val_loader = DataLoader(
    TensorDataset(X[val_idx], y[val_idx]), batch_size=64
)
test_loader = DataLoader(
    TensorDataset(X[test_idx], y[test_idx]), batch_size=64
)

model = nn.Sequential(
    nn.Linear(3, 32),
    nn.ReLU(),
    nn.Dropout(0.2),
    nn.Linear(32, 16),
    nn.ReLU(),
    nn.Dropout(0.2),
    nn.Linear(16, 1),
)

loss_fn = nn.MSELoss()
optimizer = torch.optim.AdamW(
    model.parameters(), lr=0.001, weight_decay=0.0001
)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
    optimizer, mode="min", factor=0.5, patience=3, min_lr=1e-6
)


def evaluate(data_loader):
    model.eval()  # Disables dropout
    total_loss, total_count = 0.0, 0
    with torch.no_grad():
        for xb, yb in data_loader:
            batch_loss = loss_fn(model(xb), yb)
            total_loss += batch_loss.item() * len(xb)
            total_count += len(xb)
    return total_loss / total_count


best_val_loss = float("inf")
best_state = copy.deepcopy(model.state_dict())
bad_epochs = 0
early_stopping_patience = 10
min_delta = 0.001

for epoch in range(100):
    model.train()
    for xb, yb in train_loader:
        optimizer.zero_grad()
        predictions = model(xb)
        loss = loss_fn(predictions, yb)
        loss.backward()
        torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
        optimizer.step()

    val_loss = evaluate(val_loader)
    scheduler.step(val_loss)

    if val_loss < best_val_loss - min_delta:
        best_val_loss = val_loss
        best_state = copy.deepcopy(model.state_dict())
        bad_epochs = 0
    else:
        bad_epochs += 1

    current_lr = optimizer.param_groups[0]["lr"]
    print(f"Epoch {epoch + 1:3d} | Val MSE {val_loss:.5f} | LR {current_lr:.6f}")

    if bad_epochs >= early_stopping_patience:
        print("Early stopping triggered")
        break

model.load_state_dict(best_state)
test_mse = evaluate(test_loader)
print(f"Held-out test MSE: {test_mse:.5f}")

Run it with Python and PyTorch installed:

pip install torch
python neural_network_example.py

The test MSE printed by this script is a result of your own run; no specific score is promised here. Real applications also require representative data, leakage-safe preprocessing, task-appropriate metrics, and evaluation of the conditions in which predictions will be used.

12. A practical checklist for diagnosing training

When a model performs poorly, the most productive first question is not always "Should I add more layers?" Look at the pattern in the training and validation metrics.

What you observe What to investigate first
Training loss barely decreases Input scaling, target quality, learning rate, gradients, model capacity
Training loss oscillates or diverges Learning rate, data values, batch size, gradient stability
Training improves, validation worsens Overfitting, data quality, dropout, weight decay, smaller architecture
Both training and validation remain poor Underfitting, features, optimization settings, training duration
Validation loss stops improving LR scheduler, early-stopping patience, whether more capacity helps
Model is too large or slow for deployment Size/latency profiling, then quantization if supported

A reasonable workflow is to define the supervised task → split the data → prepare features without leakage → build a simple network → train and validate → tune deliberately → test on held-out data → optimize deployment if necessary.

Closing thought

A neural network makes more sense once its components stop looking like separate buzzwords. Layers and activations determine what it can represent. Loss and gradients explain what it needs to change. Optimizers and learning rates control how it changes. Validation, regularization, and training controls help determine whether it learned something useful rather than merely memorizing the examples.

Start with one neuron and three parameter updates. Once that is intuitive, the larger PyTorch architecture is the same fundamental learning process repeated across many parameters.


← Back to all blogs

AI Engineering · LLMOps

Retrieval-Augmented Generation, Explained: From Documents to Reranking and Grounded Answers

How does a RAG system turn university admission PDFs into reliable answers? Follow the full pipeline, learn the settings that matter in code, and understand how a reranker is trained as a machine-learning model.

Scope: This article covers RAG mechanics, coding settings, and reranking—including its ML training process. It deliberately excludes explanations of attention mechanisms and Transformer architectures. University admission requirements, similarity scores, and sample training labels below are illustrative, not verified University X policies or reported experiment results.

The problem: answering questions from documents, not memory

Imagine a student asks a university chatbot:

“What documents do I need to apply to University X?”

The university maintains admission guides, eligibility rules, international-student instructions, and application deadlines as PDFs and web pages. A general-purpose LLM might know something about university applications, but it should not guess University X’s current requirements.

Retrieval-Augmented Generation (RAG) addresses that problem by finding relevant information in an external collection and supplying it to the LLM when it answers. The LLM is not retrained on every PDF update: the searchable collection can be reindexed as the documents change.

RAG has two distinct phases:

OFFLINE / WHEN DOCUMENTS CHANGE
PDFs, web pages, database records
    → Load and extract text
    → Split into chunks
    → Embed chunks as vectors
    → Store vectors + text + source metadata

ONLINE / WHEN A STUDENT ASKS
Student's question
    → Embed question
    → Retrieve candidate chunks (e.g., top 20)
    → Rerank candidates (e.g., keep best 5)
    → Build a prompt with question + evidence
    → LLM generates answer with source citations

The key separation is retrieval finds evidence; generation turns that evidence into an answer. Reranking sits between them and improves which evidence reaches the LLM.

1. Document ingestion: loading PDFs correctly

For a PDF-based knowledge base, PyPDFLoader from langchain-community is a convenient wrapper around PDF text extraction. The similarly named pypdf package is the underlying PDF-processing library; they are not the same API.

from langchain_community.document_loaders import PyPDFLoader

loader = PyPDFLoader(
    "admission.pdf",
    mode="page",
    extraction_mode="plain",
    extract_images=False,
)

pages = loader.load()
print(pages[0].page_content[:200])
print(pages[0].metadata)

This is runnable with an actual admission.pdf and the required dependencies installed. Each page is returned as a document with text and metadata such as the source path and page index.

Setting What it determines Example / tradeoff
File path Which PDF is loaded "admission.pdf"
mode Whether one document represents a page or the whole file "page" preserves page-level references; "single" can avoid page-boundary breaks
extraction_mode How ordinary PDF text is extracted "plain" vs. "layout" where supported
extract_images Whether to process embedded PDF images False for text-centric PDFs; image extraction needs additional handling
Password How to access encrypted PDFs Set only if needed

A PDF can look readable while containing scanned images rather than selectable text. Ordinary PDF text extraction is not OCR; scanned admission forms may require OCR or other image-aware extraction. Validate a few pages before indexing the whole collection.

Keep metadata alongside every chunk—for example source, page, university, document title, and a version/date if known. Metadata makes filtering and citations possible. For the page index returned by the loader, note that page is commonly zero-based; use page_label where available for human-readable citations.

2. Chunking: why chunk_size and chunk_overlap matter

Suppose an admission guide is 80 pages long. Embedding the entire guide as a single vector would mix requirements, fees, housing, deadlines, and other topics into one representation. Instead, split it into smaller chunks that preserve useful meaning.

Two settings are especially important:

  • chunk_size: The maximum target length of a chunk, in characters or tokens depending on the splitter. It includes any overlap; it is not the new content plus overlap.
  • chunk_overlap: Content carried over between adjacent chunks to avoid losing information at boundaries. It is a target, not a promise that every pair will overlap by exactly that amount.

For a simplified fixed-length example, chunk_size=100 and chunk_overlap=20 means a 100-unit chunk followed by a new chunk beginning 80 units later. Real splitters usually prefer paragraph or sentence boundaries, so their chunk lengths can vary.

Characters and tokens are not interchangeable. With the standard RecursiveCharacterTextSplitter, chunk_size=500 usually means 500 characters because the default length_function is len. A tokenizer-aware splitter instead measures token counts.

from langchain_text_splitters import RecursiveCharacterTextSplitter

# Default: counts characters, not model tokens.
character_splitter = RecursiveCharacterTextSplitter(
    chunk_size=500,
    chunk_overlap=75,
    add_start_index=True,
)

# Alternative: count tokens with the embedding model's tokenizer.
from sentence_transformers import SentenceTransformer

embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
token_splitter = RecursiveCharacterTextSplitter.from_huggingface_tokenizer(
    embedding_model.tokenizer,
    chunk_size=180,
    chunk_overlap=30,
    add_start_index=True,
)

chunks = token_splitter.split_documents(pages)

The second example is aligned to the chosen embedding model’s tokenizer. Its 180/30 values are starting choices to test, not universal defaults. all-MiniLM-L6-v2 truncates inputs beyond its model limit (commonly 256 word pieces), so choosing 500 tokens with that particular embedding model can silently discard part of each chunk. Tokenizer limits, special tokens, and the model’s effective maximum input length must be checked together.

The default recursive splitter tries boundaries such as "\n\n", "\n", " ", and finally individual characters. separators controls that order; add_start_index=True adds a chunk’s character start offset to metadata when it can be located.

Chunking decision Benefit Risk if taken too far
Smaller chunks More focused retrieval A requirement may be separated from its qualification
Larger chunks More surrounding context Irrelevant material, longer prompts, possible truncation
More overlap Better continuity across boundaries Duplicates, larger index, repeated evidence
Page-based loading Easier page citations A paragraph may cross a page boundary

Practical rule: Start with meaningful document sections, use a tokenizer compatible with your embedding model, and tune chunking based on questions your system must answer.

3. Embeddings and the vector database

An embedding model turns a text chunk into a numerical vector. A bi-encoder generates embeddings for the question and chunks independently. You can therefore calculate document embeddings once during indexing and reuse them across many student questions.

For example, all-MiniLM-L6-v2 produces 384-dimensional embeddings. In a real system, the vector database stores the vector together with its original text and metadata. Options for vector search include FAISS and Pinecone; FAISS is a similarity-search library, while Pinecone is a managed vector-database service.

Similarity is often measured with cosine similarity:

cosine(𝐪,𝐝)=𝐪⋅𝐝∥𝐪∥∥𝐝∥ \operatorname{cosine}(\mathbf{q},\mathbf{d}) =\frac{\mathbf{q}\cdot\mathbf{d}}{\|\mathbf{q}\|\,\|\mathbf{d}\|}

Here, 𝐪\mathbf{q} is the question embedding and 𝐝\mathbf{d} is a document-chunk embedding. The score measures vector alignment—not a guaranteed probability that a passage correctly answers the question.

texts = [chunk.page_content for chunk in chunks]

vectors = embedding_model.encode(
    texts,
    batch_size=32,
    normalize_embeddings=True,
)

question = "What documents do I need to apply to University X?"
query_vector = embedding_model.encode(
    [question], normalize_embeddings=True
)[0]
Embedding setting Meaning Example
model_name Which text-to-vector model is used all-MiniLM-L6-v2
embedding_dimension How many numbers each vector contains 384 for this model
batch_size Number of texts encoded per batch 32
normalize_embeddings Whether vectors have unit length True
Model input limit How much text the encoder actually sees Model-specific; check truncation
Similarity metric How vectors are compared Cosine or dot product

Consistency matters: Index and query with the same compatible embedding model and preprocessing setup. If you switch to a model producing different embeddings, the collection normally needs to be re-embedded. The vector index must use the expected dimension.

4. Retrieval: top_k is not a threshold

At query time, the system embeds the student’s question and searches the stored chunk vectors.

If top_k=20, the retriever asks for the 20 highest-ranking candidates. This does not mean the candidates each exceeded a similarity of 0.87. A score threshold, if supported, is an additional filter; the numeric scale depends on the model, metric, and database implementation.

Retrieval setting What it controls Example
top_k / k Number of candidate chunks returned 20
similarity_metric Vector comparison Cosine
score_threshold Optional minimum accepted similarity Must be calibrated; no universal 0.87
metadata_filter Which documents are eligible university = X
search_type How candidates are found Similarity, MMR, or hybrid retrieval
fetch_k Initial candidate count for methods such as MMR 40

Metadata filtering is valuable here: a highly similar passage from University Y is still the wrong evidence for University X. In some systems, hybrid retrieval combines semantic vector search with keyword search. MMR (maximal marginal relevance) can balance relevance against near-duplicate results.

A successful retriever aims for recall: get enough genuinely useful passages into the candidate set. It does not need to arrange all 20 perfectly—that is where reranking can help.

5. Reranking: a second, more careful relevance judgment

The student asks:

“What documents do I need to apply to University X?”

Vector retrieval returns 20 candidate chunks. Some may discuss fees or admission deadlines because their wording overlaps with the question. Reranking scores each retrieved passage against the actual question and sorts the candidates again.

Vector retrieval:     top_k = 20 candidate chunks
                              ↓
Cross-encoder:        question + chunk → relevance score
                      (repeated for each of 20 chunks)
                              ↓
Reranking:            sort by the new scores
                              ↓
Selection:            top_n = 5 chunks for the LLM

This is not just another cosine-similarity sort.

Retrieval with a bi-encoder Reranking with a cross-encoder
Encodes the question and documents separately Evaluates a question–document pair jointly
Compares stored vectors mathematically Uses a learned model to predict pair relevance
Efficient across a large collection More expensive for each candidate pair
Optimized for finding likely matches quickly Used to improve ordering within a candidate set

Both models perform numerical computation internally. “Cross-encoder reads the text” does not mean it operates without numerical representations; it means it uses the paired text as one model input instead of comparing two independently precomputed embeddings.

A concrete example

The following scores are invented to demonstrate ranking, not outputs from the actual model:

Candidate passage Illustrative reranker score
University X — passport, transcripts, and language certificate 0.96
University X — general eligibility criteria 0.79
University X — annual tuition 0.18

The reranker can elevate a passage that directly answers the documents question over one that merely concerns university admissions. It also has a limitation: it cannot recover a relevant passage that retrieval failed to include in the first 20 candidates.

Real inference code

from sentence_transformers import CrossEncoder

reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L6-v2")

candidate_texts = [
    "Applicants must submit their passport and transcript.",
    "University X charges an annual tuition fee.",
    "Applicants must provide English proficiency evidence.",
]

pairs = [(question, passage) for passage in candidate_texts]
scores = reranker.predict(pairs)

ranked = sorted(
    zip(candidate_texts, scores),
    key=lambda item: float(item[1]),
    reverse=True,
)

for passage, score in ranked:
    print(round(float(score), 3), passage)

The code is runnable after model dependencies are installed and the pretrained weights are available. It deliberately prints model scores, not fabricated outputs. The model shown commonly returns raw logits, not calibrated probabilities from 0 to 1. A score threshold such as >= 0.87 must therefore not be copied blindly from a hypothetical example. CrossEncoder.rank(question, passages, top_k=5) is another supported API for ranking and selecting candidates.

Top-K and threshold are separate ideas: top_n=5 keeps at most five highest-ranked candidates; an optional calibrated threshold can reject insufficiently relevant results. A system can apply either or both.

6. How a reranker is trained as an ML model

A reranker is not an invented function such as magic_relevance_score(question, chunk). A pretrained reranker is a supervised machine-learning model whose parameters were optimized on examples of query–passage relevance.

One well-known training resource is MS MARCO, built around real web-search queries and candidate passages. The pretrained model cross-encoder/ms-marco-MiniLM-L6-v2 is a concrete example of a reranker trained for passage ranking. The rows below are our university example, not literal MS MARCO records:

Query Passage Relevance label
Required admission documents? Submit passport and transcript 1
Required admission documents? Tuition costs $12,000 annually 0
Required admission documents? University X was founded in 1950 0

For a binary-relevance training setup, the loop looks like any other supervised ML training process:

Labeled (question, passage) pairs
    → Model predicts relevance
    → Loss compares prediction with label
    → Backpropagation computes parameter gradients
    → Optimizer updates model parameters
    → Repeat and validate on held-out queries

With binary labels y∈{0,1}y\in\{0,1\} and predicted probability pp, one possible objective is binary cross-entropy:

L=−[ylog(p)+(1−y)log(1−p)] L=-\left[y\log(p)+(1-y)\log(1-p)\right]

  • y=1y=1: the passage is labeled relevant.
  • y=0y=0: the passage is labeled non-relevant.
  • pp: a probability derived from the model’s prediction for this training objective.

This is one possible training approach, not the universal loss for every reranker. Ranking-based objectives can instead learn which passages should score above others. A model may output raw logits at inference even when its training objective uses binary cross-entropy.

Why hard negatives matter

A random passage about football is an easy negative for a university-documents question. A better training challenge is a hard negative:

“University X admissions are open until December 1.”

It sounds relevant to admissions, but it does not answer which documents must be submitted. Hard negatives teach the reranker to distinguish a general topic match from evidence that actually answers the question.

A minimal fine-tuning illustration

from datasets import Dataset
from sentence_transformers import CrossEncoder
from sentence_transformers.cross_encoder import (
    CrossEncoderTrainer,
    CrossEncoderTrainingArguments,
)
from sentence_transformers.cross_encoder.losses import BinaryCrossEntropyLoss

train_data = Dataset.from_dict({
    "sentence1": [
        "What documents are required?",
        "What documents are required?",
        "What is the tuition fee?",
    ],
    "sentence2": [
        "Submit a passport and transcript.",
        "The university was founded in 1950.",
        "Annual tuition is $12,000.",
    ],
    "label": [1.0, 0.0, 1.0],
})

model = CrossEncoder("cross-encoder/ms-marco-MiniLM-L6-v2")
args = CrossEncoderTrainingArguments(
    output_dir="./university-reranker",
    num_train_epochs=3,
    per_device_train_batch_size=2,
    learning_rate=2e-5,
    report_to="none",
)
trainer = CrossEncoderTrainer(
    model=model,
    args=args,
    train_dataset=train_data,
    loss=BinaryCrossEntropyLoss(model),
)
trainer.train()
model.save_pretrained("./university-reranker")

This is an API-level, runnable fine-tuning illustration with current Sentence Transformers training interfaces, subject to library-version and hardware compatibility. Its three examples are far too few to produce a useful new reranker; they show the components and workflow, not a trained system validated for university admissions. A real project needs a much larger dataset with positive and negative examples, a held-out validation set, and ranking metrics such as MRR or nDCG.

You usually do not have to train a reranker from scratch. Start with a pretrained model, evaluate it on your own admission questions, and fine-tune only if the domain evidence supports doing so.

7. Context augmentation and the LLM answer

Once reranking selects the strongest chunks, put the question and the retrieved passages into a prompt. Include source references so the answer can cite evidence.

SYSTEM:
Answer using only the supplied University X documents.
If the documents do not establish an answer, say so.
Cite the source document and page for each requirement.

CONTEXT:
[admission.pdf, page 4]
Applicants must submit transcripts and a passport copy.

[international_students.pdf, page 2]
Proof of English proficiency is required for this program.

QUESTION:
What documents do I need to apply to University X?

A possible answer to this hypothetical context is:

For the program covered by these documents, you need transcripts and a passport copy (admission.pdf, p. 4), plus proof of English proficiency (international_students.pdf, p. 2).

The LLM should not invent a motivation-letter requirement if that is absent from the supplied passages. It also should not claim the retrieved passages are exhaustive when they might omit another applicable admission rule. University, program, degree level, intake year, and applicant type can all matter; filtering metadata or asking a targeted follow-up may be necessary.

RAG does not retrain the LLM at answer time. It augments the prompt with evidence retrieved from the external source collection. Retrieval can reduce unsupported answers, but it does not guarantee factual accuracy.

8. All the important RAG coding settings, in one place

These are starting configurations to evaluate, not universal best practices. Library names and supported parameters vary, especially across vector databases and LLM providers.

Stage Setting What it defines Illustrative value
PDF loading mode Per-page vs. whole-PDF document "page"
PDF loading extraction_mode Text extraction style "plain"
PDF loading extract_images Embedded-image handling False
Chunking chunk_size Maximum target chunk length; units depend on tokenizer/length function 180 model tokens in the MiniLM example
Chunking chunk_overlap Repeated context at chunk boundaries 30 model tokens
Chunking length_function / tokenizer Whether length means characters or tokens Embedding-model tokenizer
Chunking separators Preferred boundaries when splitting Paragraphs, lines, spaces
Embeddings embedding_model Which model produces vectors all-MiniLM-L6-v2
Embeddings embedding_dimension Stored vector length 384 for that model
Embeddings batch_size Texts processed per embedding batch 32
Embeddings normalize_embeddings Unit-length vectors for comparison True
Index / search similarity_metric Vector comparison method Cosine
Retrieval top_k Initial retrieved-candidate count 20
Retrieval metadata_filter Restricts the source collection University X
Retrieval score_threshold Optional minimum accepted similarity Calibrate on your data
Retrieval search_type / fetch_k Similarity vs. diversity/hybrid search and candidate pool MMR with fetch_k=40, if used
Reranking reranker_model Pairwise relevance-scoring model MS MARCO MiniLM cross-encoder
Reranking top_n How many reranked chunks reach the LLM 5
Reranking max_length Reranker pair-input limit Model-specific
Generation temperature Randomness of sampling, if supported 0–0.2
Generation max_output_tokens Upper bound on generated response length 500
Generation top_p Nucleus-sampling control 1.0
Generation Context budget How many retrieved tokens can fit, alongside prompt and response Model-specific
Reliability API timeout Upper bound for a request to complete e.g., 30 seconds

A small configuration object

RAG_CONFIG = {
    "pdf_mode": "page",
    "chunk_size": 180,               # Embedding-model tokens
    "chunk_overlap": 30,
    "embedding_model": "all-MiniLM-L6-v2",
    "embedding_batch_size": 32,
    "normalize_embeddings": True,
    "similarity_metric": "cosine",
    "retrieval_top_k": 20,
    "reranker_model": "cross-encoder/ms-marco-MiniLM-L6-v2",
    "rerank_top_n": 5,
    "temperature": 0.1,
    "max_output_tokens": 500,
}

This is a configuration template, not a complete application: your code must read and apply these values to the chosen libraries. Keep separate budgets for embedding-model input length, reranker pair length, and LLM input/output tokens; they are different limits.

9. A compact, runnable retrieval-and-reranking demonstration

This script demonstrates the central online retrieval + reranking part without requiring a vector-database server or paid LLM API. It uses three illustrative passages as a tiny in-memory collection. It prints the best evidence and a draft prompt; it does not call an LLM or generate an answer.

Install the core library:

pip install sentence-transformers numpy
import numpy as np
from sentence_transformers import CrossEncoder, SentenceTransformer

question = "What documents do I need to apply to University X?"
passages = [
    "University X applicants must provide a passport copy and transcripts.",
    "University X tuition fees are listed in the finance guide.",
    "International applicants to University X need proof of English proficiency.",
]
sources = ["admission.pdf, p. 4", "fees.pdf, p. 1", "international.pdf, p. 2"]

# Indexing: independently embed each passage.
encoder = SentenceTransformer("all-MiniLM-L6-v2")
doc_vectors = encoder.encode(passages, normalize_embeddings=True)

# Query: compare the question vector against stored vectors.
query_vector = encoder.encode([question], normalize_embeddings=True)[0]
similarities = doc_vectors @ query_vector  # cosine for normalized vectors
candidate_ids = np.argsort(similarities)[::-1][:20]

# Reranking: score each question–passage pair with a second model.
reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L6-v2")
pairs = [(question, passages[int(i)]) for i in candidate_ids]
rerank_scores = reranker.predict(pairs)
order = np.argsort(rerank_scores)[::-1][:2]
selected_ids = [int(candidate_ids[int(j)]) for j in order]

# The next step would be to pass this prompt to your chosen LLM.
context = "\n\n".join(
    f"[{sources[i]}]\n{passages[i]}" for i in selected_ids
)
prompt = (
    "Answer only from this context and cite its sources. "
    "If evidence is missing, say so.\n\n"
    f"Context:\n{context}\n\nQuestion: {question}"
)
print(prompt)

Why [:20] returns only three candidates here: the demonstration contains only three passages. In a real indexed university corpus, top_k=20 means up to 20 candidates, and the selected count is also constrained by filters and the contents of the index.

For a real PDF-backed application, replace the passages list with your loaded and chunked documents, preserve their metadata, persist the embeddings in a vector index, and supply the constructed prompt to a configured LLM. Those integrations depend on the chosen database and LLM provider, so they are intentionally not presented here as working API calls.

10. How to evaluate and debug a RAG system

Changing top_k, chunk size, or the reranker is meaningful only if you can observe whether the system improves. Make a small test set of real university questions with known supporting passages and expected answers.

Observation Likely investigation
Relevant document never appears in top 20 Extraction quality, metadata filters, chunking, embeddings, retrieval recall
Right document appears at rank 15 but is missed in final 5 Reranker relevance quality, reranking top_n, hard negatives
Retrieved passage is cut in the middle of a requirement Chunk boundaries, overlap, tokenizer limit
Correct passages are provided but answer invents requirements Prompt constraints, generation behavior, citation checking
Response is too slow Retrieval size, reranker candidate count, embedding/API latency
Token usage is unexpectedly high Number and size of selected chunks, duplicate overlap, output budget

Useful measurements include Recall@K for retrieval, MRR or nDCG for ranking, answer correctness and citation accuracy for generation, plus p50/p95 latency and per-request cost. Evaluate on held-out questions, not only the examples used to tune settings or train a reranker.

One important failure boundary: reranking fixes the order of candidates; it does not fix missing source documents, bad OCR, incorrect metadata, or unsupported final claims. A reliable RAG system needs each stage to work.

Closing thought

RAG becomes much easier to reason about when the stages have distinct jobs:

Load accurate sources → split them into sensible chunks → embed and index them → retrieve broadly → rerank carefully → give the LLM a small, cited evidence set → check the final answer.

The first retrieval stage uses fast vector similarity to find potential evidence. The cross-encoder reranker is a separately trained ML model that scores the question–passage pair more carefully. Settings such as chunk_size, tokenizer, top_k, top_n, context budget, and model choice control how much useful information reaches the LLM—and at what latency and cost.

The goal is not merely to produce a fluent answer about University X. It is to produce an answer the student can trace back to the correct, applicable university documents.