Skip to content

sonald/sad

Repository files navigation

SAD - Sian's Auto-Differentiation

Python NumPy CuPy pytest uv

SAD (Sian's Auto-Differentiation) 是一个纯 Python 实现的深度学习框架,具备自动微分功能。它类似于 PyTorch,但完全从零开始构建,支持 CPU(NumPy)和 GPU(CuPy)计算,采用动态计算图。

✨ 核心特性

  • 🔥 自动微分: 动态计算图,支持高阶梯度
  • 🚀 GPU 加速: 通过 CuPy 实现透明的 GPU 计算
  • 🧠 神经网络: 完整的神经网络层和模型实现
  • 📊 可视化: 计算图可视化功能
  • 🎯 预训练模型: VGG16 等经典模型架构
  • 🔧 优化器: SGD、Momentum 等优化算法
  • 🏗️ 模块化设计: 清晰的层次结构和接口

🏗️ 架构概览

sad/
├── core.py        # 核心:Variable、Function、自动微分引擎
├── functions.py   # 数学运算:激活函数、张量操作、卷积等
├── layers.py      # 神经网络层:Linear、Conv2d、Dropout 等
├── models.py      # 预构建模型:Sequential、MLP、VGG16
├── optimizers.py  # 优化器:SGD、Momentum
├── datasets.py    # 数据集工具和常用数据集
├── cuda.py        # GPU 加速工具(CuPy 集成)
└── utils.py       # 可视化和实用工具

🚀 快速开始

安装依赖

本项目使用 uv 进行包管理,提供快速可靠的依赖解析:

# 安装 uv(如果尚未安装)
pip install uv

# 安装基础依赖
uv sync

# 安装 GPU 支持
uv sync --extra gpu

# 安装开发工具
uv sync --extra dev

# 安装数据集工具
uv sync --extra datasets

# 或者使用传统 pip(不推荐)
pip install numpy>=1.21.0 matplotlib>=3.5.0 pillow>=9.0.0

基本用法

import sad
from sad.core import Variable, with_grad
import sad.functions as F
import numpy as np

# 创建变量并启用梯度计算
with with_grad(True):
    x = Variable(np.array([1.0, 2.0, 3.0]), requires_grad=True)
    y = F.sum(x ** 2)
    y.backward()
    print(f"x.grad: {x.grad.data}")  # [2.0, 4.0, 6.0]

# 快速验证安装
uv run python demo.py

线性回归示例

import numpy as np
from sad.core import Variable, with_grad
import sad.functions as F

# 生成数据
np.random.seed(42)
xs = Variable(np.random.randn(100, 1))
ys = Variable(5 + xs.data * 2 + np.random.randn(100, 1) * 0.1)

# 定义参数
W = Variable(np.ones((1, 1)))
b = Variable(np.zeros(1))

# 定义模型
def predict(x):
    return F.matmul(x, W) + b

# 训练
lr = 0.01
with with_grad(True):
    for i in range(1000):
        y_pred = predict(xs)
        loss = F.mean_squared_error(y_pred, ys)
        
        W.cleargrad()
        b.cleargrad()
        loss.backward()
        
        W.data -= lr * W.grad.data
        b.data -= lr * b.grad.data
        
        if i % 100 == 0:
            print(f"Step {i}: loss = {loss.data:.4f}")

print(f"最终参数: W = {W.data[0,0]:.3f}, b = {b.data[0]:.3f}")

神经网络示例

from sad.models import Sequential
from sad.layers import Linear
from sad.optimizers import SGD
import sad.functions as F

# 定义网络
model = Sequential(
    Linear(10, in_size=1),
    Linear(1)
)

# 定义优化器
optimizer = SGD(model.params(), lr=0.01)

# 训练循环
with with_grad(True):
    for epoch in range(100):
        # 前向传播
        y_pred = model(x)
        loss = F.mean_squared_error(y_pred, y_true)
        
        # 反向传播
        model.cleargrads()
        loss.backward()
        
        # 参数更新
        optimizer.step()

卷积神经网络

from sad.models import Sequential
from sad.layers import Conv2d, Linear, Pooling
import sad.functions as F

# 定义 CNN
model = Sequential(
    Conv2d(32, kernel_size=3, stride=1, padding=1),
    F.relu,
    Pooling(kernel_size=2, stride=2),
    Conv2d(64, kernel_size=3, stride=1, padding=1), 
    F.relu,
    Pooling(kernel_size=2, stride=2),
    Linear(128),
    F.relu,
    Linear(10)  # 10 类分类
)

# 训练...

🎨 高级功能

GPU 加速

# 自动检测并使用 GPU
x = Variable(np.random.randn(1000, 1000))
x.to_gpu()  # 转移到 GPU
y = F.matmul(x, x)  # GPU 上的矩阵乘法
y.to_cpu()  # 转回 CPU

计算图可视化

from sad.utils import plot_dot_graph

with with_grad(True):
    x = Variable(np.array([2.0]), name='x')
    y = x ** 3 + x
    y.name = 'y'
    
    # 生成计算图
    plot_dot_graph(y, to_file='computation_graph.png')

高阶梯度

with with_grad(True):
    x = Variable(np.array([2.0]))
    y = x ** 3
    
    y.backward(create_graph=True)
    dx = x.grad  # 一阶导数
    
    x.cleargrad()
    dx.backward()
    ddx = x.grad  # 二阶导数

模型保存和加载

# 保存模型参数
model.save_params('model_weights.npz')

# 加载模型参数
model.load_params('model_weights.npz')

# VGG16 预训练模型
from sad.models import VGG16
vgg = VGG16.from_pretrained('vgg16_weights.npz')

📊 示例项目

1. 函数拟合

使用多层感知机拟合 sin 函数:

import numpy as np
from sad.models import MLP
import sad.functions as F

# 生成数据
x = np.random.rand(100, 1)
y = np.sin(2 * np.pi * x) + 0.1 * np.random.randn(100, 1)

# 定义模型
model = MLP([1, 10, 10, 1], activation=F.tanh)

# 训练...(见 tst_sad.ipynb)

2. 图像分类

使用 VGG16 进行图像分类:

from sad.models import VGG16
from PIL import Image
import numpy as np

# 加载预训练模型
model = VGG16.from_pretrained('vgg16.npz')

# 预处理图像
image = Image.open('image.jpg')
x = VGG16.preprocess(image)
x = Variable(x[None, ...])  # 添加 batch 维度

# 预测
with with_grad(False):
    y = model(x)
    pred = F.softmax(y)

🧪 测试

本项目包含 13 个全面的测试模块,覆盖所有核心功能:

# 使用 uv 运行所有测试(推荐)
uv run python -m pytest tests/

# 运行所有测试(传统方式)
python -m pytest tests/ -v

# 运行特定测试模块
python -m pytest tests/test_sad.py -v
python -m pytest tests/test_core_enhanced.py -v

# 运行测试并查看覆盖率
python -m pytest --cov=sad tests/

# 运行特定功能测试
python -m pytest tests/test_functions_complete.py -v  # 数学函数测试
python -m pytest tests/test_layers_complete.py -v    # 神经网络层测试
python -m pytest tests/test_models_complete.py -v    # 模型测试
python -m pytest tests/test_cuda_integration.py -v   # GPU 测试(需要 CuPy)

# 运行单个测试
python -m pytest tests/test_sad.py::TestForwardOperations::test_square_forward

测试覆盖范围

  • 核心测试: 自动微分、基本运算、Variable 操作
  • 函数测试: 三角函数、激活函数、张量操作、卷积运算
  • 层测试: Linear、Conv2d、Dropout、池化层
  • 模型测试: Sequential、MLP、VGG16 架构
  • 优化器测试: SGD、Momentum 算法
  • GPU 测试: CPU/GPU 操作一致性验证
  • 边界测试: 异常情况和边界条件处理

📚 核心概念

Variable(变量)

# 创建变量
x = Variable(data, name='x', requires_grad=True)

# 属性
x.data          # 实际数据(NumPy/CuPy 数组)
x.grad          # 梯度
x.shape         # 形状
x.requires_grad # 是否需要梯度

Function(函数)

class MyFunction(Function):
    def forward(self, x):
        # 前向计算
        return result
    
    def backward(self, grad):
        # 反向传播
        return input_grad

Context Managers(上下文管理器)

# 启用/禁用梯度计算
with with_grad(True):
    # 在此块中启用梯度计算
    pass

# 训练/评估模式
with train_mode(True):
    # 训练模式(影响 Dropout 等)
    pass

🔧 架构设计

核心设计模式

  1. 延迟初始化: 神经网络层在首次使用时才初始化权重,支持灵活的输入形状
  2. 弱引用: 计算图使用弱引用防止内存泄漏,自动清理不再使用的节点
  3. 广播机制: 自动处理张量形状不匹配,支持类似 NumPy 的广播规则
  4. 世代排序: 基于世代的拓扑排序确保正确的梯度流向和计算顺序
  5. 上下文管理: 全局配置管理器控制梯度计算和训练模式

技术特性

  • 动态计算图: 支持动态网络结构和控制流
  • 高阶梯度: 支持计算二阶及更高阶导数
  • CPU/GPU 透明切换: 统一的接口,自动检测和使用 GPU 加速
  • 模块化架构: 清晰的组件分离,便于扩展和维护
  • 类型安全: 支持 NumPy 和 CuPy 数组类型的自动检测

性能优化

  • 内存效率: 智能的内存管理和垃圾回收
  • 计算优化: 避免不必要的拷贝和内存分配
  • 并行计算: 利用 NumPy/CuPy 的向量化操作
  • 缓存机制: 智能缓存中间结果减少重复计算

📂 项目结构

sad/
├── pyproject.toml      # 项目配置和依赖管理(uv)
├── demo.py             # 快速演示脚本
├── tst_sad.ipynb       # Jupyter 实验笔记本
├── sad/                # 核心框架代码
│   ├── __init__.py     # 模块导入配置
│   ├── core.py         # 核心:Variable、Function、自动微分引擎
│   ├── functions.py    # 数学函数:三角、激活、张量操作、卷积
│   ├── layers.py       # 神经网络层:Linear、Conv2d、Dropout、Pooling
│   ├── models.py       # 预构建模型:Sequential、MLP、VGG16
│   ├── optimizers.py   # 优化器:SGD、Momentum(支持钩子函数)
│   ├── datasets.py     # 数据集工具:下载、缓存、预处理、变换
│   ├── cuda.py         # GPU 加速:CuPy 集成和后端抽象
│   └── utils.py        # 实用工具:可视化、计算图绘制
└── tests/              # 完整测试套件(13 个模块)
    ├── test_sad.py             # 基础功能测试
    ├── test_core_enhanced.py   # 核心功能增强测试
    ├── test_functions_complete.py  # 数学函数完整测试
    ├── test_layers_complete.py     # 神经网络层测试
    ├── test_models_complete.py     # 模型架构测试
    ├── test_optimizers.py          # 优化器测试
    ├── test_cuda_integration.py    # GPU 集成测试
    ├── test_datasets.py            # 数据集工具测试
    ├── test_utils.py               # 实用工具测试
    ├── test_edge_cases.py          # 边界情况测试
    ├── test_performance.py         # 性能测试
    ├── test_regressions.py         # 回归测试
    └── vgg16.npz                   # VGG16 预训练权重

🤝 贡献

欢迎提交 Issue 和 Pull Request!开发前请运行完整测试套件确保代码质量:

# 运行完整测试
uv run python -m pytest tests/ --cov=sad

# 运行代码质量检查(如果配置)
uv run python -m pytest tests/ -v --cov=sad --cov-report=html

📄 许可证

MIT License

🙏 致谢

本项目受到以下项目启发:


注意: 这是一个教育性质的深度学习框架,主要用于学习自动微分和深度学习的底层原理。对于生产环境,建议使用成熟的框架如 PyTorch 或 TensorFlow。

About

sonald's stupid automatic differentiation

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published