9.0
重磅
AI SCORE
开源项目2025-09-15 17:47
用 Rust 从头实现 Transformer 模型
Hacker News · github.com#Rust#LLM
Editor brief · 编辑速览
开源项目 RustGPT 用纯 Rust 实现完整的 Transformer LLM,兼具学习 AI 原理和系统编程的价值。
开源项目 RustGPT 用纯 Rust 实现完整的 Transformer LLM,兼具学习 AI 原理和系统编程的价值。
纯 Rust 编写,无外部 ML 框架依赖。从零开始构建,仅使用 ndarray 进行矩阵运算。
本项目演示了如何用 Rust 从零开始构建基于 transformer 的语言模型,包括:
这不是生产级 LLM,与大型模型相差甚远。
这只是一个演示这些模型内部工作原理的玩具项目。
从这两个核心文件开始了解实现:
src/main.rs - 训练管道、数据准备和交互模式
src/llm.rs - 核心 LLM 实现,包含前向/反向传播和训练逻辑
该模型使用基于 transformer 的架构,包含以下组件:
Input Text → Tokenization → Embeddings → Transformer Blocks → Output Projection → Predictions
src/
├── main.rs # 🎯 Training pipeline and interactive mode
├── llm.rs # 🧠 Core LLM implementation and training logic
├── lib.rs # 📚 Library exports and constants
├── transformer.rs # 🔄 Transformer block (attention + feed-forward)
├── self_attention.rs # 👀 Multi-head self-attention mechanism
├── feed_forward.rs # ⚡ Position-wise feed-forward networks
├── embeddings.rs # 📊 Token embedding layer
├── output_projection.rs # 🎰 Final linear layer for vocabulary predictions
├── vocab.rs # 📝 Vocabulary management and tokenization
├── layer_norm.rs # 🧮 Layer normalization
└── adam.rs # 🏃 Adam optimizer implementation
tests/
├── llm_test.rs # Tests for core LLM functionality
├── transformer_test.rs # Tests for transformer blocks
├── self_attention_test.rs # Tests for attention mechanisms
├── feed_forward_test.rs # Tests for feed-forward layers
├── embeddings_test.rs # Tests for embedding layers
├── vocab_test.rs # Tests for vocabulary handling
├── adam_test.rs # Tests for optimizer
└── output_projection_test.rs # Tests for output layer
实现包括两个训练阶段:
预训练:从事实陈述中学习基本世界知识
指令微调:学习对话模式
# Clone and run
git clone https://github.com/tekaratzas/RustGPT.git
cd RustGPT
cargo run
# The model will:
# 1. Build vocabulary from training data
# 2. Pre-train on factual statements (100 epochs)
# 3. Instruction-tune on conversational data (100 epochs)
# 4. Enter interactive mode for testing
训练后,以交互方式测试模型:
Enter prompt: How do mountains form?
Model output: Mountains are formed through tectonic forces or volcanism over long geological time periods
Enter prompt: What causes rain?
Model output: Rain is caused by water vapor in clouds condensing into droplets that become too heavy to remain airborne
# Run all tests
cargo test
# Test specific components
cargo test --test llm_test
cargo test --test transformer_test
cargo test --test self_attention_test
# Build optimized version
cargo build --release
# Run with verbose output
cargo test -- --nocapture
本实现演示了关键的 ML 概念:
依赖项:
欢迎贡献!本项目非常适合学习和实验。
git checkout -b feature/model-persistencecargo test有问题?开启一个 issue 或开始讨论!
没有 PyTorch、TensorFlow 或 Candle - 只有纯 Rust 和线性代数!