Core Training Module 02 • Foundations of Intelligence

02. Machine Learning (ML) & AI Foundations

The mathematical and architectural bedrock of modern artificial intelligence: from classical statistical pattern recognition to deep neural networks, natural language processing, and the Transformer architecture that powers Generative AI and LLMs.

Instructor Insight: You cannot truly master LLMs, RAG, and autonomous agents without understanding how vectors, attention matrices, and loss backpropagation operate under the hood. Treat the Transformer as your engine.
Visual Architecture Blueprint

02. AI / ML Foundation Roadmap

How statistical data transforms through neural representations into modern Transformer foundation models.

02. AI / ML Foundation
From Data to Intelligence • Machine Learning • Deep Learning • NLP • Transformers
Machine Learning
Pillar 01
  • Supervised ML
  • Unsupervised ML
  • Features
  • Evaluation
  • Model Serving
Scikit-learn • XGBoost • MLOps Inspect →
Deep Learning
Pillar 02
  • Neural Networks
  • Backpropagation
  • Optimizers
  • PyTorch
  • GPU Basics
PyTorch • CUDA • Backprop Inspect →
NLP
Pillar 03
  • Tokenization ✓
  • Embeddings ✓
  • Attention ✓
  • NLP Basics ✓
Text Vectorization • Semantics Inspect →
From
Data
to
Intelligence
•••
Transformers
Heart of Modern LLMs
Architecture Mechanics
  • Self Attention ✓
  • Multi-Head Attention ✓
  • Positional Encoding ✓
  • Encoder / Decoder ✓
Lifecycle & Serving
  • Pretraining ✓
  • Fine-Tuning ✓
  • Inference ✓
Build
Real AI
Systems
⇒ LLM
Comprehensive Deep-Dive

3. Detailed Pillar Exploration & Code Blueprints

Examine the mathematical mechanics, day-1 practical applications, and code examples for each component of the AI / ML foundation.

Pillar 01 • Statistical Learning
Classical Machine Learning (ML) & MLOps
Core Statistical ML
Core Concepts
  • Supervised ML: Mapping inputs to known labels (Classification & Regression via Logistic Regression, Random Forest, XGBoost)
  • Unsupervised ML: Finding latent patterns without labels (K-Means, DBSCAN clustering, PCA dimensionality reduction)
  • Feature Engineering: One-hot encoding, scaling, imputing missing data, creating interaction variables
  • Evaluation Metrics: Precision, Recall, F1-Score, ROC-AUC curve, Confusion Matrix, and Mean Squared Error
  • Model Serving: Serializing models to ONNX/Joblib and deploying low-latency inference endpoints
Scikit-Learn Training Pipeline
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
import joblib

# 1. Train-test split
X_train, X_test, y_train, y_test = train_test_split(
    features, labels, test_size=0.2, random_state=42
)

# 2. Fit model
clf = RandomForestClassifier(n_estimators=100)
clf.fit(X_train, y_train)

# 3. Evaluate & Serialize for Production
preds = clf.predict(X_test)
print(classification_report(y_test, preds))
joblib.dump(clf, "model.joblib")
Why AI Engineers Care
Day-1 Takeaway

Not every problem requires a heavy billion-parameter LLM. Production AI systems frequently use lightweight Scikit-learn or XGBoost classifiers for fast pre-filtering, intent classification, and routing before invoking expensive generative models.

Pillar 02 • Neural Computation
Deep Learning & PyTorch Framework
Neural Networks
Core Concepts
  • Neural Networks: Perceptrons, hidden layers, non-linear activations (ReLU, GELU, Sigmoid, Softmax)
  • Backpropagation: Applying calculus chain rule to calculate gradients of loss with respect to weights
  • Optimizers: Gradient Descent, Stochastic Gradient Descent (SGD), Adam, and AdamW with weight decay
  • PyTorch Framework: Tensors, computational dynamic graph, nn.Module, and training loop lifecycle
  • GPU Basics: CUDA device placement, tensor memory allocation, half-precision (FP16/BF16), and batching
PyTorch Training Loop Blueprint
import torch
import torch.nn as nn

# 1. Define Model
class NeuralNet(nn.Module):
    def __init__(self, in_dim, out_dim):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(in_dim, 128),
            nn.GELU(),
            nn.Linear(128, out_dim)
        )
    def forward(self, x): return self.net(x)

# 2. Setup GPU, Optimizer & Loss
device = "cuda" if torch.cuda.is_available() else "cpu"
model = NeuralNet(768, 10).to(device)
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3)
criterion = nn.CrossEntropyLoss()
Why AI Engineers Care
Day-1 Takeaway

Every foundation model (Claude, GPT, Llama) is fundamentally a PyTorch network trained via backpropagation and AdamW across clusters of GPUs. Understanding tensor math lets you fine-tune models, debug CUDA memory crashes, and quantize weights.

Pillar 03 • Natural Language Processing
NLP, Tokenization & Vector Embeddings
Language Vectors
Core Concepts
  • Tokenization: Breaking text into discrete tokens using Byte-Pair Encoding (BPE), WordPiece, or SentencePiece
  • Dense Embeddings: Mapping words and concepts into dense high-dimensional geometric coordinate space
  • Cosine Similarity: Measuring semantic proximity between vectors: cos(θ) = (A • B) / (||A|| ||B||)
  • Attention Intuition: Allowing words to look at surrounding words rather than processing sequentially like RNNs
  • NLP Tasks: Named entity recognition (NER), sentiment analysis, semantic text similarity
Tokenization & Embedding Code
from sentence_transformers import SentenceTransformer
import tiktoken

# 1. Subword Tokenizer
enc = tiktoken.get_encoding("cl100k_base")
tokens = enc.encode("AI agents reason over context")
print(f"Token IDs: {tokens}")

# 2. Semantic Embedding Generation
embedder = SentenceTransformer("all-MiniLM-L6-v2")
vector = embedder.encode("PostgreSQL with pgvector")
print(f"Embedding Vector Dimensions: {vector.shape}")
# -> Output: (384,) floating point coordinates
Why AI Engineers Care
Day-1 Takeaway

Embeddings are the universal currency of modern Retrieval-Augmented Generation (RAG) and semantic search. When you chunk a PDF, calculate its vector, and store it in PostgreSQL or Pinecone, you are applying foundational NLP.

Pillar 04 • The Engine of LLMs
The Transformer Architecture (Attention is All You Need)
Foundation Architecture
Core Concepts
  • Self-Attention: Calculating Query, Key, and Value matrices: Attention(Q, K, V) = softmax(QK^T / √d_k) V
  • Multi-Head Attention: Running multiple attention projections simultaneously to capture syntax, semantics, and context
  • Positional Encoding: Giving word vectors spatial order (Sinusoidal embeddings and modern RoPE)
  • Decoder-Only LLMs: The architecture of GPT and Claude: causal masking where tokens only look backwards
  • Pretraining & Fine-Tuning: Unsupervised next-token prediction followed by instruction tuning (SFT) and RLHF
  • Inference Optimization: Key-Value (KV) caching to eliminate redundant re-computation of previous tokens
Scaled Dot-Product Attention
import torch
import torch.nn.functional as F

def scaled_dot_product_attention(Q, K, V):
    # d_k: dimension of key vectors
    d_k = Q.size(-1)
    
    # Calculate attention scores
    scores = torch.matmul(Q, K.transpose(-2, -1)) / (d_k ** 0.5)
    
    # Softmax over token probabilities
    weights = F.softmax(scores, dim=-1)
    
    # Weighted sum of Values
    return torch.matmul(weights, V), weights
Why AI Engineers Care
Day-1 Takeaway

Every modern Generative AI capability — from code generation to autonomous tool invocation — stems from the Transformer's ability to attend over context. Mastering its attention mechanism is the difference between being a prompt user and a true AI systems engineer.

Practical Engineering Projects

4. Hands-On Labs in This Module

Four applied coding labs built in Python, PyTorch, and Scikit-Learn.

Lab 01 • Scikit-Learn Classifier

Train an XGBoost/RandomForest intent classifier on customer service logs, perform cross-validation, and export the model to ONNX.

Deliverable: Low-latency intent classification endpoint.
Lab 02 • PyTorch Neural Network

Write a PyTorch training loop from scratch: build an MLP, implement cross-entropy loss, AdamW optimizer, and train on CUDA GPU.

Deliverable: Custom trained neural network with loss telemetry.
Lab 03 • Vector Embeddings & BPE

Implement Byte-Pair Encoding (BPE) subword tokenization and generate sentence embeddings to compute cosine similarity matrices.

Deliverable: Custom text vectorizer & semantic similarity engine.
Lab 04 • Mini-Transformer Attention

Implement Multi-Head Self-Attention in pure PyTorch: create Q, K, V projections, apply causal masks, and trace token attention weights.

Deliverable: Working attention mechanism running next-token prediction.