Certainly! Below is a comprehensive Rust program that implements an advanced neural network designed for text data. We'll build a Recurrent Neural Network (RNN) using Long Short-Term Memory (LSTM) units, which are well-suited for processing sequential data like text. We'll use the tch crate, which provides PyTorch bindings for Rust, allowing us to leverage efficient deep learning capabilities.
Overview
- Goal: Create a character-level language model that predicts the next character in a sequence.
- Architecture: An embedding layer, followed by an LSTM layer, and a fully connected output layer.
- Dataset: Any arbitrary text (for demonstration, we'll use a sample string).
Dependencies
Add the following to your Cargo.toml:
[dependencies]
tch = "0.14.0" # Ensure you have the latest version
Full Code
use tch::{nn, nn::Module, nn::OptimizerConfig, Device, Kind, Tensor};
use std::collections::HashMap;
/// Preprocess the text data: build vocabulary and map characters to indices.
fn preprocess_text(text: &str) -> (Vec<i64>, HashMap<char, i64>, HashMap<i64, char>) {
// Create a set of unique characters
let mut chars: Vec<char> = text.chars().collect();
chars.sort();
chars.dedup();
// Map each character to a unique index
let char_to_idx: HashMap<char, i64> = chars.iter().enumerate()
.map(|(i, &c)| (c, i as i64)).collect();
// Map indices back to characters
let idx_to_char: HashMap<i64, char> = chars.iter().enumerate()
.map(|(i, &c)| (i as i64, c)).collect();
// Encode the entire text as indices
let encoded_text: Vec<i64> = text.chars().map(|c| char_to_idx[&c]).collect();
(encoded_text, char_to_idx, idx_to_char)
}
/// Define the LSTM-based language model
struct LSTMModel {
lstm: nn::LSTM,
fc: nn::Linear,
device: Device,
}
impl LSTMModel {
fn new(vs: &nn::Path, input_size: i64, hidden_size: i64, output_size: i64, device: Device) -> Self {
// Define LSTM layer
let lstm_config = nn::LSTMConfig {
batch_first: true,
..Default::default()
};
let lstm = nn::lstm(vs / "lstm", input_size, hidden_size, lstm_config);
// Define a fully connected layer
let fc = nn::linear(vs / "fc", hidden_size, output_size, Default::default());
Self { lstm, fc, device }
}
fn forward(&self, x: &Tensor, hidden: &mut (Tensor, Tensor)) -> (Tensor, (Tensor, Tensor)) {
// Forward pass through LSTM layer
let (output, (h_n, c_n)) = x.to_device(self.device).lstm(&hidden.0, &hidden.1, &self.lstm);
// Reshape output to (batch_size*seq_length, hidden_size)
let output = output.contiguous().view([-1, output.size()[2]]);
// Pass through fully connected layer
let logits = output.apply(&self.fc);
(logits, (h_n, c_n))
}
}
fn main() {
// Sample text data
let text = "To be, or not to be, that is the question:";
let (encoded_text, char_to_idx, idx_to_char) = preprocess_text(text);
// Hyperparameters
let vocab_size = char_to_idx.len() as i64;
let embed_size = 64;
let hidden_size = 128;
let seq_length = 10;
let learning_rate = 0.01;
let num_epochs = 30;
// Device configuration
let device = Device::cuda_if_available();
// Create a variable store
let vs = nn::VarStore::new(device);
let root = &vs.root();
// Define the model
let model = LSTMModel::new(root, vocab_size, hidden_size, vocab_size, device);
// Define the optimizer
let mut optimizer = nn::Adam::default().build(&vs, learning_rate).unwrap();
// Training loop
let data_len = encoded_text.len();
let num_batches = (data_len - 1) / seq_length;
for epoch in 1..=num_epochs {
let mut total_loss = 0.0;
let mut hidden = (
Tensor::zeros(&[1, 1, hidden_size], (Kind::Float, device)),
Tensor::zeros(&[1, 1, hidden_size], (Kind::Float, device)),
);
for batch in 0..num_batches {
let start_idx = batch * seq_length;
let end_idx = start_idx + seq_length;
let inputs = &encoded_text[start_idx..end_idx];
let targets = &encoded_text[start_idx + 1..end_idx + 1];
// Convert inputs and targets to tensors
let input_tensor = Tensor::of_slice(inputs).to_device(device).unsqueeze(0);
let target_tensor = Tensor::of_slice(targets).to_device(device);
// One-hot encode inputs
let input_one_hot = input_tensor.one_hot(vocab_size).to_kind(Kind::Float);
// Zero gradients
optimizer.zero_grad();
// Forward pass
let (outputs, new_hidden) = model.forward(&input_one_hot, &mut hidden);
// Calculate loss
let loss = outputs.cross_entropy_for_logits(&target_tensor.view([-1]));
total_loss += f64::from(&loss);
// Backward pass and optimization
loss.backward();
optimizer.step();
// Detach hidden states to prevent backpropagating through entire history
hidden = (new_hidden.0.detach(), new_hidden.1.detach());
}
println!("Epoch [{}/{}], Loss: {:.4}", epoch, num_epochs, total_loss / num_batches as f64);
// Generate sample text
if epoch % 5 == 0 {
let sample_length = 100;
let mut sample = String::new();
// Start with a random character from the text
let mut input_idx = encoded_text[0];
let mut input_tensor = Tensor::of_slice(&[input_idx]).to_device(device).unsqueeze(0);
// Initialize hidden state
let mut hidden = (
Tensor::zeros(&[1, 1, hidden_size], (Kind::Float, device)),
Tensor::zeros(&[1, 1, hidden_size], (Kind::Float, device)),
);
for _ in 0..sample_length {
let input_one_hot = input_tensor.one_hot(vocab_size).to_kind(Kind::Float);
let (output, new_hidden) = model.forward(&input_one_hot, &mut hidden);
// Get the predicted character
let probs = output.softmax(-1, Kind::Float).squeeze();
let top_idx = probs.argmax(0, false).int64_value(&[]);
// Append character to sample
sample.push(idx_to_char[&top_idx]);
// Prepare next input
input_tensor = Tensor::of_slice(&[top_idx]).to_device(device).unsqueeze(0);
// Update hidden state
hidden = (new_hidden.0, new_hidden.1);
}
println!("Sampled text:\n{}", sample);
}
}
}
Explanation
1. Preprocessing
The preprocess_text function prepares the text data:
- Character Mapping: Creates mappings from characters to indices (
char_to_idx) and indices back to characters (idx_to_char).
- Encoding: Converts the entire text into a sequence of indices (
encoded_text).
2. Model Definition
We define an LSTMModel struct that encapsulates the model components:
- Layers:
- LSTM Layer: Processes sequences and maintains hidden states.
- Fully Connected Layer: Maps LSTM outputs to the vocabulary size for predictions.
- Forward Method: Performs a forward pass through the network, returning the output logits and updated hidden states.
3. Training Loop
In the main function:
- Hyperparameters: Set values for embedding size, hidden size, sequence length, etc.
- Data Preparation: Calculate the number of batches and ensure sequences align.
- Loop Over Epochs:
- Initialize hidden states to zeros.
- Loop over batches, prepare inputs and targets.
- Perform forward and backward passes.
- Update the model parameters using the optimizer.
- Loss Tracking: Compute and display the average loss per epoch.
4. Text Generation
- Every few epochs, we generate and display sample text to observe how the model is learning.
- Process:
- Start with an initial character.
- Use the model to predict the next character iteratively.
- Accumulate the predicted characters to form a sample text.
How to Run the Code
-
Install Rust: If you haven't installed Rust, do so using rustup.
-
Create a New Project:
cargo new lstm_text_model
cd lstm_text_model
-
Add Dependencies:
In your Cargo.toml, add:
[dependencies]
tch = "0.14.0"
-
Copy the Code:
Replace the contents of src/main.rs with the code provided above.
-
Install LibTorch:
The tch crate requires LibTorch (PyTorch C++ libraries).
-
Download LibTorch: Get the CPU or CUDA version from PyTorch's website.
-
Set LIBTORCH Environment Variable: Point it to the extracted LibTorch folder.
export LIBTORCH=/path/to/libtorch
-
Build and Run:
cargo run --release
The --release flag compiles the project in release mode, which is optimized.
Expected Output
The program will print the loss after each epoch and display a sampled text every 5 epochs. Initially, the loss will be high, and the sampled text will be nonsensical. As training progresses, the loss should decrease, and the sampled text should start resembling the input text.
Example output snippet:
Epoch [1/30], Loss: 3.3672
Epoch [2/30], Loss: 3.0258
Epoch [3/30], Loss: 2.7225
Epoch [4/30], Loss: 2.4801
Epoch [5/30], Loss: 2.2967
Sampled text:
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
Epoch [6/30], Loss: 2.1623
Epoch [7/30], Loss: 2.0589
...
Notes and Improvements
- Data Size: For demonstration, we used a short text. For better results, train on larger text data.
- Embedding Layer: An embedding layer can be added before the LSTM to convert input indices into dense vectors.
- Batching: Implementing mini-batch training would improve training speed and stability.
- Dropout and Regularization: Adding dropout layers can prevent overfitting.
- Model Complexity: Experiment with deeper networks or different architectures like GRUs or Transformers for improved performance.
- Learning Rate Schedule: Adjusting the learning rate over time can lead to better convergence.
Conclusion
This Rust program showcases how to build and train an LSTM-based language model using the tch crate. It's a starting point for implementing more complex models and experimenting with neural networks in Rust for text data processing.
Feel free to modify and extend the code to suit your specific requirements or to explore different neural network architectures.
Disclaimer: Ensure you have the appropriate setup for running the code, including Rust and LibTorch. If you encounter any issues, refer to the tch-rs documentation or seek help from the Rust community.