Thanks to visit codestin.com
Credit goes to Github.com

Skip to content
/ mlx-101 Public

๐ŸŽ Complete MLX tutorial for Apple Silicon - From zero to neural networks with Python & Swift examples

Notifications You must be signed in to change notification settings

suh4s/mlx-101

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

10 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐ŸŽ MLX Tutorial Project

Apple's Machine Learning Framework for Apple Silicon - Made Simple

This project is your complete guide to MLX, Apple's blazing-fast machine learning framework optimized for Apple Silicon. From zero to neural networks in minutes!

๐ŸŽฏ TL;DR - Get Started in 60 Seconds

# Jump in and see MLX magic
cd mlx-101
source mlx-env/bin/activate
python mlx_demo.py        # ๐Ÿš€ See MLX in action!

What just happened? You just ran machine learning operations on Apple Silicon GPU using unified memory! ๐Ÿคฏ

โœจ What You'll Get

๐ŸŽฏ Hands-on Examples - Working code for arrays, neural networks, and computer vision
๐Ÿš€ Apple Silicon Power - Harness the full potential of M1/M2/M3+ chips
๐Ÿ Python & Swift - Learn both language interfaces
๐Ÿง  Real Neural Networks - Build and train models from scratch
๐Ÿ“Š Interactive Learning - Jupyter notebooks ready to go
๐Ÿ”ง Modern Setup - Fast dependency management with uv

๐Ÿ”ฅ Features

๐ŸŽฏ Feature โœ… Status ๐Ÿ“ Description
Python Examples โœ… Working Complete tutorials from basics to neural networks
Swift Integration โœ… Ready Type-safe ML with Swift + MLX
Neural Networks โœ… Implemented Build networks from scratch
Computer Vision โœ… Examples Image processing and CNN basics
Jupyter Support โœ… Configured Interactive development environment
Fast Dependencies โœ… Using uv Lightning-fast package management
Apple Silicon โœ… Optimized Native Metal Performance Shaders

About MLX

MLX is an array framework for machine learning research on Apple Silicon. It's designed to be user-friendly, efficient, and flexible, with a Python API that closely follows NumPy and a C++ API. MLX is particularly optimized for Apple Silicon (M1, M2, M3+ chips) and provides unified memory that allows arrays to live in shared memory accessible to both CPU and GPU.

System Requirements

  • Hardware: Apple Silicon Mac (M1, M2, M3+)
  • OS: macOS 13.5+ (macOS 14+ recommended)
  • Python: 3.9+ (native arm64, not x86 via Rosetta)
  • Swift: 5.7+ (for Swift examples)

Project Structure

mlx-101/
โ”œโ”€โ”€ README.md                 # This file
โ”œโ”€โ”€ pyproject.toml           # Project configuration and dependencies
โ”œโ”€โ”€ requirements.txt         # Frozen dependency versions
โ”œโ”€โ”€ .gitignore              # Git ignore rules
โ”œโ”€โ”€ examples/               # Python examples
โ”‚   โ”œโ”€โ”€ 01_basic_operations.py
โ”‚   โ”œโ”€โ”€ 02_linear_algebra.py
โ”‚   โ”œโ”€โ”€ 03_neural_networks.py
โ”‚   โ””โ”€โ”€ 04_image_processing.py
โ”œโ”€โ”€ swift-examples/         # Swift examples (coming soon)
โ””โ”€โ”€ notebooks/              # Jupyter notebooks

Installation & Setup

1. Clone and Navigate

# Clone the repository
git clone https://github.com/suh4s/mlx-101.git
cd mlx-101

2. Create Virtual Environment

# Create isolated environment using uv (faster than pip)
uv venv mlx-env

# Activate the environment
source mlx-env/bin/activate

3. Install Dependencies

# Install MLX and related packages
uv pip install mlx numpy matplotlib jupyter pillow

# Or install from requirements.txt
uv pip install -r requirements.txt

4. Verify Installation

python -c "import mlx.core as mx; print(f'MLX version: {mx.__version__}'); print('MLX is working!')"

5. Environment Management

# Activate environment (run this each time you start)
source mlx-env/bin/activate

# Deactivate when done
deactivate

# Install new packages
uv pip install package_name

# Update requirements after installing new packages
uv pip freeze > requirements.txt

๐Ÿš€ Quick Start

Ready to dive in? Here's your fast track to MLX awesomeness:

# 1. Jump into your environment
cd mlx-101
source mlx-env/bin/activate

# 2. See MLX in action (30 seconds)
python mlx_demo.py

# 3. Explore detailed examples
python examples/01_basic_operations.py

# 4. Start experimenting
jupyter lab

๐ŸŽฎ Usage & Examples

๐Ÿƒโ€โ™‚๏ธ Daily Workflow

# Start every session
source mlx-env/bin/activate

# Run examples
python examples/01_basic_operations.py    # ๐ŸŽฏ Arrays & basics
python examples/03_neural_networks.py     # ๐Ÿง  Neural networks
python mlx_demo.py                        # โšก Quick overview

# Interactive development
jupyter lab                               # ๐ŸŽช Modern interface
jupyter notebook                          # ๐Ÿ“Š Classic interface

# When finished
deactivate

๐Ÿ“ฆ Managing Dependencies

# Install new packages (fast with uv!)
uv pip install transformers torch

# Keep track of dependencies
uv pip freeze > requirements.txt

# Reproduce environment elsewhere
uv pip install -r requirements.txt

๐ŸŽฏ Learning Path & File Guide

Step File What You'll Learn Key Concepts
1๏ธโƒฃ mlx_demo.py Quick MLX overview Basic arrays, GPU acceleration
2๏ธโƒฃ 01_basic_operations.py Arrays, math, NumPy interop Array creation, indexing, broadcasting
3๏ธโƒฃ 02_linear_algebra.py Matrix operations & linear systems Matrix math, decompositions, solving equations
4๏ธโƒฃ 03_neural_networks.py Neural networks from scratch Activations, loss functions, gradients
5๏ธโƒฃ 04_image_processing.py Computer vision basics Convolutions, CNNs, image transforms
6๏ธโƒฃ 05_langgraph_mlx_guide.py AI agents with LangGraph + MLX Agent workflows, local LLMs, tool integration
7๏ธโƒฃ working_examples.py Curated robust operations Production-ready MLX patterns
8๏ธโƒฃ notebooks/ Interactive experimentation Jupyter development workflow
9๏ธโƒฃ swift-examples/ Swift + MLX integration Type-safe ML with Swift

๐Ÿ“š Detailed File Breakdown

๐Ÿš€ mlx_demo.py - Your MLX Introduction

# What you'll see in 30 seconds:
โ€ข MLX vs NumPy speed comparison
โ€ข GPU acceleration in action  
โ€ข Unified memory demonstration
โ€ข Basic neural network forward pass

๐Ÿงฎ 01_basic_operations.py - MLX Fundamentals

# Core concepts covered:
โ€ข Array creation (zeros, ones, random, linspace)
โ€ข Mathematical operations (+, -, *, /, power)
โ€ข Array indexing and slicing
โ€ข Broadcasting rules and examples
โ€ข MLX โ†” NumPy interoperability
โ€ข Memory model and device management

๐Ÿ”ข 02_linear_algebra.py - Mathematical Powerhouse

# Advanced math operations:
โ€ข Matrix multiplication and transposes
โ€ข Linear system solving (Ax = b)
โ€ข Matrix decompositions (QR, SVD)
โ€ข Vector operations and norms
โ€ข Geometric transformations
โ€ข CPU stream usage for unsupported GPU ops

๐Ÿง  03_neural_networks.py - ML Building Blocks

# Neural network essentials:
โ€ข Activation functions (ReLU, Sigmoid, Tanh)
โ€ข Loss functions (MSE, Cross-entropy, MAE)
โ€ข Gradient computation and backpropagation
โ€ข Simple linear regression training
โ€ข Multi-layer perceptron (MLP) example
โ€ข Best practices for neural network training

๐Ÿ“ธ 04_image_processing.py - Computer Vision

# Computer vision fundamentals:
โ€ข Image creation and manipulation
โ€ข Convolution operations and kernels
โ€ข CNN building blocks (Conv2D, ReLU, MaxPool)
โ€ข Image transformations (flip, rotate, resize)
โ€ข Color space operations (RGB โ†” Grayscale)
โ€ข Hybrid MLX-NumPy techniques for complex ops

๐Ÿค– 05_langgraph_mlx_guide.py - AI Agent Integration

# Building intelligent agents with LangGraph + MLX:
โ€ข Agent workflow orchestration with LangGraph
โ€ข Local LLM inference with MLX-LM
โ€ข MLX-powered mathematical reasoning tools
โ€ข Computer vision capabilities for agents
โ€ข Privacy-first, Apple Silicon-optimized AI workflows
โ€ข Real-world use cases and performance benefits

โœ… working_examples.py - Production-Ready Code

# Curated examples that always work:
โ€ข Robust linear algebra operations
โ€ข Reliable image processing patterns
โ€ข Neural network components
โ€ข Performance benchmarks
โ€ข Best practices for real applications

๐ŸŽฏ Key Takeaways from This Repository

๐Ÿง  What You've Learned

After working through this repository, you now understand:

๐ŸŽ MLX Fundamentals

  • Unified Memory Architecture: CPU and GPU share the same memory space - no costly transfers!
  • Lazy Evaluation: Operations are automatically fused for maximum efficiency
  • Apple Silicon Optimization: Native Metal Performance Shaders provide blazing speed
  • NumPy Compatibility: Easy migration path from existing NumPy-based workflows

๐Ÿ”ง Technical Mastery

  • Array Operations: Creation, indexing, slicing, and broadcasting in MLX
  • Linear Algebra: Matrix operations, decompositions, and solving linear systems
  • Neural Networks: Building networks from scratch with proper gradients
  • Computer Vision: Image processing, convolutions, and CNN architectures
  • Performance Optimization: When to use CPU vs GPU streams for different operations

๐Ÿš€ Production-Ready Skills

  • Environment Management: Isolated development with uv and virtual environments
  • Dependency Tracking: Proper pyproject.toml and requirements.txt management
  • Error Handling: Graceful fallbacks for GPU-unsupported operations
  • Hybrid Approaches: Combining MLX with NumPy for complex operations
  • Best Practices: Code patterns that work reliably across different MLX versions

๐Ÿ”ฌ Key Discoveries & Fixes Made

During the development of this repository, we encountered and solved several important MLX compatibility issues:

๐Ÿ”ง GPU/CPU Stream Issues

  • Problem: Some linear algebra operations (mx.linalg.inv, mx.linalg.qr, mx.linalg.solve) not yet supported on GPU
  • Solution: Use CPU streams with proper evaluation: with mx.stream(mx.cpu): result = operation(); mx.eval(result)
  • Impact: All linear algebra examples now work reliably across MLX versions

๐Ÿ“ Array Assignment Limitations

  • Problem: MLX's .at[].set() method causing 'ArrayAt' object has no attribute 'set' errors
  • Solution: Hybrid approach using NumPy for complex assignments, converting back to MLX
  • Impact: Image processing operations like max pooling and resizing now work perfectly

๐Ÿ”„ Missing Operations

  • Problem: Operations like mx.rot90() don't exist in current MLX versions
  • Solution: Use NumPy equivalents and convert: mx.array(np.rot90(np.array(mlx_array)))
  • Impact: All image transformation examples work seamlessly

โšก Performance Optimizations Discovered

  • Unified Memory: True zero-copy between CPU and GPU operations
  • Lazy Evaluation: Operations are automatically fused for better performance
  • Broadcasting: MLX's broadcasting rules closely follow NumPy for familiar behavior
  • Vectorization: Always prefer vectorized operations over Python loops

๐ŸŽ“ Critical Insights Discovered

โšก Performance Insights

# โœ… MLX Strengths: Fast unified memory operations
result = mlx_array @ other_array  # GPU-accelerated, no memory transfers

# โš ๏ธ MLX Limitations: Some linalg ops need CPU streams
with mx.stream(mx.cpu):
    inv_matrix = mx.linalg.inv(matrix)  # Fallback to CPU when needed

๐Ÿ”„ Compatibility Patterns

# โœ… Hybrid MLX-NumPy approach for complex operations
mlx_data = mx.array(input_data)      # Use MLX for computation
numpy_data = np.array(mlx_data)      # Convert for complex assignments
result = mx.array(processed_numpy)   # Back to MLX for further processing

๐Ÿงฎ Development Workflow

  1. Start Simple: Use working_examples.py for guaranteed-working patterns
  2. Understand Limitations: Know when to use CPU streams vs GPU
  3. Leverage Strengths: Use MLX for heavy computation, NumPy for complex indexing
  4. Test Incrementally: Build up from basic operations to complex models

๐Ÿ”‘ Essential Patterns You've Mastered

๐ŸŽฏ Robust MLX Code

# Always handle GPU/CPU compatibility
try:
    result = mx.linalg.solve(A, b)  # Try GPU first
except:
    with mx.stream(mx.cpu):         # Fallback to CPU
        result = mx.linalg.solve(A, b)
        mx.eval(result)

๐Ÿ“Š Efficient Data Processing

# Leverage broadcasting and vectorization
processed = (data - mean) / std     # Vectorized normalization
result = mx.sum(processed * weights, axis=1)  # Efficient reductions

๐Ÿง  Neural Network Building

# Clean, extensible neural network patterns
def layer_forward(x, weights, bias):
    return mx.maximum(0, x @ weights + bias)  # ReLU activation

# Gradient-ready operations
loss = mx.mean((predictions - targets) ** 2)  # MSE loss

๐Ÿš€ What Makes You MLX-Ready Now

โœ… Environment Mastery: Professional development setup with uv and virtual environments
โœ… Core Understanding: Deep knowledge of MLX's unified memory and lazy evaluation
โœ… Practical Skills: Real examples that work across different MLX versions
โœ… Performance Awareness: Know when to use GPU vs CPU streams
โœ… Production Patterns: Robust code that handles edge cases gracefully
โœ… Multi-Language Ready: Both Python and Swift MLX interfaces understood
โœ… Computer Vision Capable: Image processing and CNN implementation skills
โœ… Debugging Skills: Can identify and fix common MLX compatibility issues

You're now equipped to build serious machine learning applications on Apple Silicon! ๐ŸŽ‰

๐Ÿ”ฅ Why This Setup Rocks

MLX Advantages

  • ๐ŸŽ Apple Silicon Optimized: Native Metal Performance Shaders for maximum performance
  • ๐Ÿง  Unified Memory: CPU and GPU share memory seamlessly - no transfers needed!
  • โšก Lazy Evaluation: Operations are fused automatically for efficiency
  • ๐Ÿ NumPy Compatible: Easy migration from existing NumPy code
  • ๐ŸฆŽ Swift Native: Type-safe, performant Swift integration
  • ๐Ÿ”ง Auto Differentiation: Ready for gradient-based learning out of the box

Your Environment Advantages

  • ๐Ÿš€ Fast Package Management: Using uv instead of slow pip
  • ๐Ÿ”’ Isolated Environment: No conflicts with system Python packages
  • ๐Ÿ“Š Rich Examples: Working code you can learn from immediately
  • ๐ŸŽฏ Multi-language: Both Python and Swift ready to go
  • ๐Ÿ“ Comprehensive Docs: Everything documented and explained
  • ๐ŸŽช Jupyter Ready: Interactive development environment set up

๐Ÿ’ก Pro Tips

๐Ÿƒโ€โ™‚๏ธ Performance Tips

# โœ… Good - Vectorized operations
result = a * 2 + b

# โŒ Avoid - Python loops
result = [a[i] * 2 + b[i] for i in range(len(a))]

๐Ÿ› ๏ธ Development Workflow

  • Always activate: source mlx-env/bin/activate before starting
  • Quick test: Run python mlx_demo.py to verify everything works
  • Interactive dev: Use jupyter lab for experimentation
  • Keep updated: uv pip freeze > requirements.txt after installing packages

๐ŸŽฏ Learning Strategy

  1. Start simple: Begin with 01_basic_operations.py
  2. Understand by doing: Modify examples and see what happens
  3. Read the outputs: Examples are heavily commented for learning
  4. Build incrementally: Start with arrays, then move to neural networks

๐Ÿš€ MLX Specific Tips

  • MLX arrays live in unified memory - accessible by both CPU and GPU
  • Use mx.array() instead of np.array() for MLX operations
  • Leverage broadcasting for element-wise operations
  • Take advantage of lazy evaluation - operations are fused when possible
  • Convert between MLX and NumPy easily: np.array(mlx_array)

๐Ÿ“š Resources

About

๐ŸŽ Complete MLX tutorial for Apple Silicon - From zero to neural networks with Python & Swift examples

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published