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.
02. AI / ML Foundation Roadmap
How statistical data transforms through neural representations into modern Transformer foundation models.
- Supervised ML
- Unsupervised ML
- Features
- Evaluation
- Model Serving
- Neural Networks
- Backpropagation
- Optimizers
- PyTorch
- GPU Basics
- Tokenization ✓
- Embeddings ✓
- Attention ✓
- NLP Basics ✓
Data
to
Intelligence
•••
- Self Attention ✓
- Multi-Head Attention ✓
- Positional Encoding ✓
- Encoder / Decoder ✓
- Pretraining ✓
- Fine-Tuning ✓
- Inference ✓
Real AI
Systems
⇒ LLM
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.
Classical Machine Learning (ML) & MLOps
Core Statistical ML
- 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
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")
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.
Deep Learning & PyTorch Framework
Neural Networks
- 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
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()
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.
NLP, Tokenization & Vector Embeddings
Language Vectors
- 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
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
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.
The Transformer Architecture (Attention is All You Need)
Foundation Architecture
- 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
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
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.
4. Hands-On Labs in This Module
Four applied coding labs built in Python, PyTorch, and Scikit-Learn.
Train an XGBoost/RandomForest intent classifier on customer service logs, perform cross-validation, and export the model to ONNX.
Write a PyTorch training loop from scratch: build an MLP, implement cross-entropy loss, AdamW optimizer, and train on CUDA GPU.
Implement Byte-Pair Encoding (BPE) subword tokenization and generate sentence embeddings to compute cosine similarity matrices.
Implement Multi-Head Self-Attention in pure PyTorch: create Q, K, V projections, apply causal masks, and trace token attention weights.