using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Double; // For double-precision matrices
namespace UniversalRNN
{
public class RNN
{
// Hyperparameters and configuration
public int InputSize { get; set; } // Size of input vector
public int HiddenSize { get; set; } // Number of hidden units
public int OutputSize { get; set; } // Size of output vector
public int NumLayers { get; set; } = 1; // Number of RNN layers
public string ActivationFunction { get; set; } = "tanh"; // Default: tanh
public double LearningRate { get; set; } = 0.01;
public string Optimizer { get; set; } = "SGD"; // Options: SGD, Adam
public double DropoutRate { get; set; } = 0.0; // 0 means no dropout
// Weights and biases (initialized randomly)
private Matrix<double> Wxh; // Input to hidden
private Matrix<double> Whh; // Hidden to hidden
private Matrix<double> Why; // Hidden to output
private Vector<double> Bh; // Hidden bias
private Vector<double> By; // Output bias
// Gradients for backpropagation
private Matrix<double> dWxh;
private Matrix<double> dWhh;
private Matrix<double> dWhy;
private Vector<double> dBh;
private Vector<double> dBy;
// Adam optimizer parameters
private Matrix<double> mWxh, vWxh; // For Adam
private Matrix<double> mWhh, vWhh;
private Matrix<double> mWhy, vWhy;
private Vector<double> mBh, vBh;
private Vector<double> mBy, vBy;
private double Beta1 = 0.9;
private double Beta2 = 0.999;
private double Epsilon = 1e-8;
private int T = 0; // Time step for Adam
public RNN(int inputSize, int hiddenSize, int outputSize)
{
InputSize = inputSize;
HiddenSize = hiddenSize;
OutputSize = outputSize;
// Initialize weights and biases
var random = new Random();
Wxh = Matrix<double>.Build.Random(hiddenSize, inputSize);
Whh = Matrix<double>.Build.Random(hiddenSize, hiddenSize);
Why = Matrix<double>.Build.Random(outputSize, hiddenSize);
Bh = Vector<double>.Build.Random(hiddenSize);
By = Vector<double>.Build.Random(outputSize);
// Initialize gradients and Adam parameters
dWxh = Matrix<double>.Build.Dense(hiddenSize, inputSize);
dWhh = Matrix<double>.Build.Dense(hiddenSize, hiddenSize);
dWhy = Matrix<double>.Build.Dense(outputSize, hiddenSize);
dBh = Vector<double>.Build.Dense(hiddenSize);
dBy = Vector<double>.Build.Dense(outputSize);
mWxh = Matrix<double>.Build.Dense(hiddenSize, inputSize);
vWxh = Matrix<double>.Build.Dense(hiddenSize, inputSize);
// Similarly for others...
mWhh = Matrix<double>.Build.Dense(hiddenSize, hiddenSize);
vWhh = Matrix<double>.Build.Dense(hiddenSize, hiddenSize);
mWhy = Matrix<double>.Build.Dense(outputSize, hiddenSize);
vWhy = Matrix<double>.Build.Dense(outputSize, hiddenSize);
mBh = Vector<double>.Build.Dense(hiddenSize);
vBh = Vector<double>.Build.Dense(hiddenSize);
mBy = Vector<double>.Build.Dense(outputSize);
vBy = Vector<double>.Build.Dense(outputSize);
}
// Forward pass for a single sequence
public List<Vector<double>> Forward(List<Vector<double>> inputs, bool autoregressive = false)
{
var hs = new List<Vector<double>>(); // Hidden states
var outputs = new List<Vector<double>>(); // Output predictions
Vector<double> hPrev = Vector<double>.Build.Dense(HiddenSize, 0.0); // Initial hidden state
for (int t = 0; t < inputs.Count; t++)
{
var xt = inputs[t]; // Current input
var hNext = (Wxh * xt + Whh * hPrev + Bh).PointwiseTanh(); // RNN cell (using tanh by default)
if (DropoutRate > 0) hNext = ApplyDropout(hNext, DropoutRate); // Apply dropout
hs.Add(hNext);
var yt = (Why * hNext + By).PointwiseTanh(); // Output layer
outputs.Add(yt);
if (autoregressive)
{
// Feed output back as next input (for generation)
hPrev = hNext;
inputs[t + 1] = yt; // Modify next input to be the current output
}
else
{
hPrev = hNext; // Standard forward
}
}
return outputs; // Return sequence of outputs
}
// Training loop with backpropagation through time
public void Train(List<List<Vector<double>>> sequences, List<List<Vector<double>>> targets, int epochs = 100, int batchSize = 32)
{
for (int epoch = 0; epoch < epochs; epoch++)
{
double totalLoss = 0;
var batches = BatchData(sequences, targets, batchSize);
Parallel.For(0, batches.Count, i => // Parallelize batches for performance
{
var (batchInputs, batchTargets) = batches[i];
var outputs = Forward(batchInputs, autoregressive: true); // Enable learning from output
// Compute loss (e.g., MSE) and gradients
for (int t = 0; t < outputs.Count; t++)
{
var loss = MeanSquaredError(outputs[t], batchTargets[t]);
totalLoss += loss;
// Backpropagation (simplified)
var dyt = (outputs[t] - batchTargets[t]) * (1 - outputs[t].PointwisePower(2)); // Derivative of tanh
dWhy += dyt.OuterProduct(batchInputs[t]);
dBy += dyt;
var dh = Why.Transpose() * dyt + (t < outputs.Count - 1 ? dWhh.Transpose() * Vector<double>.Build.Dense(HiddenSize) : Vector<double>.Build.Dense(HiddenSize, 0));
dWxh += dh.OuterProduct(batchInputs[t - 1]); // Assuming previous input
dWhh += dh.OuterProduct(batchInputs[t]); // Recurrent part
dBh += dh;
}
// Update weights using optimizer
UpdateWeights();
});
Console.WriteLine($"Epoch {epoch + 1}/{epochs}, Loss: {totalLoss / batches.Count}");
}
}
// Helper: Apply dropout
private Vector<double> ApplyDropout(Vector<double> vector, double rate)
{
var mask = Vector<double>.Build.Dense(vector.Count, i => new Random().NextDouble() > rate ? 1.0 : 0.0);
return vector.PointwiseMultiply(mask) / (1 - rate); // Scale to maintain expected value
}
// Optimizer update
private void UpdateWeights()
{
T++;
if (Optimizer == "Adam")
{
// Adam update for Wxh (and similarly for others)
mWxh = Beta1 * mWxh + (1 - Beta1) * dWxh;
vWxh = Beta2 * vWxh + (1 - Beta2) * (dWxh.PointwisePower(2));
var mHat = mWxh / (1 - Math.Pow(Beta1, T));
var vHat = vWxh / (1 - Math.Pow(Beta2, T));
Wxh -= LearningRate * mHat.PointwiseDivide(vHat.PointwiseSqrt() + Epsilon);
// Repeat for other parameters...
// (Omitted for brevity; you can extend this)
}
else // SGD
{
Wxh -= LearningRate * dWxh;
Whh -= LearningRate * dWhh;
Why -= LearningRate * dWhy;
Bh -= LearningRate * dBh;
By -= LearningRate * dBy;
}
// Reset gradients
dWxh.Clear();
dWhh.Clear();
dWhy.Clear();
dBh.Clear();
dBy.Clear();
}
// Loss function: Mean Squared Error
private double MeanSquaredError(Vector<double> predicted, Vector<double> actual)
{
return (predicted - actual).PointwisePower(2).Sum() / predicted.Count;
}
// Batch data
private List<(List<Vector<double>>, List<Vector<double>>)> BatchData(List<List<Vector<double>>> inputs, List<List<Vector<double>>> targets, int batchSize)
{
var batches = new List<(List<Vector<double>>, List<Vector<double>>)>();
for (int i = 0; i < inputs.Count; i += batchSize)
{
batches.Add((inputs.Skip(i).Take(batchSize).ToList(), targets.Skip(i).Take(batchSize).ToList()));
}
return batches;
}
}
class Program
{
static void Main(string[] args)
{
// Example usage: Train on a simple sequence (e.g., sine wave generation)
var rnn = new RNN(inputSize: 1, hiddenSize: 64, outputSize: 1);
var sequences = new List<List<Vector<double>>> { /* Add your input sequences */ };
var targets = new List<List<Vector<double>>> { /* Add your target sequences */ };
rnn.Train(sequences, targets, epochs: 50, batchSize: 16);
// Inference with autoregressive mode
var inputSequence = new List<Vector<double>> { Vector<double>.Build.Dense(1, 0.5) }; // Example input
var generated = rnn.Forward(inputSequence, autoregressive: true);
foreach (var output in generated)
{
Console.WriteLine($"Generated Output: {output[0]}");
}
}
}
}