Neural networks
Dense networks, native CPU and available accelerator operations, reverse mode differentiation, SGD and Adam, and concise fitted classifier pipelines.
ImplementedAner 0.1.0 or newerOne foundation. Different structures.
Aner’s native Tensor operations and reverse mode autodiff connect the model families. The architecture expresses how information moves; shape checks, numerical placement and retained model snapshots keep the experiment explicit.
Forward operations build the objective. Backward operations produce gradients. An optimizer returns the next learned snapshot.
Shapes describe samples, spatial axes, valid timesteps or graph membership. An edge list and a label selection have separate roles.
Retain the requested and effective device, precision and execution policy. Backend availability is specific to the build and hardware.
Fit returns a new model. Evaluate held out data without advancing training; retain the split, transform, seed and checkpoint identity.
Aner Neural is the built in neural network library, imported as aner.nn. It provides Float64/Float32 tensors, native CPU and optional Metal/MPS or CUDA operations, reverse mode automatic differentiation, and SGD or Adam parameter updates. Sequence primitives on CPU Float64/Float32, native Metal Float32 and native CUDA Float64/Float32 add rank one through rank eight composition, embeddings, normalization, masked token loss and attention; see native sequence and attention primitives. Aner programs describe a model through the concise classifier API or an explicit training loop; Aner's native C++ runtime performs the tensor operations.
The current library supports dense neural networks, including explicit supported CPU, CUDA and Metal/MPS replicas through ml.fit with a ParallelContext; see distributed neural training. Native CNN models add inferred shape image layers, executable vision architectures, full checkpoints, development diagrams and optional MPI replicas. Native RNN/LSTM/GRU and advanced recurrent profiles add padded sequence objectives, detached streaming state and explicit truncated training. Streaming ingestion from external datasets and additional optimizer families remain future work. Custom Transformer blocks can be composed from the supported native sequence primitives. The complete CUDA sequence backend supports Float64 and Float32 alongside CPU and Metal sequence execution. General distributed Tensor execution, contextual neural training, model sharding is not implemented; CNN and recurrent training support optional MPI/NCCL gradient collectives. Fitted classifier checkpoints and warm starts are implemented. The device backends share shape, differentiation, and explicit placement contracts; Tensor devices and performance documents requirements and matched measurements.
For native byte/BPE tokenization, end to end decoder training, full fine tuning, freezing, LoRA, checkpoints, evaluation and generation, see native language model research.
Native model workflows in development
The 0.0.7-dev.1 source adds graph neural networks and a shared CNN, recurrent and graph workflow: explicit sparse topology, typed held out evaluation, immutable minibatch updates and training phase resets. These development APIs do not change the currently published package.
Model and parameter references
Use the model directory to choose a technique and the exact model API inventory to inspect every registered overload. Each reference explains inputs, configuration variables, defaults, shapes, random/state ownership, limits and complete examples:
| Technique | Parameter and lifecycle reference |
|---|---|
| Dense Sequential / MLP classifier | Dense model parameters |
| SGD / Adam and explicit keyed loops | Optimizer parameters and state |
| CNN builders and vision architectures | CNN parameter reference |
| RNN, LSTM, GRU and advanced sequence profiles | Recurrent parameter reference |
| Native language/scientific generation | Generative parameter reference |
| KNN, K means and decision trees | KNN, K means, decision trees, under aner.ml |
Module guide and API map
Start with the concise classifier example below, then use the linked references for the level of control your experiment needs. nn describes model topology and numerical differentiation; fitting, preprocessing ownership, checkpoints and fitted evaluation use ml. Import both modules when using a fitted classifier. References are pages in this documentation hierarchy, rather than additional aner.nn.* imports.
| Task | API family | Reference |
|---|---|---|
| Configure Dense topology and initialization | nn.sequential, network .dense, .tanh, .relu, .sigmoid, .dropout, nn.mlp | Model configuration below and neural workflows |
| Fit and evaluate an immutable classifier | ml.classifier, .fit, .evaluate, .predict, .probabilities | Classifier API below and aner.ml |
| Configure batches, validation and checkpoints | ml.training, .validation, .select_best, .save, ml.load_classifier, .warm_start | Neural workflows |
| Define explicit numerical forward/backward loops | nn.parameter, arithmetic, losses, nn.backward, nn.grad, nn.sgd, keyed optimizers | Tensor API and explicit optimizer API below |
| Select and inspect native execution | nn.configure, nn.place, nn.execution, devices, precision and backend accessors | Tensor devices and workflow placement |
| Inspect bounded training observations | Dev mode and aner.viz | Development mode, visual reports |
| Use explicit supported Dense replicas | ml.fit with an enrolled context | Distributed neural training |
Runnable examples and expected results
The offline examples need the native Aner executable and no credentials or downloaded data. From the folder containing examples, check and run a concise classifier or audited mini batch workflow:
aner check examples/neural_iris_concise.aner
aner run examples/neural_iris_concise.aner
aner check examples/neural_minibatch.aner
aner run examples/neural_minibatch.anerThe online concise Iris example and mini batch example include downloadable source. Concise Iris retains source attribution, uses 120 fitting and 30 testing rows, and prints the full fitted/evaluation summary. Mini batch Iris uses 90 fitting, 30 validation and 30 final test rows, selects the best post epoch validation loss from a fixed 100 epoch horizon, and prints the partition counts followed by Boolean checks that training loss decreased and final test accuracy is in [0, 1]:
90
30
30
true
trueThese checks establish that the complete workflow runs and produces finite bounded evaluation, rather than a guaranteed accuracy level. For explicit updates use XOR below; for state restoration use the checkpoint example, saving to new files in a writable folder. Use the custom class example when implementing your own supported Tensor forward pass and loss.
Dense model example
Follow the one time installation guide to put aner on your PATH. Open a terminal in the folder containing the binary bundle's examples directory, then check and run the XOR model:
aner check examples/neural_xor.aner
aner run examples/neural_xor.anerUse the same commands on macOS, Linux, or Windows, including VS Code's terminal. No separate neural library installation is needed: aner.nn ships with Aner.
The XOR example trains on four synthetic observations, using two input features, eight hidden units with tanh, and one output with sigmoid. It computes mean squared error, runs 3,000 full batch updates at learning rate 0.5, and prints the initial loss, final loss, and four predictions. The target values are 0, 1, 1, 0, in that order. This demonstrates that gradients and parameter updates compose into a working training loop; it is not a medical data model or a benchmark for large datasets.
A recorded reference run produced these rounded results:
| Result | Value |
|---|---|
| Initial mean squared error | 0.265645 |
| Final mean squared error | 0.000346018 |
Prediction for [0, 0] | 0.011831 |
Prediction for [0, 1] | 0.980513 |
Prediction for [1, 0] | 0.980293 |
Prediction for [1, 1] | 0.021817 |
Your output should show the loss decreasing and predictions approaching the four targets. These reference values are not a guarantee of identical final decimals across platforms.
Concise dense classifier pipelines
The built in classifier API groups layer parameters and the repeated training loop into native values. It uses the same tensor kernels and autograd as the detailed examples.
import aner.dataset
import aner.nn
import aner.ml
let flowers = dataset.iris()
let split = flowers.split(test: 0.2, seed: 2026)
let network = nn.sequential(seed: 42)
.dense(inputs: 4, outputs: 8)
.tanh()
.dense(inputs: 8, outputs: 3)
let pipeline = ml.classifier(network, standardize: true, loss: "cross_entropy", optimizer: "sgd")
let fitted = pipeline.fit(split.train(), epochs: 2000, rate: 0.1)
print(fitted.evaluate(split.test()).summary())Run aner run examples/neural_iris_concise.aner. The Wine example uses 13 → 16 → 3 dimensions, 1,000 epochs, and rate 0.05. The Iris notebook separates data, topology, fitting, and evaluation into persistent cells. The older detailed Iris program retains its explicit forward/backward/update loop and visual capture calls.
| Call | Result | Meaning |
|---|---|---|
nn.sequential(seed: Int64) | NeuralNetwork | Start an empty immutable network configuration with an explicit initialization seed. |
network.dense(inputs: Int64, outputs: Int64) | NeuralNetwork | Return a configuration with a seeded dense stage; adjacent dimensions must agree. |
network.dense(inputs: Int64, outputs: Int64, initialization: String) | NeuralNetwork | Choose "seeded", "xavier" or "he"; default seeded uses scale 0.5. |
network.dense(inputs: Int64, outputs: Int64, weights: Tensor, bias: Tensor) | NeuralNetwork | Supply finite detached initial weights of shape inputs × outputs and bias of shape 1 × outputs. |
network.summary(), pipeline.summary() | String | Describe architecture, initialization, and training policy before fitting. |
network.tanh(), network.relu(), network.sigmoid() | NeuralNetwork | Return a configuration with the named activation stage. |
network.dropout(probability: Float64) | NeuralNetwork | Append elementwise inverted dropout with finite probability in [0,1). Training samples masks; prediction and evaluation bypass them. |
pipeline.dropout_seed(seed: Int64) | ClassifierPipeline | Choose reproducible dropout streams for full batch and mini batch fits. Omission automatically seeds each fresh active dropout fit and records its resolved seed. |
ml.classifier(network: NeuralNetwork, standardize: Bool, loss: String = "cross_entropy", optimizer: String = "sgd") | ClassifierPipeline | Configure preprocessing, optional loss (default "cross_entropy"), and optional optimizer ("sgd" or "adam"). |
pipeline.fit(training: Dataset, epochs: Int64, rate: Float64, progress: Bool = false) | FittedClassifier | Return an independent fitted snapshot using initial or warm start parameters and full batch SGD or Adam, optionally reporting bounded measured progress and fixed horizon ETA. |
pipeline.warm_start(model: FittedClassifier) | ClassifierPipeline | Return a compatible plan using the prior fitted weights and fixed scaler; the prior model remains unchanged. |
fitted.weights(layer: Int64), fitted.bias(layer: Int64) | Tensor | Return detached copies using zero based Dense layer indices, excluding activations and dropout. |
fitted.save(path: String) | Unit | Save a versioned fitted checkpoint to a new file in an existing directory. |
ml.load_classifier(path: String) | FittedClassifier | Validate and load architecture, fitted parameters, scaling, schema, and provenance. |
fitted.evaluate(testing: Dataset) | EvaluationReport | Reuse the fitted preprocessing and evaluate the supplied rows without refitting. |
fitted.summary(), report.summary() | String | Return readable configuration, results, and dataset provenance; the evaluation summary includes the fitted summary. |
fitted.initial_loss(), fitted.training_loss(), fitted.training_accuracy() | Float64 | Read detached training metrics without printing the full report. |
report.loss(), report.accuracy(), report.rows() | Float64, Float64, Int64 | Read evaluation metrics and evaluated row count. |
fitted.predict(input: Dataset), fitted.probabilities(input: Dataset) | Tensor | Apply fitted preprocessing and return class IDs or probabilities for a compatible Dataset. |
Receiver builders have qualified forms nn.dense(network, inputs, outputs), nn.tanh(network), nn.relu(network), nn.sigmoid(network) and nn.dropout(network, probability); each returns a new network. nn.dense also has the explicit initialization and weights/bias overloads in the table.
Dropout is an optional stage, usually placed after a hidden activation and before the next Dense stage. It temporarily zeroes activation values during training; it does not delete neurons or weights. Probability 0.2 gives each activation a 20% chance of being dropped, rather than selecting exactly 20% of a layer. Retained activations are scaled by 1 / (1 - probability). Prediction, validation, and detached final training metrics use the complete network. Zero probability is an identity operation. Development recording does not control training/evaluation behavior.
let network = nn.sequential(seed: 42)
.dense(inputs: 4, outputs: 16, initialization: "he").relu()
.dropout(probability: 0.2)
.dense(inputs: 16, outputs: 3, initialization: "xavier")
let plan = ml.classifier(network, standardize: true, optimizer: "adam")
.dropout_seed(seed: 2026)The initialization seed, mini batch shuffle seed, and dropout seed have separate purposes. Set .dropout_seed(seed) once on the immutable classifier plan; the trainer derives new masks for each training update and layer. Repeating a fresh fit with the same seed and unchanged inputs, configuration, and numerical environment reproduces those streams. Omit .dropout_seed(...) for a new automatically seeded run. Its fitted summary and checkpoint retain the resolved exact integer seed and stream protocol. Automatic seeding happens once per fresh active dropout fit, never during prediction or on each batch. A warm start restores the saved stream position; a conflicting explicitly chosen seed is rejected. Networks without active dropout preserve their existing behavior. See the runnable dropout example and randomness contracts.
Use all three imports above: aner.dataset for teaching data and partitions, aner.nn for topology, and aner.ml for fitted classification. The names are library APIs, not additional language keywords. Instance calls are resolved from the receiver's static type. Named arguments can make positional configuration clearer without changing type checking. A leading . on the next line continues a method chain.
The optional loss argument accepts exactly "cross_entropy" or "mse", with "cross_entropy" as the default for existing two argument calls. Cross entropy averages one hot cross entropy over rows from raw logits. MSE computes nn.mse(nn.softmax(logits), one_hot_targets): the sum of squared probability errors divided by rows × classes. The configured loss is used for every training update, initial and final training loss, and evaluation loss. Summaries identify the selected loss. Accuracy and predictions still use the highest scoring class.
To choose MSE, change only the classifier configuration:
let pipeline = ml.classifier(network, standardize: true, loss: "mse")
let fitted = pipeline.fit(split.train(), epochs: 2000, rate: 0.1)Keep the network's final Dense layer as raw logits; the classifier applies softmax internally for MSE, so do not add a softmax layer. The MSE Iris program and MSE Iris notebook use this policy with the same split, topology, epochs, and rate as the concise cross entropy example. Different losses have different scales and gradients, so their loss values are not directly comparable and their convergence can differ at the same learning rate. The optional argument requires a compatible native runtime and editor integration with loss signatures and development inspection. Updating only the extension does not update the executable.
Configurations and fitted snapshots are separate immutable values. dense and activation methods return a new configuration; they do not mutate an existing let binding. Ordinary fit starts from the network initialization and learns standardization solely from the supplied training features. pipeline.warm_start(model) instead returns a plan that starts from that immutable fitted snapshot and reuses its scaler without refitting. Both forms allocate independent trainable parameters and leave earlier fitted values unchanged. Test features reuse exactly the fitted statistics. This protects that preprocessing boundary; it cannot determine whether the caller chose medically independent patients or a valid study partition.
The trainer uses the configured loss and SGD or Adam, through the legacy full batch overload or immutable ml.training mini batch settings. Plans capture a requested device, precision, and preserve/adapt/fast execution policy. CPU and CUDA support Float64/Float32; Metal/MPS supports native Float32. Preserve on Metal/MPS with Float64 uses reported CPU Float64 fallback. Numerical state is prepared once after CPU Float64 preprocessing. SGD remains the default; Adam uses beta1=0.9, beta2=0.999, epsilon=1e 8 and retains moments and update count across compatible warm starts. Default initialization uses seeded random weights with scale 0.5 and zero biases; the custom Dense overload accepts a finite weights/bias pair instead. Epoch count and finite positive learning rate are explicit. The optional optimizer string defaults to "sgd"; names other than "sgd" and "adam" raise R2701. A named optimizer: "sgd" may be supplied without a loss argument. Dense stages use consecutive seeds base_seed + dense_index, where the first Dense stage has index zero and activations and dropout do not increment the index. Seed overflow is rejected. Default trainable parameters are created when fit runs. Custom initialization tensors are copied and detached when the Dense configuration is created. The architecture must start with a Dense stage and end with Dense raw logits; its input width must match the dataset feature count and its output width must match the dataset class count. Copies of a fitted value share its immutable snapshot efficiently; fitting another model does not mutate that snapshot. The low level Tensor API still has shared gradient metadata, as documented below.
Summaries preserve topology and per layer seeds, training configuration and metrics, actual device/precision/backend information, fitted scaling statistics, source hashes, exact source row IDs, and dataset attribution. Evaluation checks feature names, units, column order, feature count, and class names/order against the fitted schema. Legacy full batch evaluation reports overlap with training rows for compatibility. Configured mini batch evaluation instead rejects overlap with retained fitting/preprocessing membership, and final test views cannot reuse earlier validation selection membership. Raw Tensor extraction discards Dataset identity, requiring explicit boundary audits in custom loops. Partition views retain their seed, fractions, roles, and source row fingerprints; keep the source with the output as well. A fixed seed supports repeatability in the same build and environment; it does not guarantee bitwise identity across compilers or future devices. Saved notebook output is not a serialized fitted model or checkpoint.
Training is bounded by 32 stages, 1,000,000 trainable parameters, 100,000 epochs, and 500,000,000 estimated training work units, in addition to the tensor/graph limits below. The work estimate is a conservative guard, not elapsed time, measured FLOPs, or a process memory quota. Raising the interpreter's step limit does not raise these library limits. Library failures use source located R2701 diagnostics. Configured mini batch training uses compact sources and lazy schedules, admits up to 100,000 updates and one trillion estimated work units, and retains the individual Tensor/graph bounds. Streaming notebook output during a running cell and automatic user defined layer registration remain future work. Development notebooks provide completed cell variables, captures, and loss views; see development and production.
Additional classifier accessors
The aner.ml module guide lists every classifier/configuration accessor, including fitted center, scale, training_row_ids, measured training_seconds, and evaluation row_ids. Predictions are detached N × 1 class IDs; probabilities are detached N × C values whose columns follow the fitted class vocabulary. Both require a compatible Dataset and reuse the fitted scaler. Dataset extraction into bare Tensors does not preserve the classifier's schema or source membership checks.
Create a visual training report
aner run examples/neural_iris_concise.aner --debug-viz reports/iris-conciseChoose a new output directory. For variable/object observations as well, run aner examples/development_nn.aner --dev reports/nn-first and start at inspection.html. The CLI records the native training graph after backward and before each selected update: epochs 0, 1, 2, every max(100, ceil(epochs / 60)) epochs, and the final trained state. This keeps one fit within the recorder's 64 snapshot limit; the Iris example records every 100 epochs. Add --debug-values only when you want bounded raw tensor/gradient values in the report. Capture does not change the model's numerical updates. This is an offline HTML/JSON/text report, not a live notebook chart.
Multiple fits are recorded as separate series with local epoch steps and capture phases. The loss chart does not connect different fits into one continuous curve. All series share the bounded 64 snapshot budget; later fits may have fewer stored observations when the budget is exhausted. Manual viz.capture calls use their own strictly increasing step series. The detailed Iris example remains useful for choosing your own viz.capture points. Dataset attribution travels with recorded training reports.
Custom initialization and fitted checkpoints
let network = nn.sequential(seed: 42)
.dense(inputs: 4, outputs: 8,
weights: nn.random(4, 8, seed: 7, scale: 0.25),
bias: nn.zeros(1, 8))
.tanh()
.dense(inputs: 8, outputs: 3)
let pipeline = ml.classifier(network, standardize: true,
loss: "cross_entropy", optimizer: "sgd")
print(network.summary())
print(pipeline.summary())
let fitted = pipeline.fit(split.train(), epochs: 400, rate: 0.1)
fitted.save("iris.anermodel")
let restored = ml.load_classifier("iris.anermodel")
let resumed = pipeline.warm_start(restored)
.fit(split.train(), epochs: 100, rate: 0.1)This fragment follows the imports and split from the classifier example above. Save to a new file: checkpoints never overwrite an existing path or create missing parent directories. weights and bias are provided together, with finite values and exact shapes. A Tensor literal can supply manually chosen weights.
A warm start validates architecture, loss, standardization policy, feature/class schema, and parameter shapes. It reuses the prior training derived center/scale even when the new training rows differ; original scaler source identity and rows remain distinct from the new fit's rows. The returned model reports the new fit's epochs/rate rather than an invented cumulative history. SGD has no additional momentum state to restore.
All new fitted Dense saves use the bounded version 7 binary checkpoint, including default CPU Float64 fits and networks without active dropout, retaining architecture, initialization policy, detached fitted parameters, scaling, schema, metrics, source metadata, exact row IDs, optimizer state, and cumulative training updates. Active dropout additionally retains its exact seed, origin and stream protocol. Versions 1 to 6 remain readable with their original metadata limits; missing legacy cumulative update history is marked partial. It excludes raw feature/target rows and autograd graphs. Loading validates version, dimensions, finite values, positive scales, schema consistency, bounds, and trailing bytes. The payload limit is 64 MiB; failures use R2701.
For s stages, p copied or serialized parameters, r retained source row IDs, and m metadata bytes, custom Dense creation costs O(inputs × outputs + outputs + s) time and extra space; summaries cost O(s) time/output space; warm start configuration costs O(s) validation time and O(1) shared storage; weight/bias extraction costs O(selected elements) time and extra space; save/load costs O(p + r + m) time and space. These bounds exclude disk latency and the ordinary training graph. See the model state guide and the runnable checkpoint example.
Tensor operations and differentiation
Network parameters, features, predictions, and scalar objectives use native Tensor values. For neutral inspection through the neural namespace, nn.rows(value: Tensor) and nn.cols(value: Tensor) return Int64 dimensions; nn.item(value: Tensor) reads a 1 × 1 Float64 scalar; nn.value(tensor: Tensor, row: Int64, column: Int64) reads a zero based bounded element. nn.zeros(rows, cols) and nn.random(rows, cols, seed, scale) construct the same values as their aner.tensor counterparts. The Tensor reference defines construction, shape and dtype validation, matrix operations, activations, loss operations, reverse mode differentiation, parameter updates, device placement, and numerical limits. Network and fitted classifier APIs are defined on this page.
Built in modules and current scope
import aner.nn; selects a built in module and exposes the nn namespace. It does not load external packages. Third party native plugins, module aliases, package manifests, dependency resolution, version negotiation, and stable extension ABIs are not supported.
Use the built in sequential/classifier values for common dense classification, or ordinary Aner functions and explicit training loops for lower level experiments. The portable native CPU path is single threaded. A compiled CPU provider may manage internal worker threads; eligible macOS builds use Apple Accelerate for matrix products. Optional native CUDA builds support Float64/Float32 Tensor execution; Metal/MPS supports Float32, with precision policy controlling explicit CPU fallback or adaptation. Supported Dense replica training uses the separate ml.fit boundary with an explicit execution context, sample weighted Float64 host reduction and one canonical CPU optimizer; it does not provide a general cluster Tensor device.
Keep the data schema and partitions, preprocessing, model architecture, seeds, optimization settings, software version, and metrics with your experiment. Fitted classifier state can be saved, validated, loaded, and used for a compatible warm start. General Tensor/object checkpoints and KNN/K-means serialization remain future work. The built in teaching catalogue and preprocessing are documented in Aner datasets; aner.data reads external CSV files with explicit table to tensor conversion.
Training observations
The visual training example imports aner.viz and captures the loss graph after backward at selected steps. Its offline report connects the model topology to recorded values, gradients, and loss history. See visual training reports for small neuron views, bounded summaries, and headless execution. Captures add overhead but do not alter numerical tensors, gradients, or parameter updates.
Multiclass classification
The Iris milestone adds nn.softmax(value: Tensor) -> Tensor, nn.cross_entropy(logits: Tensor, targets: Tensor) -> Tensor, nn.argmax(value: Tensor) -> Tensor, and nn.accuracy(scores: Tensor, labels: Tensor) -> Float64.
Softmax normalizes each row and supports differentiation. Cross entropy accepts raw logits and matching constant, exact one hot targets; its scalar loss is averaged over rows. It combines normalization and logarithms stably rather than taking the log of rounded softmax probabilities. Logit gradients are (probabilities - targets) / rows. Differentiable targets and soft label distributions are rejected in this first version. Nonrepresentable results remain errors.
Argmax returns a detached rows × 1 Tensor of zero based class IDs in the input precision and device, choosing the first index on ties. Accuracy accepts one finite integral in range class ID per row and returns the correctly classified fraction; scores may be logits or probabilities. These metrics do not add autograd edges.
Run the Iris classifier, using the licensed dataset module, for a three class example with training only scaling, held out evaluation, and visual captures.
Related modules
Neural architecture, differentiable losses, and optimization remain in aner.nn. Classical fitted models and the new classifier pipeline live in aner.ml; common evaluation lives in aner.metrics. The Iris neural example now uses metrics.accuracy(nn.argmax(scores), labels), the same label contract as KNN. Existing nn.accuracy(scores, labels) is unchanged. metrics.mean_squared_error is a detached evaluation scalar, whereas nn.mse is a differentiable loss tensor.
The neutral aner.tensor module offers creation and inspection of the same native Tensor values. See classical ML APIs for KNN, K means, and shared evaluation metrics.
Training configuration and placement
Use nn.devices() to inspect actual runtime capabilities and tensor.dtype(), tensor.device(), and tensor.backend() to verify Tensor execution. nn.configure(device, precision, policy) selects a run/session profile, and .place() applies it before parameter creation. nn.execution() reports requested and actual settings. Strict .to("cuda") preserves Float64 or Float32; .astype("Float32").to("mps") selects native Metal/MPS Float32. .on(device, precision, policy) selects an immutable classifier profile. An unavailable explicitly requested accelerator fails. ROCm remains unavailable. General cluster placement through nn.configure or Tensor .to("cluster") is unsupported. Explicit enrolled Dense replicas instead use parallel.cluster and ml.fit, as defined in distributed neural training. Dense can select initialization: "xavier" or "he" in addition to the original default and custom tensors. fit(..., progress: true) prints measured CLI progress; fitted.training_seconds() reports duration. All new version 7 checkpoints retain requested/effective precision and device policy, Adam state, cumulative training updates, and source device provenance; they load portably on CPU in their actual saved precision. Versions 1 to 6 remain readable with their historical metadata limits. See the full workflow and complexity reference for exact contracts, classes with custom forward/loss, Dev versus Prod, platform requirements, and runnable source/VS Code/Jupyter examples.
Mini batch and explicit optimizer API reference
| Native call | Result and contract |
|---|---|
nn.mlp(inputs: Int64, hidden: List, outputs: Int64, seed: Int64) | NeuralNetwork; positive Int64 hidden widths, Xavier Dense stages and hidden ReLU, raw output logits; an empty hidden List produces one Dense stage. |
nn.xavier(rows: Int64, cols: Int64, seed: Int64) | Detached CPU Float64 Tensor; finite seeded weights in the Xavier uniform interval for those dimensions. |
nn.optimizer(name: String, rate: Float64) | Optimizer; exactly "sgd" or "adam", finite positive rate. |
nn.update(optimizer: Optimizer, parameter: Tensor, key: String) or optimizer.update(parameter, key) | New trainable leaf Tensor; valid current gradient, same shape/precision/device for each stable unique parameter key. |
nn.reset(optimizer: Optimizer) or optimizer.reset() | Unit; discard keyed optimizer history explicitly. |
nn.summary(network: Optimizer) or optimizer.summary() | String; configured optimizer and tracked state. |
nn.clock() | Float64; monotonic seconds for elapsed time differences, rather than a wall clock timestamp. |
nn.memory() | String; JSON native tracked host/device/current/peak buffer byte report. |
nn.reset_memory_peaks() | Unit; reset peaks to currently retained tracked storage, without freeing buffers. |
nn.backend_details() | String; compiled/runtime backend details. |
The qualified nn.summary overload retains the native label network even for an Optimizer; optimizer.summary() avoids that receiver label.
Optimizer objects retain mutable keyed history even though parameter numerical values remain immutable. Copies of an optimizer share that history; retain the same optimizer across updates and keep one stable key per parameter. Call nn.backward once for the loss, update each parameter from that completed gradient, retain each returned leaf, and recompute the next forward pass. Adam uses beta1 0.9, beta2 0.999 and epsilon 1e 8; configurable beta values, clipping and schedules remain future work. Each optimizer key is NUL free and from 1 through 1,024 UTF-8 bytes. A single optimizer admits at most 4,096 keys, 1,000,000 total keyed parameter elements and 100,000 updates per key. Invalid topology/MLP widths use R2701; invalid Tensor or explicit optimizer operations use R2001.
The memory report counts tracked native numerical buffers, rather than total process RSS; graphs, provider workspace and other allocations can add memory. Synchronize a device before timing native accelerator work. Full resource admission and operation complexity are defined in Tensor, devices, and neural workflows.
nn.mlp(inputs, hidden: List, outputs, seed) builds a Xavier Dense network with hidden ReLU. ml.training(epochs, batch, rate, seed).validation(data).select_best(enabled) configures complete shuffled epochs and held out post epoch metrics; pass it as pipeline.fit(training, config: config, progress: true). nn.optimizer(name, rate) exposes keyed SGD/Adam updates to explicit Tensor loops. Version 7 fitted checkpoints retain mini batch epoch, exact source order, batch/shuffle settings, cumulative fitting/selection provenance, optimizer state and cumulative training updates. Best epoch restoration also restores its dropout stream position. The neural workflow defines API constraints, selected epoch continuation, phases, resource reporting, and complexity. The MNIST Dense benchmark supplies complete concise, functional, and class based programs and notebooks.
Explicit normal initialization
aner.random provides opt in Philox normal draws for custom weights. The native initialization example fills a typed Float64 array from an explicitly seeded generator, converts it to a Tensor, and supplies zero bias through the existing Dense overload. Existing initialization and dropout sequences, default zero biases and checkpoint continuation recipes are unchanged. This public sampler does not silently replace a model's established RNG or change its accelerator reproducibility contract.
Convolutional and recurrent development APIs
Aner 0.0.4 or newer includes native CPU CNNs and RNN, LSTM, GRU and advanced sequence models. Use the matching editor integration. Current Mac packages also include Metal/MPS; current Linux and Windows packages do not include CUDA or MPI/NCCL. Those optional source backends require separately prepared compatible runtimes. These model families share native Tensor autodiff, explicit placement and checkpoint contracts.
See the complete callable index for the native module and method name catalogue.