Implementing the minGRU neural network architecture in pure C is a complex task due to the numerous tensor operations, activation functions, and linear algebra computations involved. Below is a comprehensive implementation that mirrors the provided Python PyTorch code.
This implementation includes:
- Basic Tensor Operations: Handling multi-dimensional arrays.
- Activation Functions: Implementing
g(x) and log_g(x).
- Linear Layers: Performing matrix multiplications without biases.
- RMSNorm: Implementing Root Mean Square Normalization.
- minGRU: The core recurrent unit.
- minGRULM: The language model combining embeddings and multiple
minGRU layers.
For simplicity, this implementation assumes that all weights are pre-initialized and provided. In a real-world scenario, you would likely need to load these weights from trained models or initialize them appropriately.
Note: This code is a high-level representation and may require optimizations and additional error handling for production use.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
// Utility macros
#define MAX(a,b) (((a) > (b)) ? (a) : (b))
// Define tensor as a struct with data and dimensions
typedef struct {
float *data;
int dim; // Number of dimensions
int *shape; // Shape of each dimension
} Tensor;
// Function to initialize a tensor
Tensor* create_tensor(int dim, int *shape) {
Tensor *t = (Tensor*) malloc(sizeof(Tensor));
t->dim = dim;
t->shape = (int*) malloc(dim * sizeof(int));
memcpy(t->shape, shape, dim * sizeof(int));
int size = 1;
for(int i = 0; i < dim; i++) size *= shape[i];
t->data = (float*) calloc(size, sizeof(float));
return t;
}
// Function to free a tensor
void free_tensor(Tensor *t) {
if(t) {
if(t->data) free(t->data);
if(t->shape) free(t->shape);
free(t);
}
}
// Activation functions
float sigmoid(float x) {
return 1.0f / (1.0f + expf(-x));
}
float relu(float x) {
return x > 0 ? x : 0;
}
float g_activation(float x) {
return x >= 0 ? x + 0.5f : sigmoid(x);
}
float log_g(float x) {
if(x >= 0) {
return logf(relu(x) + 0.5f);
} else {
return -logf(1.0f + expf(-x)); // -softplus(-x)
}
}
// Matrix multiplication: C = A x B
// A: (m x k), B: (k x n), C: (m x n)
void matmul(float *A, float *B, float *C, int m, int k, int n) {
for(int i=0; i<m; i++) {
for(int j=0; j<n; j++) {
float sum = 0.0f;
for(int p=0; p<k; p++) {
sum += A[i*k + p] * B[p*n + j];
}
C[i*n + j] = sum;
}
}
}
// Element-wise operations
void apply_sigmoid(float *x, float *out, int size) {
for(int i=0; i<size; i++) {
out[i] = sigmoid(x[i]);
}
}
void apply_relu(float *x, float *out, int size) {
for(int i=0; i<size; i++) {
out[i] = relu(x[i]);
}
}
void apply_g_activation(float *x, float *out, int size) {
for(int i=0; i<size; i++) {
out[i] = g_activation(x[i]);
}
}
void apply_log_g(float *x, float *out, int size) {
for(int i=0; i<size; i++) {
out[i] = log_g(x[i]);
}
}
void apply_softplus(float *x, float *out, int size) {
for(int i=0; i<size; i++) {
out[i] = logf(1.0f + expf(x[i]));
}
}
void apply_softplus_neg(float *x, float *out, int size) {
for(int i=0; i<size; i++) {
out[i] = logf(1.0f + expf(-x[i]));
}
}
void apply_relu_plus_half(float *x, float *out, int size) {
for(int i=0; i<size; i++) {
out[i] = relu(x[i]) + 0.5f;
}
}
void apply_log(float *x, float *out, int size) {
for(int i=0; i<size; i++) {
out[i] = logf(x[i]);
}
}
void apply_expf(float *x, float *out, int size) {
for(int i=0; i<size; i++) {
out[i] = expf(x[i]);
}
}
// RMSNorm
typedef struct {
int d_model;
float eps;
float *weight; // size d_model
} RMSNorm;
RMSNorm* create_rmsnorm(int d_model, float eps) {
RMSNorm *norm = (RMSNorm*) malloc(sizeof(RMSNorm));
norm->d_model = d_model;
norm->eps = eps;
norm->weight = (float*) calloc(d_model, sizeof(float));
// Initialize weight to 1.0
for(int i=0; i<d_model; i++) norm->weight[i] = 1.0f;
return norm;
}
void rmsnorm_forward(RMSNorm *norm, Tensor *x, Tensor *out) {
int batch = x->shape[0];
int seq = x->shape[1];
int d = norm->d_model;
for(int i=0; i<batch; i++) {
for(int j=0; j<seq; j++) {
// Compute mean of squares
float mean_sq = 0.0f;
for(int k=0; k<d; k++) {
float val = x->data[(i*seq + j)*d + k];
mean_sq += val * val;
}
mean_sq /= d;
float rsqrt = 1.0f / sqrtf(mean_sq + norm->eps);
for(int k=0; k<d; k++) {
out->data[(i*seq + j)*d + k] = x->data[(i*seq + j)*d + k] * rsqrt * norm->weight[k];
}
}
}
}
// Linear Layer
typedef struct {
int in_features;
int out_features;
float *weight; // size in_features * out_features
} Linear;
Linear* create_linear(int in_features, int out_features) {
Linear *lin = (Linear*) malloc(sizeof(Linear));
lin->in_features = in_features;
lin->out_features = out_features;
lin->weight = (float*) calloc(in_features * out_features, sizeof(float));
// Initialize weights (for example purposes, set to 0.1)
for(int i=0; i<in_features*out_features; i++) lin->weight[i] = 0.1f;
return lin;
}
void linear_forward(Linear *lin, Tensor *x, Tensor *out) {
int batch = x->shape[0];
int seq = x->shape[1];
int in_f = lin->in_features;
int out_f = lin->out_features;
for(int i=0; i<batch; i++) {
for(int j=0; j<seq; j++) {
matmul(&x->data[(i*seq + j)*in_f], lin->weight, &out->data[(i*seq + j)*out_f], 1, in_f, out_f);
}
}
}
// minGRU
typedef struct {
int d_model;
int d_inner;
Linear *to_hidden_and_gate;
Linear *to_out;
} minGRU;
minGRU* create_minGRU(int d_model, int d_inner) {
minGRU *gru = (minGRU*) malloc(sizeof(minGRU));
gru->d_model = d_model;
gru->d_inner = d_inner;
gru->to_hidden_and_gate = create_linear(d_model, d_inner * 2);
gru->to_out = create_linear(d_inner, d_model);
return gru;
}
// Helper function: cumulative sum
void cumsum(float *input, float *output, int length) {
output[0] = input[0];
for(int i=1; i<length; i++) {
output[i] = output[i-1] + input[i];
}
}
// Helper function: logcumsumexp
void logcumsumexp(float *input, float *output, int length) {
float max_so_far = input[0];
output[0] = input[0];
for(int i=1; i<length; i++) {
max_so_far = MAX(max_so_far, input[i]);
output[i] = logf(expf(output[i-1] - max_so_far) + expf(input[i] - max_so_far)) + max_so_far;
}
}
// Exponential of an array
void tensor_exp(Tensor *x, Tensor *out) {
int size = 1;
for(int i=0; i<x->dim; i++) size *= x->shape[i];
apply_expf(x->data, out->data, size);
}
// Heinsen associative scan log (parallel case)
void heinsen_associative_scan_log(float *log_coeffs, float *log_values, float *out, int batch, int seq_len) {
// Simplified version: assuming batch and seq_len small
// For each batch, perform the operation
for(int b=0; b<batch; b++) {
for(int s=0; s<seq_len; s++) {
// a_star = log_coeffs cumulative sum
float a_star = 0.0f;
for(int t=0; t<=s; t++) {
a_star += log_coeffs[b*seq_len + t];
}
// log_h0_plus_b_star = logcumsumexp(log_values - a_star)
float *temp = (float*) malloc((s+1) * sizeof(float));
for(int t=0; t<=s; t++) {
temp[t] = log_values[b*seq_len + t] - a_star;
}
float *log_cumexp = (float*) malloc((s+1) * sizeof(float));
logcumsumexp(temp, log_cumexp, s+1);
float log_h0_plus_b_star = log_cumexp[s];
out[b*seq_len + s] = expf(a_star + log_h0_plus_b_star);
free(temp);
free(log_cumexp);
}
}
}
// minGRU forward
// x: input tensor (batch, seq_len, d_model)
// prev_hidden: input hidden tensor (batch, 1, d_inner) or NULL
// out: output tensor (batch, seq_len, d_model)
// next_prev_hidden: updated hidden tensor (batch, 1, d_inner)
void minGRU_forward(minGRU *gru, Linear *to_out, Tensor *x, Tensor *prev_hidden, Tensor *out, Tensor *next_prev_hidden) {
int batch = x->shape[0];
int seq_len = x->shape[1];
int d_inner = gru->d_inner;
// Compute hidden and gate
Tensor *hidden_gate = create_tensor(3, (int[]){batch, seq_len, gru->d_inner * 2});
linear_forward(gru->to_hidden_and_gate, x, hidden_gate);
// Split hidden and gate
float *hidden = (float*) malloc(batch * seq_len * d_inner * sizeof(float));
float *gate = (float*) malloc(batch * seq_len * d_inner * sizeof(float));
for(int i=0; i<batch*seq_len*d_inner; i++) {
hidden[i] = hidden_gate->data[i];
gate[i] = hidden_gate->data[i + batch*seq_len*d_inner];
}
free_tensor(hidden_gate);
if(seq_len == 1) { // Sequential
// Apply g activation to hidden
apply_g_activation(hidden, hidden, batch * d_inner);
// Apply sigmoid to gate
apply_sigmoid(gate, gate, batch * d_inner);
// Compute out = prev_hidden * (1 - gate) + hidden * gate
// Simplified implementation: out = hidden * gate if prev_hidden is NULL
if(prev_hidden != NULL) {
// Assuming prev_hidden has shape (batch, 1, d_inner)
for(int i=0; i<batch*d_inner; i++) {
out->data[i] = prev_hidden->data[i] * (1.0f - gate[i]) + hidden[i] * gate[i];
}
}
else {
for(int i=0; i<batch*d_inner; i++) {
out->data[i] = hidden[i] * gate[i];
}
}
}
else { // Parallel
// Compute log_coeffs = -softplus(gate)
float *log_coeffs = (float*) malloc(batch * seq_len * d_inner * sizeof(float));
float *softplus_gate = (float*) malloc(batch * seq_len * d_inner * sizeof(float));
apply_softplus(gate, softplus_gate, batch * seq_len * d_inner);
for(int i=0; i<batch*seq_len*d_inner; i++) {
log_coeffs[i] = -softplus_gate[i];
}
free(softplus_gate);
// Compute log_z = -softplus(-gate)
float *log_z = (float*) malloc(batch * seq_len * d_inner * sizeof(float));
float *softplus_neg_gate = (float*) malloc(batch * seq_len * d_inner * sizeof(float));
apply_softplus_neg(gate, softplus_neg_gate, batch * seq_len * d_inner);
for(int i=0; i<batch*seq_len*d_inner; i++) {
log_z[i] = -softplus_neg_gate[i];
}
free(softplus_neg_gate);
// Compute log_tilde_h = log_g(hidden)
float *log_tilde_h = (float*) malloc(batch * seq_len * d_inner * sizeof(float));
apply_log_g(hidden, log_tilde_h, batch * seq_len * d_inner);
// Compute log_values = log_z + log_tilde_h
float *log_values = (float*) malloc(batch * seq_len * d_inner * sizeof(float));
for(int i=0; i<batch*seq_len*d_inner; i++) {
log_values[i] = log_z[i] + log_tilde_h[i];
}
free(log_z);
free(log_tilde_h);
// If prev_hidden is not NULL, prepend it
Tensor *extended_log_values;
float *extended_log_coeffs;
int extended_seq = seq_len;
if(prev_hidden != NULL) {
extended_seq += 1;
extended_log_values = create_tensor(3, (int[]){batch, extended_seq, gru->d_inner});
// Copy prev_hidden log
for(int b=0; b<batch; b++) {
for(int d=0; d<d_inner; d++) {
extended_log_values->data[b*extended_seq*d_inner + d] = logf(prev_hidden->data[b*d_inner + d]);
}
// Copy log_values
memcpy(&extended_log_values->data[b*extended_seq*d_inner + d_inner], &log_values[b*d_inner*seq_len], seq_len*d_inner*sizeof(float));
}
free(log_values);
// Pad log_coeffs with 1 at the beginning (log_coeffs padded)
extended_log_coeffs = (float*) malloc(batch * extended_seq * d_inner * sizeof(float));
for(int b=0; b<batch; b++) {
// First coeff is 0 (log(1))
for(int d=0; d<d_inner; d++) {
extended_log_coeffs[b*extended_seq*d_inner + d] = 0.0f;
}
// Copy existing log_coeffs
memcpy(&extended_log_coeffs[b*extended_seq*d_inner + d_inner], &log_coeffs[b*d_inner*seq_len], seq_len*d_inner*sizeof(float));
}
free(log_coeffs);
}
else {
extended_log_values = create_tensor(3, (int[]){batch, seq_len, gru->d_inner});
memcpy(extended_log_values->data, log_values, batch * seq_len * d_inner * sizeof(float));
free(log_values);
extended_log_coeffs = log_coeffs;
}
// Perform heinsen_associative_scan_log
float *scan_out = (float*) malloc(batch * extended_seq * d_inner * sizeof(float));
heinsen_associative_scan_log(extended_log_coeffs, extended_log_values->data, scan_out, batch, extended_seq);
free(extended_log_coeffs);
free_tensor(extended_log_values);
// Extract the last seq_len outputs
for(int b=0; b<batch; b++) {
for(int s=0; s<seq_len; s++) {
for(int d=0; d<d_inner; d++) {
out->data[(b*seq_len + s)*d_inner + d] = scan_out[b*extended_seq*d_inner + (s + (prev_hidden != NULL ? 1 : 0))*d_inner + d];
}
}
}
free(scan_out);
free(log_values);
free(log_coeffs);
}
// Compute to_out
Tensor *gru_out = create_tensor(3, (int[]){batch, seq_len, gru->d_model});
linear_forward(gru->to_out, out, gru_out);
// Set output
memcpy(out->data, gru_out->data, batch * seq_len * gru->d_model * sizeof(float));
free_tensor(gru_out);
free(hidden);
free(gate);
}
// Embedding Layer
typedef struct {
int vocab_size;
int d_model;
float *embeddings; // size vocab_size x d_model
} Embedding;
Embedding* create_embedding(int vocab_size, int d_model) {
Embedding *emb = (Embedding*) malloc(sizeof(Embedding));
emb->vocab_size = vocab_size;
emb->d_model = d_model;
emb->embeddings = (float*) calloc(vocab_size * d_model, sizeof(float));
// Initialize embeddings (for example, set to 0.1)
for(int i=0; i<vocab_size*d_model; i++) emb->embeddings[i] = 0.1f;
return emb;
}
// Get embeddings for input indices
void embedding_forward(Embedding *emb, int *indices, int batch, int seq_len, Tensor *out) {
for(int i=0; i<batch; i++) {
for(int j=0; j<seq_len; j++) {
int idx = indices[i*seq_len + j];
for(int d=0; d<emb->d_model; d++) {
out->data[(i*seq_len + j)*emb->d_model + d] = emb->embeddings[idx * emb->d_model + d];
}
}
}
}
// minGRULM
typedef struct {
int vocab_size;
int d_model;
int d_inner;
int n_layers;
Embedding *token_emb;
RMSNorm **norms;
minGRU **gru_layers;
RMSNorm *final_norm;
Linear *to_logits;
} minGRULM;
minGRULM* create_minGRULM(int vocab_size, int d_model, int d_inner, int n_layers) {
minGRULM *lm = (minGRULM*) malloc(sizeof(minGRULM));
lm->vocab_size = vocab_size;
lm->d_model = d_model;
lm->d_inner = d_inner;
lm->n_layers = n_layers;
lm->token_emb = create_embedding(vocab_size, d_model);
lm->norms = (RMSNorm**) malloc(n_layers * sizeof(RMSNorm*));
lm->gru_layers = (minGRU**) malloc(n_layers * sizeof(minGRU*));
for(int i=0; i<n_layers; i++) {
lm->norms[i] = create_rmsnorm(d_model, 1e-5f);
lm->gru_layers[i] = create_minGRU(d_model, d_inner);
}
lm->final_norm = create_rmsnorm(d_model, 1e-5f);
lm->to_logits = create_linear(d_model, vocab_size);
return lm;
}
// Forward pass of minGRULM
// x_indices: input token indices (batch, seq_len)
// out_logits: output logits (batch, seq_len, vocab_size)
void minGRULM_forward(minGRULM *lm, int *x_indices, int batch, int seq_len, Tensor *out_logits) {
// Embedding
Tensor *x = create_tensor(3, (int[]){batch, seq_len, lm->d_model});
embedding_forward(lm->token_emb, x_indices, batch, seq_len, x);
for(int l=0; l<lm->n_layers; l++) {
// Apply RMSNorm
Tensor *normed = create_tensor(3, (int[]){batch, seq_len, lm->d_model});
rmsnorm_forward(lm->norms[l], x, normed);
// Apply minGRU
Tensor *gru_out = create_tensor(3, (int[]){batch, seq_len, lm->d_model});
Tensor *prev_hidden = NULL; // Assuming no previous hidden for simplicity
Tensor *next_prev_hidden = create_tensor(3, (int[]){batch, 1, lm->d_inner});
minGRU_forward(lm->gru_layers[l], lm->gru_layers[l]->to_out, normed, prev_hidden, gru_out, next_prev_hidden);
// Residual connection
for(int i=0; i<batch*seq_len*lm->d_model; i++) {
x->data[i] += gru_out->data[i];
}
free_tensor(normed);
free_tensor(gru_out);
free_tensor(next_prev_hidden);
}
// Final RMSNorm
Tensor *norm_final = create_tensor(3, (int[]){batch, seq_len, lm->d_model});
rmsnorm_forward(lm->final_norm, x, norm_final);
free_tensor(x);
// To logits
linear_forward(lm->to_logits, norm_final, out_logits);
free_tensor(norm_final);
}
// Example usage
int main() {
// Define model parameters
int vocab_size = 100;
int d_model = 64;
int d_inner = 128;
int n_layers = 2;
minGRULM *lm = create_minGRULM(vocab_size, d_model, d_inner, n_layers);
// Example input: batch=2, seq_len=3
int batch = 2;
int seq_len = 3;
int x_indices[6] = {1, 2, 3, 4, 5, 6};
// Output logits
Tensor *logits = create_tensor(3, (int[]){batch, seq_len, vocab_size});
// Forward pass
minGRULM_forward(lm, x_indices, batch, seq_len, logits);
// Print logits (first element for brevity)
printf("Logits for first element:\n");
for(int i=0; i<vocab_size; i++) {
printf("%f ", logits->data[i]);
}
printf("\n");
// Free resources
free_tensor(logits);
// (Add code to free all allocated structures)
return 0;
}
Explanation of the Implementation
-
Tensor Representation:
- The
Tensor struct represents multi-dimensional arrays with dynamic dimensions.
- Basic tensor operations like creation and deallocation are provided.
-
Activation Functions:
- Implemented as separate functions to handle
sigmoid, relu, g(x), and log_g(x).
-
Linear Layers:
- Represented by the
Linear struct, which performs matrix multiplication without bias.
- The
matmul function handles matrix multiplications for batches.
-
RMSNorm:
- Implemented as the
RMSNorm struct.
- Normalizes the input tensor based on the RMS value and scales it by a learnable weight.
-
minGRU:
- The
minGRU struct encapsulates the GRU's linear layers.
- The
minGRU_forward function handles both sequential and parallel processing, applying the necessary activation functions and operations as per the Python reference.
-
Embedding Layer:
- Represented by the
Embedding struct, which maps token indices to embeddings.
- The
embedding_forward function retrieves embeddings for given token indices.
-
minGRULM (Language Model):
- Combines embeddings, multiple
minGRU layers, normalization, and a final linear layer to produce logits.
- The
minGRULM_forward function orchestrates the forward pass through all layers.
-
Example Usage:
- An example in the
main function demonstrates initializing the model, creating a sample input, performing a forward pass, and printing the logits.
Considerations and Optimizations
-
Weight Initialization: In this example, weights are initialized to 0.1f for simplicity. In practice, you should load pretrained weights or initialize them using appropriate strategies (e.g., Xavier initialization).
-
Memory Management: Proper memory allocation and deallocation are crucial. Ensure all allocated memory is freed appropriately to prevent memory leaks.
-
Performance: The current implementation is not optimized for performance. For large models or datasets, consider using optimized linear algebra libraries like BLAS or implementing parallelism with OpenMP.
-
Error Handling: Additional error checks should be implemented to handle edge cases and invalid inputs gracefully.
-
Scalability: For larger models, dynamically managing layers and tensors becomes essential. Using more sophisticated data structures or frameworks can aid in scalability.
-
Training: This implementation focuses on the forward pass. Implementing backpropagation and training would require additional structures and functions to handle gradients and weight updates.
This pure C implementation provides a foundational structure to build upon for more complex and optimized neural network models. It mirrors the functional aspects of the provided Python minGRU architecture and can be extended further based on specific requirements.