Development and production
Inspect bounded variables, objects, loss, and gradients, configure neural initialization, and save or resume fitted models with the same production computation.
ImplementedAner runs in production mode by default. Development mode records bounded observations of variables, objects, collections, neural operations, training loss, and available gradients. Both modes use the same type checks, numerical kernels, seeds, shape checks, and resource limits. Development observes the computation; it does not choose a different training algorithm.
The -dev text in aner --version identifies the development release of the interpreter. It does not mean that a program is recording observations.
Module guide
Import aner.dev for source level observation controls. CLI --dev also enables automatic recording without requiring that import; aner.viz is the separate module for explicit scalar loss graph captures. The observation helpers do not mutate the inspected value or run its user methods.
| Start here | Continue with |
|---|---|
| Observe an ordinary collection | Explicit observation points, then the linked list program |
| Control the amount recorded | Complete API reference and recording budgets |
| Inspect neural training | Neural network inspection and visual training reports |
| Work across notebook cells | Aner notebooks, Jupyter integration and the notebook inspection reference |
The module has four function names, with two progress overloads. Notebook panels and report viewers are tooling around these observations; they are not additional aner.dev imports.
Run one source file
aner examples/development_nn.aner --dev reports/nn-first
aner examples/development_nn.aner --prodOmitting --prod also selects production. run remains optional. Use a new report directory for every development run. Aner refuses to replace an existing directory, file, or symlink. --dev and --prod cannot be combined. Existing --debug-viz remains available for the older neural only reporting workflow.
Development creates these files:
| File | Purpose |
|---|---|
inspection.html | Start here: variable table, named observations, object reference diagrams, and loss by fit. |
inspection.json | Typed, bounded snapshots and run identity for tools. Int64 values use exact decimal strings. |
index.html | Interactive neural topology, captured steps, activations, and available gradients. |
trace.json | Recorded tensor graph, loss captures, shapes, statistics, and dataset attribution. |
summary.txt | Text summary of neural captures. |
Open inspection.html directly in a browser. No server or network connection is needed. Add --debug-values when inspecting small teaching tensors or neuron values:
aner examples/development_nn.aner --dev reports/nn-values --debug-valuesShapes and statistics are recorded by default. Raw tensor arrays and gradients are opt in and bounded. Scalar values, String previews, and ordinary object/collection contents already have bounded previews. Reports are observations from that execution; editing the source does not update them.
A source located runtime failure produces a partial development report containing the observations captured before the failure and an error status. Syntax/type errors found before CLI execution have no runtime observations. A notebook runtime failure records the historical state before clearing the native session; a static failure preserves prior session variables. Neither report replays or rewinds the program.
Explicit observation points
import aner.dev
let values = List(10, "hello", 1.5)
dev.capture("Initial values", values)
let removed = values.remove_at(1)
dev.capture("After removing the String", values)Run the complete linked list program with aner check examples/development_linkedlist.aner, then aner examples/development_linkedlist.aner --dev reports/list-first. Its output is true followed by 2; the report captures shared node references and mutations. The same source produces the same ordinary output with --prod. The report directory must be new. See the complete API reference for recording controls and manual progress.
Development also observes assignments, object field updates, and collection mutations automatically. An explicit capture gives an important moment a useful name. References have stable heap IDs within the session, so shared values and cycles can be recognized without recursively following a cycle forever. Captures do not invoke user methods or getters and do not retain live objects or differentiation graphs.
In production, automatic inspection and report generation are disabled. dev.capture still evaluates its arguments normally. Guard an expensive diagnostic expression if it should disappear from production work:
if dev.enabled() {
dev.capture("First Dense weights", fitted.weights(layer: 0))
}This also avoids making the detached parameter copy when recording is off. The same principle applies to diagnostic dataset transformations or extra model evaluations.
API reference
| Signature | Result and contract |
|---|---|
dev.enabled() -> Bool | Whether this execution has development recording enabled; use it to guard expensive diagnostic calculations. |
dev.capture(label: String, value: Any) -> Unit | Store a bounded snapshot under an explicit label. Any Aner value may be supplied; opaque credential/service handles remain opaque. The label and value expressions are evaluated in both modes. |
dev.automatic(enabled: Bool) -> Unit | Enable or disable broad assignment/mutation capture for the current execution. Default is true; a notebook setting persists until session reset. Explicit captures, fit/progress observations and final global previews remain available. |
dev.progress(epoch: Int64, epochs: Int64, loss: Float64, accuracy: Float64, seconds: Float64) -> Unit | Record caller supplied training loss, held out accuracy and elapsed seconds in the manual progress series. No training or evaluation is performed by this call. |
dev.progress(epoch: Int64, epochs: Int64, loss: Float64, accuracy: Float64, seconds: Float64, validation_loss: Float64) -> Unit | The same record with a separate validation loss. |
When recording is active, progress requires epochs > 0, 0 <= epoch <= epochs, finite loss and accuracy, 0.0 <= accuracy <= 1.0, finite nonnegative seconds, and finite validation loss when supplied. Invalid progress raises source located R2101. The caller computes the actual row weighted online loss and held out measurements; the recorder does not infer epoch counts, validate their scientific provenance, or convert percentages to fractions. In production, capture and progress observation are no ops after ordinary argument evaluation. Static imports, types and named labels remain checked in both modes.
For a busy loop, select intentional observations:
import aner.dev
// Complete small program; no neural module or dataset is required.
dev.automatic(false)
let values = List(10, 20, 30)
dev.capture(label: "Before removal", value: values)
let removed = values.remove_at(1)
dev.capture(label: "After removal", value: values)
print(values.len()) // 2Save as observe.aner, run aner check observe.aner, then aner observe.aner --dev reports/observe-first. Open reports/observe-first/inspection.html; run aner observe.aner --prod to compare ordinary output. Use the notebook guide for session reset and observation freshness.
CNN architecture inspection
Native CNNModel values support dev.capture("CNN architecture", model) before fitting. Development reports draw bounded architecture blocks and residual edges without allocating weights or running a forward pass. model.diagram() returns full Mermaid source. Production and development use identical native training kernels and model state; see CNN models.
Neural network inspection
import aner.dataset
import aner.nn
import aner.ml
import aner.dev
let split = dataset.iris().split(test: 0.2, seed: 2026)
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)
print(fitted.evaluate(split.test()).summary())The architecture builder returns immutable configurations. network.summary() describes layers, shapes, parameter counts, seeds, and custom initialization before training. pipeline.summary() adds the normalization policy, loss, and optimizer. Standardization is fitted only on the supplied training rows; evaluation reuses those statistics.
weights must have shape inputs × outputs and bias must have shape 1 × outputs, with finite Tensor values in the provided precision. Both optional custom tensors are supplied together; they are detached into independent initialization storage. Omitting them retains the existing seeded scale 0.5 and zero bias initialization. An ordinary Tensor literal can replace nn.random when manually selecting weights.
Loss accepts "cross_entropy" or "mse"; optimizer accepts "sgd" or "adam". Both arguments are optional, and optimizer: "sgd" can be given without an explicit loss. Unsupported optimizers produce a source located error. The trainer uses full batch SGD or Adam: plans resolve their preserve/adapt/fast profile before training. CPU and CUDA support Float64/Float32; Metal/MPS supports native Float32. Preserve on Metal/MPS with Float64 uses reported CPU Float64 fallback. Features, targets, parameters, gradients, and optimizer moments use the effective precision/device consistently. Other optimizer settings and layer kinds require separate implementations and tests. See Tensor devices and performance.
The automatic fit captures include the initial forward/backward state, selected intermediate observations, and the final trained evaluation. Each fit has a separate series identity and local training step. Captures label whether they describe a state after backward before an update or the final state. Captured graph loss is the scalar root of that graph; diagnostic batches and phases may differ between captures. It is separate from row weighted online epoch loss and held out validation metrics in measured progress. Separate fits are not joined into one continuous loss curve. Manual viz.capture observations form their own series.
Use the complete source example, the development notebook, and the neural reference.
Save, load, and continue training
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)Save to a new file in an existing directory. Saving does not overwrite a file or create missing parent directories. Paths are relative to the program/session working directory.
| Signature | Result and contract |
|---|---|
network.dense(inputs: Int64, outputs: Int64, weights: Tensor, bias: Tensor) | New NeuralNetwork with validated custom initialization. |
network.summary(), pipeline.summary() | String describing configuration before fitting. |
fitted.weights(layer: Int64), fitted.bias(layer: Int64) | Independent detached Tensor copies; zero based Dense indices ignore activation stages. |
fitted.save(path: String) | Unit; serialize a versioned fitted checkpoint into a new file. |
ml.load_classifier(path: String) | FittedClassifier; validate and reconstruct a fitted snapshot. |
pipeline.warm_start(model: FittedClassifier) | New ClassifierPipeline sharing an immutable fitted starting point. |
A checkpoint retains architecture, detached fitted parameters, loss/optimizer configuration, fitted center/scale, feature/class schema, training metrics, source metadata, and exact source row IDs. When continuing on different compatible rows, original scaler source identity and rows remain distinct from the new training rows. Raw data features/targets and differentiation graphs are not saved. The file is a versioned binary format, not Aner code.
Warm starting validates architecture, loss, standardization policy and input schema. It reuses the prior weights and fitted scaler, without refitting normalization; the previous fitted value remains unchanged. Epoch/rate fields describe the current fit call, while cumulative training updates are retained separately from optimizer steps. SGD has no persistent moments. A compatible Adam warm start resumes its moments and step. Changing optimizer resets its state while retaining the cumulative training update identity and dropout stream position.
All new fitted Dense saves use version 7, including default CPU Float64 fits and networks without active dropout. The snapshot retains requested/effective execution policy, source device provenance, optimizer state and cumulative training updates. Configured mini batch fits also retain exact source order, batch/shuffle schedule and fitting/preprocessing/validation lineage. Active dropout retains probabilities, resolved seed and origin, versioned mask protocol and the selected epoch stream position. An explicitly conflicting dropout seed is rejected. Exact replay requires unchanged implementation, backend, precision, data/order, batch schedule, rate and seeds.
Versions 1 to 6 remain readable with their historical metadata limits: version 1 has no duration or Adam moments; version 2 adds duration and optimizer state; version 3 adds Float32 and source device precision; version 4 adds requested/effective execution policy; version 5 adds complete mini batch schedule and membership provenance; version 6 adds replica execution provenance. Legacy files contain no dropout state. Where cumulative update history cannot be reconstructed across a legacy optimizer reset, the summary marks it partial. Loading restores parameters and Adam moments on CPU in saved actual precision. Select an explicit plan before warm starting; reported precision conversion cannot recover discarded bits. Inference uses the saved normalization exactly.
Checkpoint parsing checks version, bounds, shapes, finite values, positive scales, schema consistency, and trailing bytes. The serialized payload is limited to 64 MiB. Failures produce R2701. See the runnable checkpoint example; run it in a fresh working directory because it creates iris.anermodel.
Complexity of model state operations
Let s be the number of stages, p the parameter elements copied or serialized, r retained training/scaler source row IDs, and m metadata bytes. Space below is additional to an existing model.
| Operation | Time | Additional space |
|---|---|---|
| Custom Dense initialization | O(inputs × outputs + outputs + s) | O(inputs × outputs + outputs + s) |
| Configuration summary | O(s) | O(s) output |
warm_start configuration | O(s) validation | O(1) shared starting snapshot/configuration handle |
weights(layer) | O(selected weight elements) | O(selected weight elements) |
bias(layer) | O(outputs) | O(outputs) |
| Checkpoint save/load | O(p + r + m) | O(p + r + m), subject to payload limits |
Checkpoint parameters include custom initialization tensors when the configuration retains them, alongside the fitted tensors. Fitting still allocates independent trainable parameters and its ordinary training graph. Warm start does not retain the earlier training graph. These bounds do not describe disk latency or total process RSS.
Inspect a linked list
aner examples/development_linkedlist.aner --dev reports/linked-listThe example appends mixed values, prepends a Float64 node, and removes the String node. Named captures show the reachable Node objects after each operation. The reference diagram distinguishes the list's head, each node's next, shared references, and node payloads. Its final length is the same in production and development.
The linked list notebook separates those operations into cells. Automatic mutation observations also work with built in List, Dictionary, Set, Array<T>, DynamicArray<T>, and NDArray<T>. Typed array previews show dtype, length, capacity, sorted status for one dimensional arrays, and up to 16 live elements. NDArray also shows shape, element strides, and shared storage identifiers; see multidimensional inspection. The data structure index links each type to its separate method and time/space complexity reference.
Development inside VS Code notebooks
Aner notebook controls include Dev, Prod, and Inspector. This runtime setting is separate from the shared-variables/independent-program execution setting.
- Choose Dev and rerun setup cells. Changing the runtime mode clears/cancels the current native session and invalidates observations; it does not run cells automatically.
- Open Inspector to see typed globals, object references, named observations, and captured loss after a cell completes.
- Use Aner: Open Development Training Report for the corresponding recorded topology and gradients.
- When ready, choose Prod, save the notebook, and rerun setup and training.
Development mode is saved as aner.runtime_mode: "development" in .anernb metadata. Missing metadata defaults to production. Set aner.notebook.developmentValues when bounded raw neuron/tensor values are needed; it defaults to false.
The Inspector identifies the completed execution it represents. Source edits mark observations stale; reset, stop, timeout, runtime failure, or changing modes invalidates live state. A later evaluation cell can preserve the last training view as explicitly historical, with its originating execution number. The variable table represents the current completed cell. The panel does not evaluate user expressions to inspect a value. There is no pause/step debugger or variable editing through the panel.
Jupyter notebooks
The optional Aner Jupyter integration executes .ipynb notebooks through the native session protocol. Select the Aner kernel in a configured notebook application and open the development example.
Use these directives in separate control cells:
%aner dev
%aner dev values
%aner variables
%aner reset
%aner prodMode changes and reset clear native session state. Development observations include variables, object references, per fit loss, topology summaries, and measured progress after each completed cell. The current transport buffers output until the cell returns. Pause/step debugging and live notebook streaming are not implemented.
Observation profiles and sampling
Development recording defaults to deep for compatibility with existing runs. Choose a lower cost profile when only progress or variable metadata is needed. Production remains the default runtime mode; selecting a profile does not enable Development by itself.
| Profile | Recorded observations |
|---|---|
metrics | Scalar training progress and explicit scalar dev.capture checkpoints. Broad automatic capture, object inspection, global previews and neural graphs are intentionally disabled. |
inspect | Bounded variables, collections, objects and Tensor shape/dtype/device metadata. Tensor statistics, raw tensor values/gradients and neural graphs are intentionally disabled. |
deep | Existing bounded inspection, Tensor statistics and neural graph captures. Raw tensor values/gradients still require --dev-values, --debug-values, or the notebook values opt in. |
For example, run aner example.aner --dev reports/metrics-first --dev-profile metrics --dev-progress-every 5, or add --dev-profile inspect --dev-every 10 to a Development invocation. A values opt in combined with metrics or inspect is rejected before execution. Tensor metadata only inspection avoids statistics scans and device readback; scalar progress still costs work, and a diagnostic expression passed to dev.capture is still evaluated normally.
Sampling and budget flags apply to the recording session. Existing response framing is unchanged. --dev-every N samples automatic observation opportunities; it does not sample explicit checkpoints. --dev-progress-every 1 preserves the native bounded progress schedule; it does not request every epoch of a long fit. Values greater than one request every Nth epoch plus initial/final opportunities when recording is enabled and budgets permit. --dev-graph-every 0 keeps native automatic graph selection; a positive value requests an automatic graph cadence. Recording omissions caused by profile, zero budgets or sampling are counted separately from exhausted budget drops and history replacement.
| CLI flag | Allowed value / default |
|---|---|
--dev-every, --dev-progress-every | Positive integer; default 1. |
--dev-graph-every | Nonnegative integer; default 0 (native automatic cadence). |
--dev-captures, --dev-capture-bytes | 0..64 records / 0..131072 bytes; default maxima. |
--dev-progress-records, --dev-progress-bytes | 0..64 / 0..65536; default maxima. |
--dev-graph-records, --dev-graph-bytes | 0..64 / 0..262144; default maxima. |
--dev-globals, --dev-global-bytes | 0..128 / 0..65536; default maxima. |
--dev-preview-items | 0..16; default 16. |
--dev-datasets, --dev-dataset-bytes | 0..64 / 0..65536; default maxima. |
A zero record or byte budget disables that channel. preview-items controls bounded container previews and the Inspector's raw Tensor preview size, at most 16 cells; neural graph nodes retain their separate raw cell export limits (1024 cells per tensor and 8192 shared value/gradient cells per capture). Configured budgets can exceed a profile's effective bounds: for example, metrics disables automatic records and graphs even when their configured limits are positive. Reports expose both the chosen budgets and effective channel states/bounds. Smaller generic capture budgets retain an explicit reserve of one quarter of records (rounded up) and one quarter of bytes (rounded down); automatic observations use the remainder. Profiles do not reassign disabled automatic capacity to explicit checkpoints.
In VS Code, set aner.notebook.observationProfile to metrics, inspect or deep and optionally configure aner.notebook.observationOptions with numeric native names, for example { "every": 10, "progress_every": 5, "captures": 32 }. Omitted keys retain native defaults. Profile or budget changes restart affected Development sessions; rerun setup cells. Invalid settings are rejected before source submission, retaining existing variables. Raw values require the deep profile. Both shared variable and independent program notebook execution use these settings.
Jupyter accepts %aner dev metrics every=10 progress_every=5 captures=32 in its own cell. %aner dev selects default Deep; %aner dev values selects Deep with raw values. Each directive specifies a complete configuration; omitted options return to native defaults. Invalid or duplicate options are rejected before resetting variables. Repeating the same mode/profile/options retains variables; changing them clears state and requires setup cells to be rerun. %aner reset clears variables while retaining the selected configuration.
Recording budgets and performance
With default Deep budgets, generic recording reserves the first 48 automatic observations within 96 KiB and the latest 16 explicit dev.capture checkpoints within 32 KiB. Explicit checkpoints replace the oldest explicit checkpoints when their count or byte budget is full; automatic observations cannot consume that reserve. The combined capture budget remains 64 records and 128 KiB. Each record identifies its automatic or explicit kind; reports distinguish rejected automatic observations, rejected incoming explicit checkpoints, and replaced explicit history. Expensive capture arguments are still evaluated normally.
By default, measured progress has its own 64 record, 64 KiB budget. It replaces superseded history before a series' latest record, retaining recent history where space remains. The latest record for every series, including a recorded final state, is retained only where both budgets permit; enough fits or large metadata can evict an older series' latest record. Total omissions and latest series eviction events are reported separately. Long progress metadata is bounded and marked shortened.
Default limits remain 128 global previews, 128 visited values per inspection, 6 nesting levels, 16 preview items per container, and 256 bytes per String/summary preview; the profile and configured budgets can lower the applicable limits. Globals have a 64 KiB budget and the embedded neural trace 256 KiB. Larger embedded neural traces are marked omitted, with compact graph loss records retained. Native protocol observation payloads are capped at 512 KiB; an otherwise permitted neural trace is also omitted if the complete response would exceed that cap. training_omission_reason distinguishes the trace limit from the complete inspection limit. Omitted/truncated data is labeled; absent values or gradients are not synthesized.
Development neural graphs have a default and maximum retained JSON budget of 256 KiB, configurable downward with --dev-graph-bytes. The separate legacy --debug-viz workflow retains its existing 64 snapshot behavior under a separate 64 MiB graph JSON ceiling. Neural captures retain their tensor/graph export limits. One run can contain several fits, but they share that finite recording budget. A later fit may have fewer captured states after the budget is used. Detailed values have additional per tensor limits; see visual training reports.
Inspection adds serialization, bounded object traversal, tensor statistics, and report output work. Tensor statistics take O(t) time for t elements even when the exported preview is small. Production avoids this work, while retaining normal safety checks. Guard source level diagnostic computations with dev.enabled() when appropriate. Exact speed differences depend on the workload and interpreter build; switching modes does not promise a fixed speedup.
Native compilation and the next steps
The runtime mode and the C++ interpreter's Debug/Release build configuration are separate. A Release build can optimize the interpreter while either runtime mode still works. The current development aner build compiles a bounded typed CPU subset through C++20; see native compilation. This source build compiler is absent from published 0.0.4 packages and does not add Dev observation support to compiled executables. Existing numerical kernels and the interpreted Dev/Prod paths remain separate from this build decision.
To build and run the optimized native interpreter from this checkout:
cmake --preset release
cmake --build --preset release
./build/release/aner examples/development_nn.aner --prodThis selects the Release executable explicitly. It does not change an existing aner command on PATH.
The native subset reuses checked types and resolved calls and is verified against interpreted programs; broader compiler coverage remains development work. The next observation priorities are streaming metric observations while a cell runs, source linked pause/step debugging and broader optimizer/layer implementations. These are separate from the Dev switch.
Measured neural progress and placement
fit(..., progress: true) reports bounded measured CLI progress for fixed epochs and approximate remaining time after five updates. Development reports include measured progress alongside captured loss; notebooks show these observations after the cell completes. tensor.dtype(), tensor.device(), and Tensor previews identify actual precision, placement, and native backend. GPU value/gradient observations may synchronize and read back device results. nn.execution() describes the requested and effective execution profile. Compatibility adaptation, intentional Float32 selection, and CPU Float64 fallback are separate from Dev/Prod; warnings remain visible in production. These additions do not change Dev into a different neural training algorithm. The neural workflow explains timing phases, Adam, Xavier/He initialization, custom classes, CPU and optional MPS/CUDA execution, and the distributed execution boundary.
For mini batch research, dev.automatic(false) disables broad automatic variable capture while retaining explicit captures and progress; the setting persists across notebook cells until reset. dev.progress(epoch, epochs, loss, accuracy, seconds) records a finite row weighted online loss and held out accuracy fraction, with an optional sixth validation loss argument. Development views chart these measured values separately. These custom Tensor loops must preserve and audit their original Dataset views because extracted Tensors carry no Dataset role. See neural workflows and the MNIST protocol.
Recurrent architecture inspection
RecurrentModel supports the same bounded Mermaid diagrams and immutable observations as CNNModel. Use dev.capture("LSTM", model) before fitting and inspect sample weighted training progress while fit runs. Explicit .step and .fit_chunk state boundaries remain identical in Dev and Prod; see the recurrent user guide.
See the complete callable index for the native module and method name catalogue.