Documentation home / Native modules / gs_brain
gs_brain: Native AI and Machine-Learning Workspace
A single native C shared library that brings eight related numerical, neural, optimization, dataset, classical-learning, automatic-differentiation, checkpoint and data-workspace namespaces into greenServeFE. The public interface is ordinary GSVE objects, arrays and native functions—not a second language or a Python runtime.
gs_brain.so, one module initializerOn this page
1. Architecture and integration
gs_brain consolidates the eight AI/ML C implementations into ai-modules/gs_brain.c and exposes them through one greenServeFE_module_init entry point. The module is deliberately outside the core language and VM: importing it does not add keywords, opcodes, compiler rules or a new value type.
.gsve source
│
▼
lexer → tokens → parser / AST → bytecode compiler
│
▼
GSCode instruction stream
│
▼
greenServeFE virtual machine
│
import gs_brain;
│
▼
native module loader (dlopen)
│
▼
greenServeFE_module_init(GSNativeAPI)
│
▼
gs_brain.{array,neural,optimizer,dataset,
learn,autograd,checkpoint,cortex}
The module loader resolves a shared object from the configured native-module search path, opens it dynamically and invokes the required initializer symbol. The initializer returns a GSVE object whose members are namespaces containing native function values. From GSVE, calls look like ordinary chained member calls such as gs_brain.array.matmul(a, b).
Native ABI boundary
The shared library uses module.h and GSNativeAPI with ABI version GSFE_MODULE_ABI_VERSION 1. The API supplies constructors for null, number, boolean, string, object, array and native-function values; value copy/retain/release; array and object access; string and numeric conversion; truthiness; printing; and a VM callback interface.
The module initializer has the form GSValue greenServeFE_module_init(const GSNativeAPI *native_api). The implementation returns a root object and registers each of the eight namespaces. The VM's value model remains unchanged: null, number, boolean, string, array, object, function, native function and iterator.
Core language and VM context
GSVE source files use the .gsve extension. The language uses define for declarations, func for named functions, semicolon-terminated statements, object literals, nested arrays and explicit imports. The VM pipeline is lexer → parser/AST → compiler → GSCode bytecode → stack-based execution. A code object stores instructions, constants, names, child function code objects and parameter metadata; each instruction stores an opcode, integer argument and source line. Frames track an instruction pointer, operand-stack base and lexical environment. Function values retain their captured lexical environment.
import gs_brain; define matrix = [[1, 2], [3, 4]]; define product = gs_brain.array.matmul(matrix, matrix); print(product); print(gs_brain.cortex.workspace());
Relevant VM features used by module examples include numbers, strings, booleans, null, arrays, objects, arithmetic and comparisons, logical short-circuiting, indexing and members, conditionals, loops, functions and recursion, native calls, import and from ... import .... Use the language reference and the VM reference for the complete language and execution model.
2. Build, package and install
The source repository provides a manual-only GitHub Actions workflow named Build gs_brain native AI module. Open the repository's Actions tab, select Build gs_brain native AI module, choose Run workflow, and download the resulting artifact when the job succeeds.
Build configuration used by the workflow
cc -D_POSIX_C_SOURCE=200809L -std=c11 -O2 \ -Wall -Wextra -Wpedantic -Wno-unused-parameter \ -fPIC -shared -I. $(pkg-config --cflags libcurl) \ -o dist/gs_brain.so ai-modules/gs_brain.c \ $(pkg-config --libs libcurl) -lm
Build dependencies on the workflow runner: GCC/build-essential, pkg-config, libcurl development headers/library, ZIP tooling and the C math library. The job checks the exported initializer and the presence of namespace/API markers, then packages the shared object, C source and ABI headers. It also creates SHA-256 checksums. Those checks are build/package checks; they are not a substitute for running the module inside the target VM and validating numerical results.
The workflow artifact is named gs-brain-linux-x86_64.zip. It contains gs_brain.so, gs_brain.c, module.h, value.h and SHA256SUMS. Install the shared object into a directory searched by the greenServeFE module loader. For example, if the chosen directory is /usr/local/lib/modules:
mkdir -p /usr/local/lib/modules cp gs_brain.so /usr/local/lib/modules/ export GREENSERVE_MODULE_PATH=/usr/local/lib/modules greenServeFE ai-test.gsve
The exact copy/extraction command depends on where the downloaded ZIP was saved. The environment variable must point to the directory containing the shared object, not to the ZIP file.
3. gs_brain.array — numerical and matrix foundation
The array namespace accepts ordinary GSVE nested arrays. Matrix routines validate rectangular row shapes and numeric elements, use checked temporary C buffers for computation, and return GSVE arrays or scalar values. The current implementation is a two-dimensional matrix/vector foundation rather than a general N-dimensional tensor engine.
| Export | Purpose and input shape | Result |
|---|---|---|
info() | Returns module name, version, storage description and current status. | Metadata object. |
shape(matrix) | Inspect a rectangular numeric matrix. | [rows, columns]; invalid input returns null. |
zeros(rows, columns) | Create a zero-filled matrix. | Nested numeric array. |
ones(rows, columns) | Create a one-filled matrix. | Nested numeric array. |
add(a, b) | Elementwise matrix addition; both shapes must match. | Matrix. |
multiply(a, b) | Elementwise matrix multiplication; both shapes must match. | Matrix. |
transpose(matrix) | Swap matrix rows and columns. | Transposed matrix. |
matmul(a, b) | Matrix multiplication; columns of a must equal rows of b. | Product matrix. |
dot(a, b) | Dot product of equal-length numeric vectors. | Number. |
sum(vector), mean(vector) | Sum and arithmetic mean of a non-empty numeric vector. | Number. |
min(vector), max(vector) | Minimum and maximum of a non-empty numeric vector. | Number. |
variance(vector), std(vector) | Population variance and population standard deviation. | Number. |
abs(vector) | Absolute value of each numeric vector element. | Vector. |
import gs_brain; define a = [[1, 2], [3, 4]]; define b = [[5, 6], [7, 8]]; print(gs_brain.array.info()); print(gs_brain.array.shape(a)); print(gs_brain.array.zeros(2, 3)); print(gs_brain.array.ones(2, 2)); print(gs_brain.array.add(a, b)); print(gs_brain.array.multiply(a, b)); print(gs_brain.array.transpose(a)); print(gs_brain.array.matmul(a, b)); print(gs_brain.array.dot([1, 2, 3], [4, 5, 6])); print(gs_brain.array.mean([1, 2, 3, 4])); print(gs_brain.array.std([1, 2, 3, 4]));
The implementation applies an element-count bound of one million to the array/matrix paths shown here and rejects malformed dimensions or incompatible shapes with null. Do not assume broadcasting, slicing, N-D strides, determinant/inverse, or arbitrary array views are implemented by this namespace.
4. gs_brain.neural — CPU neural-network building blocks
The neural namespace contains a linear-regression training path, a one-hidden-layer ReLU regression path, inference helpers, activations and loss/gradient utilities. Training is CPU batch gradient descent. It is a practical starter engine, not a complete layer graph or general-purpose neural framework.
| Export | Role | Implementation note |
|---|---|---|
info() | Neural subsystem metadata. | Reports CPU backend and current training scope. |
gsai_neural_train_linear(X, y, learning_rate, epochs) | Train a linear regression model. | Returns a model object with kind, weights, bias, loss, feature count, epoch count and optimizer label. |
gsai_neural_predict_linear(model, X) | Predict with the linear model. | Returns one prediction per input row. |
dense(X, weights, bias) | Dense-layer forward computation. | Forward operation only; not an automatic trainable layer object. |
relu(values), sigmoid(values) | Activation functions. | Accept scalar numeric values or numeric vectors. |
softmax(vector) | Convert finite logits to normalized probabilities. | Uses max-shift stabilization. |
mse(predictions, targets) | Mean squared error. | Requires equal non-empty numeric vectors. |
mse_grad(predictions, targets) | MSE gradient helper. | Returns the implemented gradient vector. |
binary_cross_entropy(predictions, targets) | Binary cross-entropy loss helper. | For binary probability/target vectors. |
train_mlp(X, y, hidden, epochs, learning_rate) | Train a one-hidden-layer ReLU regression model. | CPU batch-gradient-descent path. |
predict_mlp(X, model) | Run inference with the trained MLP model. | Returns predictions for supplied rows. |
gsai_neural_train_linear and gsai_neural_predict_linear. Those names are intentionally shown exactly as exported; they are not shortened to train_linear/predict_linear.import gs_brain;
define X = [[0], [1], [2], [3]];
define y = [1, 3, 5, 7];
define linear_model =
gs_brain.neural.gsai_neural_train_linear(X, y, 0.01, 1000);
define predicted =
gs_brain.neural.gsai_neural_predict_linear(linear_model, X);
print(linear_model);
print(predicted);
print(gs_brain.neural.relu([-2, 0, 3]));
print(gs_brain.neural.sigmoid([0, 1, -1]));
print(gs_brain.neural.softmax([1, 2, 3]));
print(gs_brain.neural.mse([1, 2], [1, 3]));
5. gs_brain.optimizer — explicit update kernels
Optimizer functions operate on numeric vectors and return new vectors or state objects. They do not secretly own a training loop. In particular, Adam's moment vectors and step are caller-supplied and returned, making optimizer state explicit and serializable by the calling program.
| Export | Inputs | Output |
|---|---|---|
sgd(parameters, gradients, learning_rate) | Equal-length parameter and gradient vectors plus positive learning rate. | Updated parameter vector. |
momentum(parameters, gradients, velocity, learning_rate, momentum) | Equal-length vectors, learning rate and momentum coefficient. | Momentum update result/state as defined by the native kernel. |
adam(parameters, gradients, m, v, step, learning_rate, beta1, beta2, epsilon) | Parameter, gradient and first/second-moment vectors; step and Adam hyperparameters. | Object containing updated parameters, m, v and step. |
clip_grad_norm(gradients, max_norm) | Gradient vector and positive maximum norm. | Object with gradients, original norm and boolean clipped. |
info() | No arguments. | Backend and implementation status metadata. |
import gs_brain;
define parameters = [1, 2, 3];
define gradients = [0.1, -0.2, 0.3];
define next_parameters =
gs_brain.optimizer.sgd(parameters, gradients, 0.01);
define clipped =
gs_brain.optimizer.clip_grad_norm(gradients, 0.25);
print(next_parameters);
print(clipped);
These are update kernels, not a complete optimizer lifecycle with parameter registration, learning-rate schedules, automatic gradient collection, weight decay or callbacks. The caller manages training state.
6. gs_brain.dataset — paired data preparation
The dataset namespace works with ordinary VM arrays for features and labels. Operations preserve feature/label row pairing when shuffling, splitting or batching.
| Export | Purpose | Result structure |
|---|---|---|
shuffle(X, y, seed?) | Seeded paired-row shuffle. | {X: [...], y: [...], rows: n} |
batches(X, y, batch_size, drop_last?) | Partition paired rows into mini-batches. | Array of objects containing X, y and size. |
one_hot(labels, class_count) | Encode integer class labels. | Array of one-hot rows. |
train_test_split(X, y, test_fraction, seed?) | Seeded paired train/test split. | Object with X_train, X_test, y_train, y_test. |
info() | Subsystem status metadata. | Object. |
import gs_brain; define X = [[1, 10], [2, 20], [3, 30], [4, 40]]; define y = [0, 1, 0, 1]; define split = gs_brain.dataset.train_test_split(X, y, 0.25, 42); define groups = gs_brain.dataset.batches(split.X_train, split.y_train, 2); define encoded = gs_brain.dataset.one_hot([0, 1, 2], 3); define shuffled = gs_brain.dataset.shuffle(X, y, 42); print(split); print(groups); print(encoded); print(shuffled);
This is an initial bounded utility set, not a full data-loader framework. Stratification, streaming datasets, image loaders, data augmentation and cross-validation orchestration are not implied.
7. gs_brain.learn — classical learning and evaluation
The learn namespace combines preprocessing, binary logistic regression and evaluation metrics. The implemented estimator path uses CPU batch gradient descent, a stable sigmoid calculation, binary cross-entropy and optional L2 regularization.
| Export | Purpose | Notes |
|---|---|---|
train_test_split(X, y, test_fraction, seed?) | Paired train/test split. | Returns the four train/test arrays. |
standardize(X) | Feature standardization. | Returns the transformed data and associated scaling information as implemented. |
train_logistic(X, y, epochs, learning_rate, l2?) | Train a binary logistic-regression model. | CPU batch gradient descent with optional L2 regularization. |
predict_proba(X, model) | Predict positive-class probabilities. | Uses the trained logistic model. |
predict_logistic(X, model, threshold?) | Predict binary class labels. | Optional decision threshold. |
mean_squared_error(y, predictions) | MSE metric. | Numeric target/prediction vectors. |
mean_absolute_error(y, predictions) | MAE metric. | Numeric target/prediction vectors. |
root_mean_squared_error(y, predictions) | RMSE metric. | Square root of MSE. |
r2_score(y, predictions) | Coefficient of determination. | Returns null for a zero-variance target set. |
accuracy_score(actual, predicted) | Classification accuracy. | Compares matching label vectors. |
classification_report(actual, predicted, positive_label?) | Binary classification summary. | Precision, recall, F1 and confusion counts for the selected positive label. |
info() | Subsystem status. | Reports that broad estimator parity is not implemented. |
import gs_brain;
define X = [[0], [1], [2], [3], [4], [5]];
define y = [0, 0, 0, 1, 1, 1];
define split = gs_brain.learn.train_test_split(X, y, 0.33, 7);
define model = gs_brain.learn.train_logistic(
split.X_train, split.y_train, 1000, 0.05, 0.0
);
define probabilities = gs_brain.learn.predict_proba(split.X_test, model);
define labels = gs_brain.learn.predict_logistic(split.X_test, model, 0.5);
print(probabilities);
print(labels);
print(gs_brain.learn.accuracy_score(split.y_test, labels));
print(gs_brain.learn.classification_report(split.y_test, labels));
The implemented scope is not a broad estimator catalog. Decision trees, random forests, SVM, k-nearest neighbors, naive Bayes, clustering, cross-validation, model-selection pipelines and general multiclass classification are not claimed as available here.
8. gs_brain.autograd — scalar reverse-mode automatic differentiation
The autograd namespace implements a bounded scalar computation graph. Each created value is represented by a numeric node handle. Operations append nodes referencing their input handles; backward propagates gradients through the recorded graph. This is scalar reverse-mode autodiff, not tensor-wide automatic differentiation and not yet connected to every neural training weight.
| Export | Role |
|---|---|
reset() | Clear the current graph and release its node storage. Use between independent graphs. |
variable(number) | Create a leaf node and return its numeric handle. |
add(a, b), mul(a, b) | Create addition or multiplication nodes from valid handles. |
neg(a), pow(a, b) | Create negation or power nodes. |
exp(a), log(a) | Create exponential or logarithm nodes. |
relu(a), sigmoid(a) | Create activation nodes. |
backward(output) | Run reverse-mode gradient propagation from the selected output node. |
grad(handle), value(handle) | Read a node's accumulated gradient or forward value. |
zero_grad() | Clear stored gradients without discarding the graph. |
info() | Report graph mode, supported operations, version and node count. |
import gs_brain; gs_brain.autograd.reset(); define x = gs_brain.autograd.variable(3); define y = gs_brain.autograd.variable(2); define product = gs_brain.autograd.mul(x, y); define result = gs_brain.autograd.add(product, x); gs_brain.autograd.backward(result); print(gs_brain.autograd.value(result)); print(gs_brain.autograd.grad(x)); print(gs_brain.autograd.grad(y)); gs_brain.autograd.reset();
In this example, result = x*y + x; the expected forward value is 9, with gradients 3 for x and 3 for y. Node handles are valid only for the current graph lifetime. The implementation bounds graph size to one million nodes; reset before beginning a separate graph to avoid mixing independent calculations.
9. gs_brain.checkpoint — validated numeric-vector persistence
The checkpoint namespace saves and loads numeric parameter vectors using a versioned binary format. The format has a magic identifier, version and dtype fields, element count and checksum. Loading validates the header and checksum before returning data.
| Export | Signature | Result |
|---|---|---|
save(path, vector) | File path and non-empty finite numeric vector. | Boolean success/failure. |
load(path) | Path to a compatible checkpoint. | Numeric vector or null on invalid/unreadable data. |
info() | No arguments. | Format and supported-scope metadata. |
import gs_brain;
define weights = [0.25, -0.5, 1.75];
define saved = gs_brain.checkpoint.save("weights.gsckpt", weights);
print(saved);
define restored = gs_brain.checkpoint.load("weights.gsckpt");
print(restored);
10. gs_brain.cortex — data workspace and text utilities
The cortex namespace brings together content acquisition, text/HTML/JSON processing, file ingestion, JSONL dataset appending, token analysis, a small demonstration text baseline and a lightweight matrix/tensor helper namespace.
Data functions
| Export | Purpose |
|---|---|
fetch(url) | Fetch web content through libcurl and return a structured result. |
scrape(url) | Fetch a page and return its extracted text/result fields. |
html_text(html) | Extract readable text from HTML and decode supported entities. |
html_tags(html) | Extract HTML tag information. |
clean_text(text) | Normalize and clean text whitespace/content. |
json_text(value) | Flatten JSON-like text into a text representation for processing. |
tokenize(text) | Split text into tokens. |
word_counts(text) | Return token-frequency records. |
ingest_file(path) | Ingest a supported local file as text/data input. |
dataset_append(path, record) | Append a dataset record as JSON Lines. |
Workspace and demonstration model
workspace()returns the native workspace version and capability/status information.train(text),generate(seed_text, count?)andmodel_info()expose a small weighted-bigram text baseline.- The baseline is a compact demonstration model based on observed token transitions; it is not a transformer, neural language model or deep-learning system.
Tensor helper functions
| Namespace export | Purpose |
|---|---|
tensor.shape(matrix) | Inspect matrix dimensions. |
tensor.zeros(rows, columns) | Create a zero matrix. |
tensor.add(a, b) | Elementwise matrix addition. |
tensor.matmul(a, b) | Matrix multiplication. |
tensor.transpose(matrix) | Transpose a matrix. |
tensor.dot(a, b) | Vector dot product. |
tensor.relu(values), tensor.sigmoid(values) | Apply activation functions to numeric values. |
import gs_brain; define html = ""; define text_content = gs_brain.cortex.html_text(html); define cleaned = gs_brain.cortex.clean_text(text_content); define tokens = gs_brain.cortex.tokenize(cleaned); define counts = gs_brain.cortex.data.word_counts(cleaned); print(text_content); print(tokens); print(counts); print(gs_brain.cortex.workspace()); print(gs_brain.cortex.tensor.matmul([[1, 2]], [[3], [4]])); Native data workspace
Learning with GSVE.
11. Combined workflow example
The following example demonstrates how the namespaces can be composed: split paired data, train a binary classifier, evaluate predictions, inspect a gradient graph and persist a numeric vector. It intentionally keeps each operation explicit so that the GSVE program owns its data and training flow.
import gs_brain;
define X = [[0], [1], [2], [3], [4], [5], [6], [7]];
define y = [0, 0, 0, 0, 1, 1, 1, 1];
define split = gs_brain.learn.train_test_split(X, y, 0.25, 21);
define model = gs_brain.learn.train_logistic(
split.X_train, split.y_train, 1200, 0.05, 0.0
);
define probabilities =
gs_brain.learn.predict_proba(split.X_test, model);
define predictions =
gs_brain.learn.predict_logistic(split.X_test, model, 0.5);
print("probabilities:");
print(probabilities);
print("predictions:");
print(predictions);
print("accuracy:");
print(gs_brain.learn.accuracy_score(split.y_test, predictions));
print(gs_brain.learn.classification_report(split.y_test, predictions));
gs_brain.autograd.reset();
define p = gs_brain.autograd.variable(4);
define q = gs_brain.autograd.variable(5);
define loss = gs_brain.autograd.mul(p, q);
gs_brain.autograd.backward(loss);
print(gs_brain.autograd.grad(p));
print(gs_brain.autograd.grad(q));
gs_brain.autograd.reset();
define stored = gs_brain.checkpoint.save("parameters.gsckpt", [0.1, 0.2, 0.3]);
print(stored);
This is an API-composition illustration. Validate convergence and metric values for the data and hyperparameters you choose; the example is not a benchmark or a guarantee of model quality.
12. Capability boundaries and verification status
| Area | Current implementation | Not established by this module |
|---|---|---|
| Backend | CPU native C routines. | GPU, distributed or multithreaded execution. |
| Arrays | Checked nested-array matrix operations and selected vector reductions. | Full N-D array model, broadcasting and NumPy parity. |
| Neural | Linear regression, one-hidden-layer ReLU regression, dense forward pass, activations and loss helpers. | General layer graph, convolution, broad multi-layer training or full tensor autograd integration. |
| Optimization | SGD, momentum, Adam and gradient-norm clipping kernels. | Automatic optimizer lifecycle, schedulers and full trainer orchestration. |
| Datasets | Paired shuffle, mini-batches, one-hot labels and train/test splitting. | Complete loader ecosystem, streaming and broad preprocessing pipelines. |
| Classical ML | Binary logistic regression, standardization and regression/classification metrics. | Full scikit-learn estimator catalog, cross-validation and model-selection framework. |
| Autograd | Bounded scalar reverse-mode graph. | General tensor graph or automatic MLP weight-gradient integration. |
| Checkpoints | Versioned numeric-vector files with checksum validation. | Full model/optimizer serialization or portable model interchange. |
| Cortex | Text/data ingestion helpers, tokenization, word counts, JSONL appending and weighted-bigram baseline. | Transformer models, general deep language models or unrestricted scraping. |
The AI ecosystem plan is staged: numerical foundations, classical learning, autograd, training utilities, a broader training engine, workspace orchestration and only then optional acceleration. A feature described as planned in that roadmap must not be mistaken for an exported and verified API.
For source-level details, see the unified native C implementation, native ABI header, AI ecosystem engineering plan, AI implementation notes and manual build workflow.
Related documentation
- GSVE language reference — syntax, values, functions, loops, imports and class-like objects.
- Virtual machine reference — compiler, bytecode, frames, environments and native loading.
- Bytecode reference — instruction set and disassembly.
- Native module ABI — module initializer and value API.
- Native module catalog — other greenServeFE modules.
