Skip to content

Commit 6bc7e01

Browse files
authored
Merge pull request #3 from SyntaxSpirits/feature/complete-training-system
feat: Implement complete LSTM training system
2 parents d0dab7f + fca096f commit 6bc7e01

15 files changed

Lines changed: 1481 additions & 26 deletions

.gitignore

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,28 @@
1+
# Rust build artifacts
12
/target/
3+
**/*.rs.bk
4+
Cargo.lock
5+
6+
# IDE files
27
.vscode/
8+
.idea/
39

4-
Cargo.lock
10+
# OS generated files
11+
.DS_Store
12+
.DS_Store?
13+
._*
14+
.Spotlight-V100
15+
.Trashes
16+
ehthumbs.db
17+
Thumbs.db
18+
19+
# Temporary files
20+
*~
21+
*.tmp
22+
*.swp
23+
*.swo
24+
25+
# Coverage reports
26+
/target/debug/deps/*
27+
lcov.info
28+
*.profraw

CHANGELOG.md

Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
# Changelog
2+
3+
All notable changes to this project will be documented in this file.
4+
5+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7+
8+
## [0.2.0] - 2025-06-09
9+
10+
### Added
11+
- **Complete Training System**: Full backpropagation through time (BPTT) implementation
12+
- **Multiple Optimizers**: SGD, Adam, and RMSprop with configurable parameters
13+
- **Loss Functions**: MSE, MAE, and Cross-Entropy with numerically stable implementations
14+
- **Training Infrastructure**:
15+
- LSTMTrainer with configurable training loops
16+
- Gradient clipping to prevent exploding gradients
17+
- Validation support with metrics tracking
18+
- Training configuration system
19+
- **Advanced Features**:
20+
- Gradient accumulation across time steps
21+
- Parameter state management for optimizers
22+
- Comprehensive metrics tracking and history
23+
- **Enhanced Network Architecture**:
24+
- Network-level backward propagation
25+
- Multi-layer gradient computation
26+
- Sequence processing with caching
27+
- **Examples and Documentation**:
28+
- Complete training example with sine wave prediction
29+
- Optimizer comparison demonstrations
30+
- Comprehensive API documentation
31+
32+
### Changed
33+
- **LSTM Cell**: Added backward propagation with full gradient computation
34+
- **LSTM Network**: Enhanced with training capabilities and caching
35+
- **Architecture**: Restructured for better separation of concerns
36+
- **Performance**: Optimized gradient computation and memory usage
37+
38+
### Technical Details
39+
- Implemented mathematically correct BPTT algorithm
40+
- Added bias correction for Adam optimizer
41+
- Implemented numerically stable softmax function
42+
- Enhanced multi-layer gradient flow
43+
- Added proper parameter update mechanisms
44+
45+
## [0.1.0] - 2024-06-10
46+
47+
### Added
48+
- **Core LSTM Implementation**:
49+
- Basic LSTM cell with forward propagation
50+
- Standard LSTM equations implementation
51+
- Multi-layer LSTM network support
52+
- **Peephole LSTM Variant**:
53+
- Peephole connections for enhanced performance
54+
- Direct cell state to gate connections
55+
- **Basic Architecture**:
56+
- Modular design with separate layers and models
57+
- Clean separation between cell and network levels
58+
- Configurable network architecture (input size, hidden size, layers)
59+
- **Utility Functions**:
60+
- Sigmoid and tanh activation functions
61+
- Random weight initialization
62+
- **Examples**:
63+
- Basic usage demonstrations
64+
- Multi-layer network examples
65+
- Time series prediction examples
66+
- Text generation examples
67+
- Peephole LSTM usage
68+
69+
### Technical Details
70+
- Forward-pass only implementation
71+
- Xavier-uniform weight initialization
72+
- Support for variable sequence lengths
73+
- Proper hidden and cell state management
74+
75+
## Architecture Evolution
76+
77+
### Phase 1: Basic Implementation (v0.1.0)
78+
- Forward-pass only LSTM cells
79+
- Basic multi-layer networks
80+
- Simple examples and demonstrations
81+
82+
### Phase 2: Complete Training Framework (v0.2.0)
83+
- Full backward propagation (BPTT)
84+
- Multiple optimization algorithms
85+
- Comprehensive loss functions
86+
- Training infrastructure with validation
87+
- Advanced gradient management
88+
89+
### Phase 3: Documentation & Polish (Current)
90+
- Cleaned and optimized documentation
91+
- Enhanced code clarity
92+
- Comprehensive examples
93+
- Performance optimizations
94+
95+
## Future Roadmap
96+
97+
### Planned Features
98+
- **Enhanced Architectures**:
99+
- Bidirectional LSTM
100+
- GRU (Gated Recurrent Unit)
101+
- Attention mechanisms
102+
- **Performance Optimizations**:
103+
- GPU acceleration support
104+
- Batch processing capabilities
105+
- SIMD optimizations
106+
- **Advanced Training Features**:
107+
- Learning rate scheduling
108+
- Regularization techniques (dropout, weight decay)
109+
- Early stopping
110+
- **Data Handling**:
111+
- Built-in data preprocessing
112+
- Common dataset loaders
113+
- Data augmentation
114+
- **Visualization & Monitoring**:
115+
- Training progress visualization
116+
- Loss curve plotting
117+
- Model analysis tools
118+
119+
## Contributing
120+
121+
When contributing to this project, please:
122+
1. Update the CHANGELOG.md file with your changes
123+
2. Follow the established coding style
124+
3. Add tests for new functionality
125+
4. Update documentation as needed
126+
127+
## Version History Summary
128+
129+
- **v0.1.0**: Initial LSTM implementation with forward pass
130+
- **v0.2.0**: Complete training system with BPTT and optimizers
131+
- **Current**: Documentation improvements and code polish

Cargo.toml

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
[package]
22
name = "rust-lstm"
3-
version = "0.1.0"
3+
version = "0.2.0"
44
authors = ["Alex Kholodniak <alexandrkholodniak@gmail.com>"]
55
edition = "2021"
6-
description = "A Rust library for LSTM (Long Short-Term Memory) neural networks."
6+
description = "A complete LSTM neural network library with training capabilities, multiple optimizers, and peephole variants."
77
license = "MIT"
88
repository = "https://github.com/SyntaxSpirits/rust-lstm"
99
homepage = "https://github.com/SyntaxSpirits/rust-lstm"
1010
documentation = "https://docs.rs/rust-lstm"
11+
keywords = ["lstm", "neural-network", "machine-learning", "deep-learning", "rnn"]
12+
categories = ["algorithms", "science"]
1113

1214
[dependencies]
1315
ndarray = "0.15"

README.md

Lines changed: 129 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,17 @@
11
# Rust-LSTM
22

3-
A simple LSTM (Long Short-Term Memory) neural network library implemented in Rust. This library provides basic functionalities to create and train LSTM networks.
3+
A comprehensive LSTM (Long Short-Term Memory) neural network library implemented in Rust. This library provides complete functionalities to create, train, and use LSTM networks for various sequence modeling tasks.
44

55
## Features
66

7-
- LSTM cell implementation
8-
- Multi-layer LSTM network
9-
- Random initialization of weights and biases
10-
- Forward pass through the network
7+
- **LSTM cell implementation** with forward and backward propagation
8+
- **Peephole LSTM variant** for enhanced performance
9+
- **Multi-layer LSTM networks** with configurable architecture
10+
- **Complete training system** with backpropagation through time (BPTT)
11+
- **Multiple optimizers**: SGD, Adam, RMSprop
12+
- **Loss functions**: MSE, MAE, Cross-entropy with softmax
13+
- **Training utilities**: gradient clipping, validation, metrics tracking
14+
- **Random initialization** of weights and biases
1115

1216
## Getting Started
1317

@@ -32,7 +36,9 @@ cargo build
3236

3337
## Usage
3438

35-
Here's a simple example demonstrating how to use the LSTM library:
39+
### Basic Forward Pass
40+
41+
Here's a simple example demonstrating basic LSTM usage:
3642

3743
```rust
3844
use ndarray::Array2;
@@ -59,7 +65,86 @@ fn main() {
5965
// Print the output
6066
println!("Output: {:?}", output);
6167
}
68+
```
69+
70+
### Training an LSTM Network
71+
72+
Here's how to train an LSTM for time series prediction:
73+
74+
```rust
75+
use ndarray::Array2;
76+
use rust_lstm::models::lstm_network::LSTMNetwork;
77+
use rust_lstm::training::{create_basic_trainer, TrainingConfig};
78+
use rust_lstm::optimizers::Adam;
79+
use rust_lstm::loss::MSELoss;
80+
81+
fn main() {
82+
// Create network
83+
let network = LSTMNetwork::new(1, 10, 2);
84+
85+
// Setup training with Adam optimizer
86+
let loss_function = MSELoss;
87+
let optimizer = Adam::new(0.001);
88+
let mut trainer = LSTMTrainer::new(network, loss_function, optimizer);
89+
90+
// Configure training
91+
let config = TrainingConfig {
92+
epochs: 100,
93+
print_every: 10,
94+
clip_gradient: Some(1.0),
95+
};
96+
trainer = trainer.with_config(config);
97+
98+
// Generate some training data (sine wave prediction)
99+
let train_data = generate_sine_wave_data();
100+
101+
// Train the model
102+
trainer.train(&train_data, None);
103+
104+
// Make predictions
105+
let predictions = trainer.predict(&input_sequence);
106+
}
107+
```
108+
109+
### Advanced Features
110+
111+
#### Using Different Optimizers
112+
113+
```rust
114+
use rust_lstm::optimizers::{SGD, Adam, RMSprop};
115+
116+
// SGD optimizer
117+
let sgd = SGD::new(0.01);
118+
119+
// Adam optimizer with custom parameters
120+
let adam = Adam::with_params(0.001, 0.9, 0.999, 1e-8);
121+
122+
// RMSprop optimizer
123+
let rmsprop = RMSprop::new(0.01);
124+
```
125+
126+
#### Different Loss Functions
62127

128+
```rust
129+
use rust_lstm::loss::{MSELoss, MAELoss, CrossEntropyLoss};
130+
131+
// Mean Squared Error for regression
132+
let mse_loss = MSELoss;
133+
134+
// Mean Absolute Error for robust regression
135+
let mae_loss = MAELoss;
136+
137+
// Cross-Entropy for classification
138+
let ce_loss = CrossEntropyLoss;
139+
```
140+
141+
#### Peephole LSTM
142+
143+
```rust
144+
use rust_lstm::layers::peephole_lstm_cell::PeepholeLSTMCell;
145+
146+
let cell = PeepholeLSTMCell::new(input_size, hidden_size);
147+
let (h_t, c_t) = cell.forward(&input, &h_prev, &c_prev);
63148
```
64149

65150
To run this example, save it as main.rs, and run:
@@ -68,6 +153,44 @@ To run this example, save it as main.rs, and run:
68153
cargo run
69154
```
70155

156+
## Examples
157+
158+
The library includes several examples demonstrating different use cases:
159+
160+
- `basic_usage.rs` - Simple forward pass example
161+
- `training_example.rs` - Complete training workflow with multiple optimizers
162+
- `time_series_prediction.rs` - Time series forecasting
163+
- `text_generation.rs` - Character-level text generation
164+
- `multi_layer_lstm.rs` - Multi-layer network usage
165+
- `peephole.rs` - Peephole LSTM variant
166+
167+
Run examples with:
168+
169+
```bash
170+
cargo run --example training_example
171+
cargo run --example time_series_prediction
172+
```
173+
174+
## Architecture
175+
176+
The library is organized into several modules:
177+
178+
- **`layers`**: LSTM cell implementations (standard and peephole variants)
179+
- **`models`**: High-level network architectures
180+
- **`loss`**: Loss functions for training
181+
- **`optimizers`**: Optimization algorithms
182+
- **`training`**: Training utilities and trainer struct
183+
- **`utils`**: Common utility functions
184+
185+
## Training Features
186+
187+
- **Backpropagation Through Time (BPTT)**: Complete gradient computation for sequence modeling
188+
- **Gradient Clipping**: Prevents exploding gradients during training
189+
- **Multiple Optimizers**: SGD, Adam, RMSprop with configurable parameters
190+
- **Validation Support**: Track validation metrics during training
191+
- **Metrics Tracking**: Loss curves and training progress monitoring
192+
- **Flexible Training Loop**: Configurable epochs, learning rates, and logging
193+
71194
## Running the Tests
72195

73196
To run the tests included with Rust-LSTM, execute:

examples/peephole.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
use ndarray::{arr2, Array2};
2+
use rust_lstm::layers::peephole_lstm_cell::PeepholeLSTMCell;
3+
4+
fn main() {
5+
let input_size = 3;
6+
let hidden_size = 2;
7+
8+
// Create Peephole cell
9+
let cell = PeepholeLSTMCell::new(input_size, hidden_size);
10+
11+
// Single input vector: shape (3,1)
12+
let input: Array2<f64> = arr2(&[[0.5], [0.1], [-0.3]]);
13+
14+
// Initialize hidden, cell
15+
let h_prev = Array2::<f64>::zeros((hidden_size, 1));
16+
let c_prev = Array2::<f64>::zeros((hidden_size, 1));
17+
18+
// Single timestep forward pass
19+
let (h_t, c_t) = cell.forward(&input, &h_prev, &c_prev);
20+
21+
println!("h_t = \n{:?}", h_t);
22+
println!("c_t = \n{:?}", c_t);
23+
}

0 commit comments

Comments
 (0)