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:


⚔️ 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: