Implementing the minGRU neural network architecture in pure C is a complex task due to the lack of built-in tensor operations and automatic differentiation that frameworks like PyTorch provide. However, below is a comprehensive C implementation that mirrors the provided Python minGRU architecture. This implementation includes essential components such as linear layers, activation functions, RMS normalization, and the minGRU layer itself.
Please note: This implementation is a simplified version intended for educational purposes. It assumes fixed dimensions for simplicity and does not include optimizations or dynamic memory management that would be necessary for a production-quality neural network.
Overview
- Definitions and Structures: Define constants, data structures for layers, and tensors.
- Helper Functions: Implement matrix multiplication, activation functions, normalization, and utility functions.
- Layer Implementations: Implement Linear layers, RMSNorm, and the minGRU layer.
- Model Implementation: Build the
minGRULM model with embedding, layers, and output.
- Main Function: Initialize the model, perform a forward pass with sample data, and display the output.
1. Definitions and Structures
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
// Define constants (These can be adjusted as needed)
#define BATCH_SIZE 2
#define SEQ_LEN 3
#define VOCAB_SIZE 10
#define D_MODEL 8
#define D_INNER 8
#define N_LAYERS 2
// Utility macro for indexing 3D tensors
#define IDX3(batch, seq, dim, seq_len, dim_size) ((batch)*(seq_len)*(dim_size) + (seq)*(dim_size) + (dim))
// Utility macro for indexing 2D matrices
#define IDX2(row, col, num_cols) ((row)*(num_cols) + (col))
// Data structure for Linear layer
typedef struct {
int in_features;
int out_features;
double *weights; // size: in_features * out_features
} Linear;
// Data structure for RMSNorm
typedef struct {
int features;
double eps;
double *weight; // size: features
} RMSNorm;
// Data structure for minGRU
typedef struct {
Linear *to_hidden_and_gate; // Linear layer
Linear *to_out; // Linear layer
} minGRU;
// Data structure for RMSNorm
typedef struct {
int features;
double eps;
double *weight; // size: features
} RMSNorm;
// Data structure for a Layer in minGRULM
typedef struct {
RMSNorm *norm;
minGRU *mingru;
} Layer;
// Data structure for the minGRULM model
typedef struct {
double *token_emb; // size: VOCAB_SIZE * D_MODEL
Layer *layers; // array of N_LAYERS
RMSNorm *norm;
Linear *to_logits;
} minGRULM;
// Data structure for model parameters (for simplicity, parameters are initialized randomly)
typedef struct {
// Define all weights here if needed
} Parameters;
2. Helper Functions
Matrix Multiplication
// Performs matrix multiplication: C = A * B
// A is rows_A x cols_A, B is rows_B x cols_B
// C should be rows_A x cols_B
void matmul(const double *A, const double *B, double *C, int rows_A, int cols_A, int cols_B) {
// Initialize C to zero
for (int i = 0; i < rows_A * cols_B; i++) {
C[i] = 0.0;
}
// Perform multiplication
for (int i = 0; i < rows_A; i++) {
for (int k = 0; k < cols_A; k++) {
double a = A[IDX2(i, k, cols_A)];
for (int j = 0; j < cols_B; j++) {
C[IDX2(i, j, cols_B)] += a * B[IDX2(k, j, cols_B)];
}
}
}
}
Activation Functions
double relu(double x) {
return x > 0 ? x : 0;
}
double sigmoid(double x) {
return 1.0 / (1.0 + exp(-x));
}
double softplus(double x) {
return log(1.0 + exp(x));
}
double g_func(double x) {
return x >= 0 ? x + 0.5 : sigmoid(x);
}
double log_g(double x) {
if (x >= 0) {
return log(relu(x) + 0.5);
} else {
return -softplus(-x);
}
}
RMSNorm
// Applies RMSNorm to input vector x (size: features)
// Returns normalized vector in y
void rmsnorm_forward(const RMSNorm *norm, const double *x, double *y) {
double sum_sq = 0.0;
for (int i = 0; i < norm->features; i++) {
sum_sq += x[i] * x[i];
}
double inv_rms = 1.0 / sqrt((sum_sq / norm->features) + norm->eps);
for (int i = 0; i < norm->features; i++) {
y[i] = x[i] * inv_rms * norm->weight[i];
}
}
Log Cumulative Sum Exponentials
// Computes logcumsumexp for a 1D array
// result[i] = log(sum_{j=0}^i exp(x[j]))
void logcumsumexp(const double *x, double *result, int len) {
double max_val = x[0];
for (int i = 1; i < len; i++) {
if (x[i] > max_val) {
max_val = x[i];
}
}
double cumsum = exp(x[0] - max_val);
result[0] = log(cumsum) + max_val;
for (int i = 1; i < len; i++) {
cumsum += exp(x[i] - max_val);
result[i] = log(cumsum) + max_val;
}
}
// Helper function for heinsen_associative_scan_log
// For simplicity, assume dim=1 and batch processing is handled outside
void heinsen_associative_scan_log(const double *log_coeffs, const double *log_values, double *out, int seq_len) {
// Compute a_star = cumsum(log_coeffs)
double a_star[SEQ_LEN];
a_star[0] = log_coeffs[0];
for (int i = 1; i < seq_len; i++) {
a_star[i] = a_star[i - 1] + log_coeffs[i];
}
// Compute log_h0_plus_b_star = logcumsumexp(log_values - a_star)
double temp[SEQ_LEN];
for (int i = 0; i < seq_len; i++) {
temp[i] = log_values[i] - a_star[i];
}
double log_cumsum[SEQ_LEN];
logcumsumexp(temp, log_cumsum, seq_len);
// Compute log_h = a_star + log_cumsum
for (int i = 0; i < seq_len; i++) {
out[i] = a_star[i] + log_cumsum[i];
}
}
3. Layer Implementations
Initialization Functions
// Initialize Linear layer with random weights
Linear* linear_init(int in_features, int out_features) {
Linear *layer = malloc(sizeof(Linear));
layer->in_features = in_features;
layer->out_features = out_features;
layer->weights = malloc(sizeof(double) * in_features * out_features);
// Initialize weights randomly
for (int i = 0; i < in_features * out_features; i++) {
layer->weights[i] = ((double)rand() / RAND_MAX - 0.5) * 0.1; // Small random values
}
return layer;
}
// Initialize RMSNorm
RMSNorm* rmsnorm_init(int features, double eps) {
RMSNorm *norm = malloc(sizeof(RMSNorm));
norm->features = features;
norm->eps = eps;
norm->weight = malloc(sizeof(double) * features);
// Initialize weights to 1.0
for (int i = 0; i < features; i++) {
norm->weight[i] = 1.0;
}
return norm;
}
// Initialize minGRU
minGRU* mingru_init(int d_model, int d_inner) {
minGRU *gru = malloc(sizeof(minGRU));
gru->to_hidden_and_gate = linear_init(d_model, d_inner * 2); // No bias
gru->to_out = linear_init(d_inner, d_model); // No bias
return gru;
}
// Initialize a Layer
Layer layer_init(int d_model, int d_inner) {
Layer layer;
layer.norm = rmsnorm_init(d_model, 1e-5);
layer.mingru = mingru_init(d_model, d_inner);
return layer;
}
// Initialize minGRULM
minGRULM* mingrulm_init() {
minGRULM *model = malloc(sizeof(minGRULM));
// Initialize token embeddings
model->token_emb = malloc(sizeof(double) * VOCAB_SIZE * D_MODEL);
for (int i = 0; i < VOCAB_SIZE * D_MODEL; i++) {
model->token_emb[i] = ((double)rand() / RAND_MAX - 0.5) * 0.1;
}
// Initialize layers
model->layers = malloc(sizeof(Layer) * N_LAYERS);
for (int i = 0; i < N_LAYERS; i++) {
model->layers[i] = layer_init(D_MODEL, D_INNER);
}
// Initialize final RMSNorm
model->norm = rmsnorm_init(D_MODEL, 1e-5);
// Initialize to_logits Linear layer
model->to_logits = linear_init(D_MODEL, VOCAB_SIZE);
return model;
}
minGRU Forward Pass
// minGRU forward pass
// x: batch_size x seq_len x d_model
// prev_hidden: batch_size x d_inner (can be NULL)
// out: batch_size x seq_len x d_model
// next_prev_hidden: batch_size x d_inner
void mingru_forward(const minGRU *gru, const double *x, double *out, double *next_prev_hidden,
const double *prev_hidden, int batch_size, int seq_len, int d_model, int d_inner) {
// Compute hidden and gate: x * W^T
double hidden_gate[batch_size * seq_len * d_inner * 2];
matmul(x, gru->to_hidden_and_gate->weights, hidden_gate, batch_size * seq_len, d_model, d_inner * 2);
// Split hidden and gate
double hidden[batch_size * seq_len * d_inner];
double gate[batch_size * seq_len * d_inner];
for (int i = 0; i < batch_size * seq_len * d_inner; i++) {
hidden[i] = hidden_gate[i];
gate[i] = hidden_gate[batch_size * seq_len * d_inner + i];
}
if (seq_len == 1) { // Sequential
// Apply g to hidden
for (int i = 0; i < batch_size * d_inner; i++) {
hidden[i] = g_func(hidden[i]);
}
// Apply sigmoid to gate
for (int i = 0; i < batch_size * d_inner; i++) {
gate[i] = sigmoid(gate[i]);
}
// Compute out
for (int i = 0; i < batch_size * d_inner; i++) {
if (prev_hidden != NULL) {
out[i] = prev_hidden[i] * (1.0 - gate[i]) + hidden[i] * gate[i];
} else {
out[i] = hidden[i] * gate[i];
}
// Update next_prev_hidden
next_prev_hidden[i] = out[i];
}
// Apply to_out linear layer
double temp_out[batch_size * seq_len * d_model];
matmul(out, gru->to_out->weights, temp_out, batch_size, d_inner, d_model);
memcpy(out, temp_out, sizeof(double) * batch_size * d_model);
}
else { // Parallel
// Compute log_coeffs = -softplus(gate)
double log_coeffs[batch_size * seq_len * d_inner];
for (int i = 0; i < batch_size * seq_len * d_inner; i++) {
log_coeffs[i] = -softplus(gate[i]);
}
// Compute log_z = -softplus(-gate)
double log_z[batch_size * seq_len * d_inner];
for (int i = 0; i < batch_size * seq_len * d_inner; i++) {
log_z[i] = -softplus(-gate[i]);
}
// Compute log_tilde_h = log_g(hidden)
double log_tilde_h[batch_size * seq_len * d_inner];
for (int i = 0; i < batch_size * seq_len * d_inner; i++) {
log_tilde_h[i] = log_g(hidden[i]);
}
// Compute log_values = log_z + log_tilde_h
double log_values[batch_size * seq_len * d_inner];
for (int i = 0; i < batch_size * seq_len * d_inner; i++) {
log_values[i] = log_z[i] + log_tilde_h[i];
}
// If prev_hidden is provided, concatenate
double extended_log_values[BATCH_SIZE * (SEQ_LEN +1) * D_INNER];
double extended_log_coeffs[BATCH_SIZE * (SEQ_LEN +1) * D_INNER];
if (prev_hidden != NULL) {
for (int b = 0; b < batch_size; b++) {
for (int i = 0; i < D_INNER; i++) {
extended_log_values[b * (SEQ_LEN +1) * D_INNER + i] = log(prev_hidden[b * D_INNER + i]);
extended_log_coeffs[b * (SEQ_LEN +1) * D_INNER + i] = log_coeffs[b * SEQ_LEN * D_INNER + i];
}
for (int s = 0; s < SEQ_LEN; s++) {
for (int i = 0; i < D_INNER; i++) {
extended_log_values[b * (SEQ_LEN +1) * D_INNER + (s +1)*D_INNER + i] = log_values[b * SEQ_LEN * D_INNER + s * D_INNER + i];
extended_log_coeffs[b * (SEQ_LEN +1) * D_INNER + (s +1)*D_INNER + i] = log_coeffs[b * SEQ_LEN * D_INNER + s * D_INNER + i];
}
}
}
} else {
memcpy(extended_log_values, log_values, sizeof(double) * batch_size * SEQ_LEN * D_INNER);
memcpy(extended_log_coeffs, log_coeffs, sizeof(double) * batch_size * SEQ_LEN * D_INNER);
}
// Apply heinsen_associative_scan_log
double log_h[batch_size * (SEQ_LEN +1) * D_INNER];
for (int b = 0; b < batch_size; b++) {
for (int i = 0; i < D_INNER; i++) {
heinsen_associative_scan_log(
&extended_log_coeffs[b * (SEQ_LEN +1) * D_INNER + i],
&extended_log_values[b * (SEQ_LEN +1) * D_INNER + i],
&log_h[b * (SEQ_LEN +1) * D_INNER + i],
SEQ_LEN +1
);
}
}
// Take the last seq_len elements
for (int b = 0; b < batch_size; b++) {
for (int s = 0; s < SEQ_LEN; s++) {
for (int i = 0; i < D_INNER; i++) {
out[b * SEQ_LEN * D_MODEL + s * D_MODEL + i] = exp(log_h[b * (SEQ_LEN +1) * D_INNER + i +1]);
}
}
}
// Update next_prev_hidden
for (int b = 0; b < batch_size; b++) {
for (int i = 0; i < D_INNER; i++) {
next_prev_hidden[b * D_INNER + i] = out[b * SEQ_LEN * D_MODEL + (SEQ_LEN -1) * D_MODEL + i];
}
}
// Apply to_out linear layer
double temp_out[BATCH_SIZE * SEQ_LEN * D_MODEL];
matmul(out, gru->to_out->weights, temp_out, batch_size * SEQ_LEN, D_INNER, D_MODEL);
memcpy(out, temp_out, sizeof(double) * batch_size * SEQ_LEN * D_MODEL);
}
}
4. Model Implementation
Token Embedding and Forward Pass
// Token Embedding: simple lookup
// input_ids: batch_size x seq_len
// embeddings: batch_size x seq_len x d_model
void embedding_forward(const double *token_emb, const int *input_ids, double *embeddings, int batch_size, int seq_len, int d_model) {
for (int b = 0; b < batch_size; b++) {
for (int s = 0; s < seq_len; s++) {
int token = input_ids[b * seq_len + s];
for (int m = 0; m < d_model; m++) {
embeddings[IDX3(b, s, m, seq_len, d_model)] = token_emb[token * d_model + m];
}
}
}
}
// minGRULM forward pass
// For simplicity, this function does not handle all features like return_loss
void mingrulm_forward(minGRULM *model, const int *input_ids, double *logits, int batch_size, int seq_len) {
// Step 1: Embedding
double embeddings[BATCH_SIZE * SEQ_LEN * D_MODEL];
embedding_forward(model->token_emb, input_ids, embeddings, batch_size, seq_len, D_MODEL);
// Initialize prev_hiddens (assuming zero)
double next_prev_hiddens[N_LAYERS * BATCH_SIZE * D_INNER];
memset(next_prev_hiddens, 0, sizeof(double) * N_LAYERS * BATCH_SIZE * D_INNER);
// Iterate through layers
double layer_input[BATCH_SIZE * SEQ_LEN * D_MODEL];
memcpy(layer_input, embeddings, sizeof(double) * BATCH_SIZE * SEQ_LEN * D_MODEL);
for (int l = 0; l < N_LAYERS; l++) {
// Apply RMSNorm
double normed[BATCH_SIZE * SEQ_LEN * D_MODEL];
for (int b = 0; b < batch_size; b++) {
for (int s = 0; s < seq_len; s++) {
rmsnorm_forward(model->layers[l].norm,
&layer_input[IDX3(b, s, 0, seq_len, D_MODEL)],
&normed[IDX3(b, s, 0, seq_len, D_MODEL)]);
}
}
// Apply minGRU
double gru_out[BATCH_SIZE * SEQ_LEN * D_MODEL];
double layer_prev_hiddens[BATCH_SIZE * D_INNER];
memset(layer_prev_hiddens, 0, sizeof(double) * BATCH_SIZE * D_INNER);
mingru_forward(model->layers[l].mingru, normed, gru_out, layer_prev_hiddens,
NULL, batch_size, seq_len, D_MODEL, D_INNER); // prev_hidden is NULL for simplicity
// Add residual connection
for (int i = 0; i < BATCH_SIZE * SEQ_LEN * D_MODEL; i++) {
layer_input[i] = gru_out[i] + layer_input[i];
}
// Update next_prev_hiddens (ignored in this simplified version)
}
// Apply final RMSNorm
double normed_final[BATCH_SIZE * SEQ_LEN * D_MODEL];
for (int b = 0; b < batch_size; b++) {
for (int s = 0; s < seq_len; s++) {
rmsnorm_forward(model->norm,
&layer_input[IDX3(b, s, 0, seq_len, D_MODEL)],
&normed_final[IDX3(b, s, 0, seq_len, D_MODEL)]);
}
}
// Compute logits
matmul(normed_final, model->to_logits->weights, logits, BATCH_SIZE * SEQ_LEN, D_MODEL, VOCAB_SIZE);
}
5. Main Function
int main() {
// Initialize model
minGRULM *model = mingrulm_init();
// Example input_ids (batch_size x seq_len)
int input_ids[BATCH_SIZE * SEQ_LEN] = {
1, 2, 3,
4, 5, 6
};
// Output logits (batch_size x seq_len x vocab_size)
double logits[BATCH_SIZE * SEQ_LEN * VOCAB_SIZE];
memset(logits, 0, sizeof(double) * BATCH_SIZE * SEQ_LEN * VOCAB_SIZE);
// Forward pass
mingrulm_forward(model, input_ids, logits, BATCH_SIZE, SEQ_LEN);
// Print logits
for (int b = 0; b < BATCH_SIZE; b++) {
for (int s = 0; s < SEQ_LEN; s++) {
printf("Logits for batch %d, seq %d: ", b, s);
for (int v = 0; v < VOCAB_SIZE; v++) {
printf("%.4f ", logits[IDX3(b, s, v, SEQ_LEN, VOCAB_SIZE)]);
}
printf("\n");
}
}
// Free allocated memory (omitted for brevity)
return 0;
}
Compilation and Execution
To compile and run the program:
gcc -o mingru mingru.c -lm
./mingru
Important Considerations
-
Memory Management: The above code uses malloc for dynamic memory allocation but does not include corresponding free calls. In a complete implementation, ensure that all allocated memory is properly freed to avoid memory leaks.
-
Performance: This pure C implementation is not optimized for performance. Efficient implementations would leverage optimized libraries for matrix operations and parallel processing.
-
Numerical Stability: Functions like logcumsumexp can suffer from numerical instability. Proper handling (e.g., using the log-sum-exp trick) is essential for reliable computations.
-
Batch and Sequence Handling: The implementation assumes fixed BATCH_SIZE and SEQ_LEN. For flexibility, consider modifying the code to handle variable sizes dynamically.
-
Parameter Initialization: The weights are randomly initialized. In practice, you would load pre-trained weights or implement a training mechanism.
-
Activation Functions: The g_func and log_g functions are implemented as per the provided Python code. Ensure that these functions align with the theoretical expectations for your specific use case.
-
Extensibility: This implementation provides a foundation. To extend it (e.g., adding backpropagation for training), significant additional code would be required.
Conclusion
This C implementation provides a foundational structure for the minGRU neural network architecture inspired by the provided Python code. While it covers the essential components, further enhancements and optimizations are necessary for practical applications, especially concerning memory management, performance, and numerical stability.