Machine Learning Fundamentals
🧠 Machine Learning Fundamentals: Tensors, PyTorch & TensorFlow
Machine Learning (ML) transforms programming from writing explicit conditional rules (if / else) into designing mathematical optimization systems that learn representations directly from data.
Whether building game agents, predictive market models, or natural language bots (like those hosted on Hugging Face), all modern deep learning is built on top of Tensors, Autograd (Automatic Differentiation), and Gradient Descent.
🏛️ The Three Pillars of Deep Learning
+-------------------------------------------------------------+
| 1. The Tensor (Multidimensional Array on GPU / VRAM) |
| - 0D Scalar -> 1D Vector -> 2D Matrix -> 3D/4D Batch |
+-------------------------------------------------------------+
│
▼
+-------------------------------------------------------------+
| 2. The Forward Pass (Model Architecture & Activations) |
| - Linear Layers: y = W * x + b |
| - Non-linearities: ReLU, GELU, Sigmoid, Softmax |
+-------------------------------------------------------------+
│
▼
+-------------------------------------------------------------+
| 3. The Backward Pass & Optimization (Loss -> Gradients) |
| - Compute Loss (MSE / Cross-Entropy) |
| - Backpropagation: dLoss/dW via Chain Rule |
| - Optimizer Step: W = W - lr * dLoss/dW (Adam / SGD) |
+-------------------------------------------------------------+
🔢 1. What is a Tensor?
A Tensor is a generalized multi-dimensional array with native GPU acceleration support. Coming from graphics APIs like Vulkan or low-level systems in Odin:
Rank 0: Scalar (e.g.loss = 0.42)Rank 1: Vector (e.g.coordinates or a 1D audio sample buffer) Rank 2: Matrix (e.g. tabular stock market features:[timestamp, open, high, low, close, volume])Rank 3: 3D Tensor (e.g. sequence of time-series tokens[batch_size, sequence_length, feature_dim])Rank 4: 4D Tensor (e.g. image batches in computer vision:[batch_size, channels, height, width])
⚔️ 2. PyTorch vs. TensorFlow: The Developer Comparison
| Feature | PyTorch (torch) | TensorFlow / Keras (tf) |
|---|---|---|
| Execution Paradigm | Dynamic Computation Graph (Eager execution): Code runs line by line like standard Python; trivial to debug with print() and standard debuggers. | Static Graph (Graph compilation): Compiles models with @tf.function / XLA for fixed production deployments. |
| Research & Community | The gold standard for Hugging Face, research papers, and game AI labs. | Widely used in enterprise production, Android/TFLite mobile, and web (TF.js). |
| Mental Model | Subclass nn.Module, override forward(). | Subclass tf.keras.Model or assemble with Sequential(). |
| GPU Acceleration | tensor.to("cuda") | Automatic GPU device placement. |
⚡ 3. Anatomy of a Minimal PyTorch Model
Here is the fundamental training loop used to fit any model to numerical data:
import torch
import torch.nn as nn
import torch.optim as optim
# 1. Define Model Architecture
class SimpleNet(nn.Module):
def __init__(self, input_dim: int, hidden_dim: int, output_dim: int):
super().__init__()
self.net = nn.Sequential(
nn.Linear(input_dim, hidden_dim),
nn.ReLU(), # Non-linear activation
nn.Linear(hidden_dim, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, output_dim) # Raw logits or regression values
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.net(x)
# 2. Setup Device & Instantiation
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = SimpleNet(input_dim=10, hidden_dim=64, output_dim=1).to(device)
# 3. Loss Function & Optimizer
criterion = nn.MSELoss() # Mean Squared Error for regression
optimizer = optim.Adam(model.parameters(), lr=1e-3)
# 4. Training Step (The Core Loop)
def train_step(batch_x: torch.Tensor, batch_y: torch.Tensor) -> float:
model.train()
optimizer.zero_grad() # 1. Clear stale gradients
predictions = model(batch_x) # 2. Forward pass
loss = criterion(predictions, batch_y) # 3. Compute loss
loss.backward() # 4. Backward pass (Autograd compute dLoss/dW)
optimizer.step() # 5. Update weights
return loss.item()
🤗 4. The Hugging Face Ecosystem & Pretrained Models
In modern machine learning, you rarely train large foundation models from scratch. Instead, you use the Hugging Face Hub:
transformers: Library to download, run, and fine-tune state-of-the-art pretrained transformer models (BERT, Llama, Whisper, Vision Transformers).diffusers: Library for image and audio generation models (Stable Diffusion).datasets: Library for streaming terabytes of community training data.timm(PyTorch Image Models): Pretrained computer vision backbones.onnxruntime: Tool to export trained PyTorch models to.onnxbinaries and run inference with low latency inside C++, Godot GDExtension, or Unreal Engine without requiring a Python runtime.
🔗 Related Notes
- Reinforcement Learning & Game AI — Deep Q-Networks (DQN), PPO, and training agents for game environments.
- Time-Series & Market Prediction Models — LSTM, GRU, Transformers, and feature engineering for financial and market data.
- ONNX & Engine Inference (Unreal & Godot) — Exporting PyTorch models to run in real-time game engines.
- Machine Learning Hub — Master directory for deep learning and AI architectures.
- Game Development Hub — Central game development index.