# Native convolutional networks

`aner.nn` includes immutable `CNNModel` values, differentiable image operators, native model-zoo graphs, local replica training, CUDA compute profiles and optional MPI/NCCL collective paths. CNN programs use Aner's own Tensor/autodiff engine. They do not require Python, PyTorch or a remote inference service at runtime.

A model is an architecture and a retained training snapshot. Constructing topology is cheap; parameters initialize during `prepare`, `fit`, or weight loading. Ordinary tensor constructors retain their existing small-experiment bounds. CNN execution and raw image ingestion use explicit model budgets.

Source programs import `aner.nn` and use `nn.cnn`, `nn.vision` and `CNNModel` methods. `aner::cnn` is the corresponding native C++ namespace and library, rather than another source module.

## Workflow coverage

This matrix describes implemented boundaries; it is not an inventory of every possible convolutional architecture.

| Workflow | Available | Remaining boundary |
| --- | --- | --- |
| Image classification | NCHW 2D grouped/dilated convolution, pooling, BatchNorm, activations, dropout, raw-logit heads | No CNN-model BCE, regression, segmentation or detection objective |
| Custom architecture | Shape-inferred sequential builders; ten native model-zoo graphs include internal residual/concatenation branches | No public custom branch/DAG builder, Conv1D/3D, transposed convolution, custom LayerNorm or SiLU builder |
| Data ingestion | Exact preprocessed raw tensors and raw Float32/Float64 image files | No JPEG/PNG decoder, augmentation pipeline, streaming image loader or automatic preprocessing/class-map persistence |
| Fitting | Adam/SGD, clipping, decoupled kernel/dense decay, deterministic optional shuffle, partial final batches, independent minibatch updates | No automatic image loader, scheduler or early stopping |
| Validation and inference | Batched held-out loss/accuracy/counts, probabilities, logits, predicted IDs | Caller owns split provenance, preprocessing and model selection |
| Transfer learning | Local named Safetensors import, head replacement, frozen-backbone phase, unfreezing, explicit optimizer reset | No network download or pretrained normalization/label-map recipe is inferred |
| Persistence | Versioned checked native checkpoints retain topology, parameters, buffers, moments and continuation policy | Complete files are bounded to 2 GiB; preprocessing and dataset rows stay external |
| Local parallel training | Isolated CPU replica graphs and one sample-weighted canonical optimizer update | Replicated BatchNorm requires frozen running statistics; no synchronized BatchNorm |
| Multi-process training | External MPI launch; MPI host reductions or supported resident CUDA/NCCL reductions | `parallel.cluster` SSH/process CNN execution, elastic recovery, automatic GPU discovery and sharding are unavailable |
| Accelerators | Existing CPU, MPS Float32 and CUDA profiles; explicit supported AMP/TF32 policies | One visible CUDA device per MPI rank; no indexed multi-GPU replicas inside one process or convolution/communication overlap |
| Native execution | Source API runs Aner's native Tensor/autodiff kernels | The standalone ahead-of-time source compiler does not currently lower Tensor/CNNModel programs |

Use one process per visible CUDA device under an MPI launcher when requesting multiple GPUs. Scheduler/launcher policy owns rank-to-device isolation; Aner does not discover or repartition GPUs. Numerical/collective tests cover specific declared configurations, and the hardware evidence below remains specific to those hosts. Newly added workflow methods do not establish multi-GPU throughput or validate additional hardware.

## Build a custom CNN

```aner
import aner.nn

let model = nn.cnn(channels: 1, height: 28, width: 28, seed: 42)
    .conv2d(outputs: 16, padding: 1).batch_norm().relu()
    .max_pool2d()
    .conv2d(outputs: 32, padding: 1).relu()
    .head(classes: 10)
    .on(device: "auto", precision: "Float32")
```

The input declaration owns the channel count and spatial dimensions. Subsequent builders infer their input shapes. `head` adds global average pooling, flattening and a raw class projection when the preceding output is spatial. The final projection returns logits; cross-entropy applies the appropriate normalization internally.

Use `.flatten().dense(outputs: 10)` for an explicit dense connection from all spatial features. Global pooling usually produces a smaller classifier parameter allocation.

Builder calls return new values. Training also returns a new model, preserving earlier snapshots. Finish ordinary topology edits before initializing parameters. `head(classes)` is the deliberate exception: it can replace an existing terminal classifier while retaining the backbone, and starts a fresh optimizer/shuffle run.

### Fluent API

Optional arguments have the following defaults. Named arguments may skip earlier optional settings: `.conv2d(outputs: 16, padding: 1)` and `.fit(images, labels, epochs: 4, rate: 0.001)` are valid.

| Call | Result / behavior |
| --- | --- |
| `nn.cnn(channels, height, width, seed: 42)` | Lazy `CNNModel`; input layout is NCHW |
| `.conv2d(outputs, kernel: 3, stride: 1, padding: 0, groups: 1, dilation: 1)` | Grouped/dilated square convolution with bias |
| `.batch_norm()` | Per-channel BatchNorm with persistent running statistics |
| `.relu()`, `.gelu()` | Pointwise activation |
| `.max_pool2d(kernel: 2, stride: 2, padding: 0)` | Square max pooling |
| `.avg_pool2d(kernel: 2, stride: 2, padding: 0)` | Square average pooling |
| `.global_pool()` | Global spatial average pooling |
| `.flatten()` | Flatten each sample's features |
| `.dense(outputs)` | Dense projection; requires flattened features |
| `.head(classes)` | Global-pool classifier, or replacement of a terminal dense classifier |
| `.dropout(probability: 0.5)` | Training-only dropout |
| `.on(device: "auto", precision: "Float32")` | Explicit placement/precision snapshot |
| `.prepare()` | Initialize and retain resident weights for repeated inference |
| `.performance(amp: "off", matmul: "strict", collectives: "auto")` | Explicit CUDA compute and collective policies |
| `.performance_summary()` | Requested/last compute and collective policy, loss scaling and step counters |
| `.loss_scale()`, `.attempts()`, `.skipped_updates()` | Retained AMP scaling and attempted/skipped update counts |
| `.freeze_backbone(frozen: true)` | Train only the terminal head; freeze backbone weights and BatchNorm buffers |
| `.reset_optimizer()` | Keep learned weights and lifetime counters; start a new optimizer/dataset/shuffle phase |
| `.train_step(images, targets, rate: 0.001, optimizer: "adam", clip_norm: 1.0, weight_decay: 0.0)` | One independent global minibatch; retain optimizer moments and lifetime counters |
| `.freeze_batch_norm(frozen: true)` | Freeze running statistics while retaining trainable affine parameters |
| `.budget(tensor_elements, graph_elements)` | Explicit numeric working limits |
| `.summary()`, `.diagram()` | Text description / Mermaid architecture, without forward execution |
| `.export_diagram(path)` | Native SVG or self-contained HTML export to a new path, without inference or external renderers |
| `.parameter_count()`, `.parameter_names()` | Architecture count / exact local weight names |
| `.parameter(name)` | Detached named parameter for inspection |

Module forms use a leading `model` argument: `nn.conv2d(model, outputs: 16)`, `nn.dense(model, outputs: 10)` and `nn.diagram(model)` are equivalent to receiver calls. Existing Dense-only `NeuralNetwork` overloads keep their original arguments, including `inputs` and `outputs`.

`model.export_diagram("architecture.svg")` or `"architecture.html"` writes a native, self-contained diagram to a new path whose parent already exists. SVG contains accessible text, true branch/residual edges and shape labels; HTML adds a scrollable wrapper and model description without scripts or network resources. The renderer accepts only the internal topology subset, shows at most 128 declared nodes, and explicitly counts any omitted nodes/edges without inventing bypass edges. Full node labels remain in accessible titles. `.diagram()` continues to return the complete Mermaid source for another renderer.

## Images and labels

Images have shape `[samples, channels, height, width]`. Labels are detached Tensor values containing exact zero-based class IDs of shape `[samples, 1]`, or exact one-hot rows `[samples, classes]`. Inputs must have the model's declared geometry. The model prepares execution placement/precision for each minibatch.

For small examples, use existing tensor constructors and reshape:

```aner
import aner.tensor

let images = tensor.reshape(nn.random(8, 784, seed: 2026, scale: 1.0),
                            List(8, 1, 28, 28))
let labels = nn.zeros(8, 1)
```

These random images and constant labels demonstrate API mechanics; they provide no model-quality evaluation. See the complete [small CNN program](../examples/cnn_basics.aner).

For larger, already-preprocessed image arrays, use the model's bounded raw reader:

```aner
let images = model.read_images(path: "data/train.nchw.f32", samples: 64)
```

The file must contain exactly `samples * channels * height * width` finite little-endian floating-point values, with Float32 or Float64 matching `model.dtype()`. The reader returns a CPU NCHW Tensor under the model's tensor budget. Paths follow the process working directory. There is no implicit image decoding, resize, channel reorder, value rescaling, normalization or augmentation. PNG/JPEG decoding and streaming dataset ingestion remain separate work; this fit API receives a complete input Tensor and copies minibatches from it.

Keep training, validation and test inputs separate in the calling program. The CNN Tensor API does not attach the protected Dataset role/provenance contracts of `ml.classifier` to arbitrary image arrays. Choose preprocessing and label mappings once, retain their metadata with the experiment, and apply the same transforms at inference. Pretrained weight variants can require different transforms; the [TorchVision model documentation](https://docs.pytorch.org/vision/stable/models.html#using-the-pre-trained-models) explains this dependency.

## Train, evaluate, save and resume

```aner
let fitted = model.fit(images, labels,
    epochs: 5, batch: 32, rate: 0.001, seed: 42, optimizer: "adam")
print(fitted.last_loss())
print(fitted.updates())

let predicted = fitted.predict(images)
let probabilities = fitted.probabilities(images)
let scores = fitted.logits(images)
fitted.save("checkpoints/cnn-005.acnn")

let restored = nn.load_cnn("checkpoints/cnn-005.acnn").on("auto")
let continued = restored.fit(images, labels,
    epochs: 5, batch: 32, rate: 0.001, seed: 42, optimizer: "adam")
```

`fit(images, targets, epochs: 1, batch: 32, rate: 0.001, seed: 42, optimizer: "adam", clip_norm: 1.0, weight_decay: 0.0, shuffle: true)` uses minibatch cross-entropy, keeps the final partial batch and returns detached retained parameters. Supported optimizers are `"adam"` and `"sgd"`. A positive `clip_norm` clips the global parameter gradient norm; zero disables clipping. Weight decay is decoupled: eligible weights subtract `rate * weight_decay * old_weight` in addition to their optimizer update. Biases and normalization affine parameters are excluded. The product of rate and weight decay must be below one. Shuffling is deterministic when enabled. There is no built-in learning-rate scheduler or early-stopping selector.

`last_loss` is the sample-weighted online epoch loss measured before each batch update. `evaluate(images, targets, batch: 32)` returns a detached `NeuralEvaluation` with held-out `loss()`, `accuracy()`, `samples()`, `observations()` and `summary()`. Cross-entropy is normalized by samples, including an uneven final evaluation batch. Evaluation disables dropout, uses saved BatchNorm buffers and leaves weights, optimizer state, counters and source model initialization unchanged. `loss(images, targets, batch: 32)` returns its mean cross-entropy directly. `accuracy(images, targets)` returns the fraction of correct top-1 predictions. `logits` and `probabilities` return `[N, classes]`; `predict` returns `[N, 1]` class IDs.

```aner
let held_out = fitted.evaluate(validation_images, validation_labels, batch: 32)
print(held_out.loss())
print(held_out.accuracy())
print(held_out.samples())
```

Keep validation and test tensors separate from training inputs. Evaluation does not attach Dataset partition roles or choose a model for you.

Training enables dropout and BatchNorm batch-statistic updates. Inference disables dropout and uses retained BatchNorm running statistics. Development recording does not control this training/evaluation behavior.

Checkpoints retain architecture, weights, BatchNorm buffers, Adam moments and optimizer step, update counts, completed shuffle epochs, seed, data fingerprint, freeze policy, numerical budgets and execution metadata. They contain no executable payload or dataset rows. Saves create a new file exclusively; create the parent directory first. Loads validate version, topology, dimensions, values and checksum under a 2 GiB file bound and restore portable CPU storage. Use `.on(...)` to choose a new supported execution device.

A resumed fit requires the same input values, labels, source order and shuffle seed. For the same trajectory, also retain the same batch size, optimizer, learning rate, precision and native environment. Splitting an epoch budget across successive compatible fits advances the retained shuffle epoch and Adam state. Changing optimizer intentionally resets its moments while retaining model weights. Cross-backend bitwise identity is not promised.

Use `reset_optimizer()` to deliberately start another phase on new data while keeping learned weights. It clears moments, optimizer step, completed shuffle epochs and the dataset fingerprint. The most recently measured training loss, successful/attempted/skipped lifetime update counters and precision/scaler policy remain. Calling `freeze_backbone` with a changed flag performs the same phase reset, allowing head-only training followed by full-network fine tuning without discarding the learned head. Repeating the current flag preserves continuation.

```aner
let head_fit = model.freeze_backbone().fit(train_images, train_labels, epochs: 2)
let fine_tuned = head_fit.freeze_backbone(false).fit(train_images, train_labels,
    epochs: 3, rate: 0.0001, clip_norm: 1.0, weight_decay: 0.0001)
let adapted = fine_tuned.reset_optimizer().fit(new_images, new_labels, epochs: 2)
```

The complete [CNN workflow example](../examples/cnn_workflow.aner) uses separate synthetic training and validation rows, explicit fit controls, held-out metrics and staged fine tuning.

`train_step(batch_images, batch_labels, ...)` admits one independent global minibatch and preserves optimizer moments, attempted/successful counters and dropout update identity across calls. It performs one optimizer update, or a recoverable AMP skip. It disables shuffling and retains no whole-dataset fingerprint or completed shuffle epoch, so the next minibatch can contain different data. An optional `execution` context reduces replica gradients before that single canonical update. Invalid minibatches publish no replacement model. Use this method for an external data-loader loop, manual learning-rate schedule or validation-based checkpoint selection; preserve preprocessing, row order and loader position yourself.

For repeated inference on a newly constructed random model, prepare it once:

```aner
let inference = nn.vision("resnet18", classes: 10).on("auto").prepare()
let scores = inference.logits(images224)
```

Here `images224` must contain `[N,3,224,224]` inputs. A fitted or loaded initialized model already retains weights. Calling `logits` directly on a lazy descriptor is deterministic but initializes temporary weights on each call; `.prepare()` avoids that repeated work. Randomly initialized models require training before their predictions become useful.

## Native model zoo and transfer learning

```aner
print(nn.architectures())
let architecture = nn.vision("resnet50", classes: 10, seed: 42)
print(architecture.parameter_count())
print(architecture.summary())
```

`nn.vision(architecture, classes: 1000, seed: 42)` creates an executable native graph. It allocates no parameter tensors until prepared, fitted or supplied weights.

| Architecture string | Declared input | Main structure |
| --- | --- | --- |
| `resnet18`, `resnet34` | `3 × 224 × 224` | Basic residual blocks |
| `resnet50`, `resnet101`, `resnet152` | `3 × 224 × 224` | Bottleneck residual blocks |
| `resnext50_32x4d` | `3 × 224 × 224` | Grouped bottleneck residual blocks |
| `densenet121` | `3 × 224 × 224` | Dense feature concatenation and transitions |
| `efficientnet_b0` | `3 × 224 × 224` | Depthwise MBConv, squeeze/excitation and SiLU |
| `convnext_tiny` | `3 × 224 × 224` | Depthwise convolution, LayerNorm, GELU and layer scale |
| `inception_v3` | `3 × 299 × 299` | Main Inception branches and final classifier; auxiliary head omitted |

Use exact strings returned by `nn.architectures()`. Recognizing a topology does not mean full-scale training has been benchmarked or fits the available memory. The graph uses Aner's current optimization/training profile; third-party augmentation, scheduling and regularization recipes are not imported. Residual connections follow the central structure described in the [ResNet paper](https://arxiv.org/abs/1512.03385).

Weights are explicit local Safetensors files:

```aner
let base = nn.vision("resnet50", classes: 1000)
    .load_weights("weights/resnet50.safetensors")
let transfer = base.head(classes: 10).freeze_backbone().on("auto")
let fitted = transfer.fit(images224, labels10, epochs: 5, batch: 8)
```

Import using the original classifier class count, then replace the head. `.head(10)` retains the loaded backbone and initializes a new classifier, resetting optimizer/shuffle history. `freeze_backbone()` prevents gradients and running-statistic updates in the feature extractor. Choose backbone freezing before the first training step. Changing the trainable backbone after updates is rejected; start a fresh weight-import run when changing that policy. Preserve the imported model's normalization and input geometry.

The importer checks exact names/shapes, accepts F32/F64 weights, supports scalar I64 BatchNorm counters, records the source SHA256 and rejects unexpected or missing required parameters. Supported layout adaptations include one-dimensional bias/norm vectors and ConvNeXt pointwise-linear/layer-scale shapes. Use `.parameter_names()` to inspect the expected schema. A PyTorch pickle `.pth` file is not accepted; convert a compatible state dictionary to Safetensors in a separate preparation workflow. Strip `AuxLogits.*` entries when preparing a main-only InceptionV3 file. Aner neither downloads weights nor executes a conversion script implicitly. Imported weights still require parity checks against their source implementation and preprocessing.

## Device placement and numeric budgets

The initial CNN profile is CPU Float32. `.on("auto")` explicitly selects available CUDA, then Float32 MPS, then CPU. CPU and CUDA support Float32/Float64; MPS requires Float32. An explicitly unavailable backend or unsupported precision fails before training. CUDA mixed compute is selected separately through `.performance(...)`; `.dtype()` continues to describe Tensor/master storage.

```aner
let cpu = model.on(device: "cpu", precision: "Float32")
let mac = model.on(device: "mps", precision: "Float32")
let nvidia = model.on(device: "cuda", precision: "Float32")
print(nn.cnn_capabilities())
```

Only request a device available in the runtime. `nn.cnn_capabilities()` reports the compiled/initialized native backends and MPI flag. AMD `"rocm"` and Intel `"xpu"` are explicit reserved providers: capability entries report unavailable, and execution requests fail with an explanation. They do not run through a silent CPU fallback. Implementing those providers still requires native forward/backward kernels, datatype/placement validation, build integration and hardware testing.

Default model limits are 64,000,000 elements per Tensor and 256,000,000 live graph elements. Bounds also cover convolution im2col workspaces and differentiation intermediates. For a consciously larger experiment:

```aner
let larger = model.budget(tensor_elements: 128000000,
                          graph_elements: 512000000)
```

The allowed range is at most 256M elements per Tensor and 2B graph elements, with graph budget at least the Tensor budget. Architecture admission also caps topology at 4096 operations and 150M parameter/buffer elements; training caps cumulative updates at 1M. These are numeric admission limits, not RSS/VRAM quotas. Parameters, moments, activations, graph metadata, transport buffers and allocator overhead all consume memory. A Float32 element is four bytes; Adam moments and gradients add allocations beyond weights. Begin with a small batch, inspect measured memory and increase only after validating capacity.

## CUDA compute profiles

Storage precision and matrix compute are separate choices:

```aner
let mixed = nn.vision("resnet50", classes: 10)
    .on(device: "cuda", precision: "Float32")
    .performance(amp: "fp16")
let fitted = mixed.fit(images224, labels10, epochs: 5, batch: 8)
print(fitted.performance_summary())
print(fitted.loss_scale())
print(fitted.attempts())
print(fitted.skipped_updates())
```

`performance(amp: "off", matmul: "strict", collectives: "auto")` is an immutable, allocation-free policy declaration. Named gaps are supported, including `.performance(matmul: "tf32")` and `.performance(collectives: "nccl")`. Unsupported settings are rejected when the model prepares or executes; defining or loading a profile does not silently change devices or alter storage precision. Each call replaces all three policy fields; omitted arguments use their published defaults. To keep FP16 while selecting NCCL, supply both `amp: "fp16"` and `collectives: "nccl"` in that call.

| Policy | Eligible matrix compute | Required execution |
| --- | --- | --- |
| `amp: "off", matmul: "strict"` | Existing full storage-precision GEMMs | Existing supported CPU/CUDA/MPS profile |
| `amp: "fp16"` | FP16 GEMM operands, Float32 accumulation/output | CUDA Float32 storage; compute capability 7.0+ |
| `amp: "bf16"` | BF16 GEMM operands, Float32 accumulation/output | CUDA Float32 storage; compute capability 8.0+, CUDA 11+ |
| `amp: "off", matmul: "tf32"` | cuBLAS TF32 compute for Float32 GEMMs | CUDA Float32 storage; compute capability 8.0+, CUDA 11+ |

Leave `matmul: "strict"` when enabling AMP; combining AMP with `matmul: "tf32"` is rejected. `matmul: "tensor"` is not a spelling in this API. The actual Tensor Core instruction/algorithm choice remains cuBLAS's responsibility for the admitted shapes. Tensor Core modes change numerical rounding and are not a promise of a specific throughput or bitwise match. Ampere introduced BF16 and TF32 Tensor Core operations; see [NVIDIA's architecture guide](https://docs.nvidia.com/cuda/ampere-tuning-guide/index.html#improved-tensor-core-operations). `NVIDIA_TF32_OVERRIDE=0` causes an explicit TF32 request to fail rather than advertising an inactive policy.

Mixed mode retains Float32 model weights, gradients, optimizer moments and activation storage. Eligible forward/backward matrix products, including convolution's im2col/GEMM work, convert operands to the requested lower precision on CUDA. Accumulation/results remain Float32; normalization, loss and other operations keep their implemented storage-precision kernels. Operand conversion buffers are reused within the CUDA provider. This is selective GEMM autocasting, not a conversion of every Tensor to FP16/BF16. The [cuBLAS GEMM documentation](https://docs.nvidia.com/cuda/cublas/index.html#cublasgemmex) distinguishes operand types from compute/accumulation policy.

FP16 uses retained dynamic loss scaling, initially 65536. Gradients are unscaled before clipping, global averaging and the optimizer update. A nonfinite contribution causes every participating rank to skip the same update; parameters, optimizer moments and successful-step counters do not advance. The scaler halves after overflow, and doubles after 2000 consecutive successful steps within its bounded range. BF16 uses a scale of 1. `attempts()` includes skipped batches; `updates()` counts successful optimizer updates; `skipped_updates()` exposes overflow skips. Dropout addresses the attempted step so a skipped batch does not repeat its random stream. Serial BatchNorm buffers are restored when that attempted update is skipped. An epoch with no finite forward losses is rejected.

Checkpoint continuation retains performance policy, loss-scaler state and attempted/skipped counters as well as optimizer/shuffle state. Loading remains CPU-portable; select a suitable CUDA device before executing a retained CUDA-only profile, or deliberately switch the profile off. Validate held-out quality and numerical error when choosing between strict, FP16, BF16 and TF32 modes.

## Local replicas and several machines

Local CPU fitting uses the existing `aner.parallel` execution context:

```aner
import aner.parallel

let parallel_model = model.on("cpu").freeze_batch_norm()
let fitted = parallel_model.fit(images, labels,
    epochs: 5, batch: 32, rate: 0.001,
    execution: parallel.local(workers: 2))
```

The complete [local replica example](../examples/cnn_parallel.aner) retains an uneven final batch. The batch size is global. A global batch is divided into exact, potentially unequal sample ranges. Workers own independent parameters/graphs for the batch; they return detached gradient and loss sums. The coordinator sums contributions, divides by the total sample count once and performs one optimizer update. The worker count does not multiply the batch size. Dropout addresses the logical sample and update so repartitioning a batch does not substitute a different mask stream.

For more than one replica, freeze BatchNorm running statistics explicitly with `.freeze_batch_norm()` or use `.freeze_backbone()`. Frozen BatchNorm affine parameters remain trainable unless the backbone is frozen. Synchronized BatchNorm is not implemented; the runtime rejects an unfrozen BatchNorm model with several replicas.

A strict device context can also select placement and precision:

```aner
let fitted = model.fit(images, labels, epochs: 5, batch: 32,
    execution: nn.execution_context(device: "mps", dtype: "Float32"))
```

The runtime currently exposes one accelerator per process. Several local accelerator replicas or an indexed device such as `"cuda:1"` are rejected. `parallel.cluster(config: ...)` uses the existing Dense-only SSH/process protocol and does not carry CNN graphs.

The optional CNN MPI path supports several processes and machines through an externally configured MPI launcher. Build against an existing MPI C++ installation:

```sh
cmake -S . -B build/cnn-mpi -DANER_USE_MPI=ON
cmake --build build/cnn-mpi --target aner
ANER_CNN_MPI=1 mpiexec -n 2 build/cnn-mpi/aner train.aner
```

All ranks run the same program with identical model/schema, global images/labels/order, batch schedule and seed. Use one local replica per rank; avoid `parallel.local(workers: 2)` inside an MPI rank. With `collectives: "mpi"`, gradients use CPU-staged Float64 MPI reductions. Losses and sample counts also use the MPI control path. Every rank applies the same canonical update; checkpoint publication is rank 0 only. Use a separate development report directory per rank if recording.

For multiple NVIDIA GPUs, expose one distinct GPU per rank using `CUDA_VISIBLE_DEVICES`, then select `.on("cuda")` inside each rank. The [MPI rank wrapper](../tools/aner_cnn_mpi_rank.sh) can perform local-rank mapping:

```sh
ANER_CNN_GPUS=0,1 mpiexec -n 2 tools/aner_cnn_mpi_rank.sh \
    build/cnn-mpi/aner train.aner
```

The wrapper enables `ANER_CNN_MPI=1`, reads the MPI launcher's local rank and exposes one numeric GPU ID from `ANER_CNN_GPUS`. Without that variable it preserves the scheduler's existing visible-device policy. Configure each host's list through the launcher when devices differ. Native CUDA uses the process's visible device 0. For several hosts, the MPI launcher owns host enrollment, process placement and transport. Ranks verify their complete run fingerprint before gradient exchange: input geometry, every graph operation/edge/argument, data/order, options, parameters, optimizer moments and loss-scaler configuration/state must agree. Parameter-identical graphs with different activations are rejected. RCCL/XCCL, model/tensor sharding and automatic GPU discovery/assignment remain unimplemented. The MPI compilation path and rank wrapper have separate tests; actual multi-host/GPU validation requires usable MPI/NCCL installations and the target devices.

### Resident CUDA NCCL reductions

Build with installed CUDA, MPI and NCCL development/runtime libraries:

```sh
cmake -S . -B build/cnn-nccl \
    -DANER_USE_CUDA=ON -DANER_USE_MPI=ON -DANER_USE_NCCL=ON
cmake --build build/cnn-nccl --target aner
ANER_CNN_GPUS=0,1 mpiexec -n 2 tools/aner_cnn_mpi_rank.sh \
    build/cnn-nccl/aner train.aner
```

Use `.performance(amp: "fp16", collectives: "nccl")` in `train.aner` to require native CUDA reductions. NCCL 2.14 or newer is required for the nonblocking progress path. MPI bootstraps the NCCL communicator and coordinates schema/status/cancellation; gradient payloads remain in immutable CUDA source buffers and fresh CUDA receive buffers. Native NCCL performs grouped sum reductions on the provider stream. AMP gradients are Float32 masters; full-precision CUDA gradient buffers retain their configured Float32/Float64 dtype. Scalar loss/count statistics and overflow agreement still use the MPI control path. The global sample denominator is applied once before the canonical update.

`collectives: "auto"` chooses NCCL when every rank is CUDA and the build supports it; otherwise it uses the MPI host path. `ANER_CNN_COLLECTIVE` may set the automatic choice. Explicit `collectives: "nccl"` or `"mpi"` overrides that environment choice. An explicit NCCL request requires `ANER_CNN_MPI=1` under an MPI launch, including a one-rank launch. It rejects execution outside MPI, non-CUDA ranks or a build without NCCL rather than transferring gradients through a hidden CPU fallback. `performance_summary()` identifies the requested policy and last selected transport; `nn.cnn_capabilities()` reports compiled MPI/NCCL support.

NCCL can communicate within and across GPU servers using its supported interconnects; [NVIDIA's overview](https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/overview.html) describes that transport layer. Aner owns a separate progress/status contract: `ANER_CNN_NCCL_TIMEOUT_MS` selects a timeout from 1 to 3600000 ms, default 120000 ms. Cooperative cancellation, communication errors or timeout abort the communicator and reject the incomplete global update. Recovery after process death or a failed node is not an elastic fault-recovery guarantee.

This is resident all-reduce with host control/scalar exchanges. It does not yet overlap backward computation with gradient buckets or provide optimizer/model sharding. Each rank still needs a complete model replica.

## Reproduce hardware validation

The [standalone validation harness](../tools/cnn_validation/CMakeLists.txt) builds the native Tensor/CNN implementation and its tests without building the language compiler. Run these commands from the repository root with CMake 3.27+, a C++20 compiler supported by the installed CUDA toolkit, MPI development/runtime libraries, and NCCL 2.14+ available:

```sh
cmake -S tools/cnn_validation -B build/cnn-validation \
    -DCMAKE_BUILD_TYPE=Release -DCMAKE_CUDA_ARCHITECTURES=70 \
    -DANER_USE_CUDA=ON -DANER_USE_MPI=ON -DANER_USE_NCCL=ON
cmake --build build/cnn-validation --parallel 4
ctest --test-dir build/cnn-validation --output-on-failure -j 1
```

`70` targets the tested V100. Set `CMAKE_CUDA_ARCHITECTURES` for the actual target devices; BF16/TF32 need suitable compute capability 8.0+ hardware. Use `CMAKE_PREFIX_PATH` for private dependency prefixes, or set `CUDAToolkit_ROOT`, `ANER_NCCL_INCLUDE_DIR` and `ANER_NCCL_LIBRARY` explicitly. Match the launcher to the MPI implementation linked into the build. For CPU/MPI-only validation, configure a separate build with `ANER_USE_CUDA=OFF`, `ANER_USE_MPI=ON`, `ANER_USE_NCCL=OFF`.

Run CTest without inherited `ANER_CNN_MPI`, `ANER_CNN_COLLECTIVE` or `ANER_CNN_VALIDATION_DIR` overrides; its MPI/NCCL cases set their own environment. Unsupported GPU profiles report `SKIP_UNAVAILABLE` and exit 77, which CTest records as skipped. A skip does not validate that profile. CTest includes two-local-CPU-rank reduction/admission checks and a one-rank resident NCCL check when those features are built; it does not enroll remote hosts or allocate several GPUs.

The directly executable GPU checks are:

```sh
build/cnn-validation/cuda_cnn_precision_tests --device cuda --compute fp16
build/cnn-validation/cnn_cuda_training_tests --compute fp16
ANER_CNN_GPUS=0 ANER_CNN_COLLECTIVE=nccl mpiexec -n 1 \
    tools/aner_cnn_mpi_rank.sh build/cnn-validation/cnn_nccl_tests
```

The precision test checks forward/backward numerical tolerances, compute-path counters and recoverable FP16 overflow. The training test checks resident Float32 masters, finite updates, scaler/counter retention and exact checkpoint continuation, then emits synchronized strict/selected GEMM median timings as JSON. Those timings include conversion/check costs for the specified matrix fixture; they do not measure end-to-end CNN throughput or distributed scaling. Replace `fp16` with `strict`, `bf16` or `tf32` to request another admitted profile.

For two physical GPUs on one host, select one distinct visible device per rank:

```sh
ANER_CNN_GPUS=0,1 ANER_CNN_COLLECTIVE=nccl mpiexec -n 2 \
    tools/aner_cnn_mpi_rank.sh build/cnn-validation/cnn_nccl_tests

ANER_CNN_GPUS=0,1 ANER_CNN_COLLECTIVE=nccl \
ANER_CNN_VALIDATION_DIR="$PWD/build/cnn-validation/checkpoints-two-gpus-001" \
mpiexec -n 2 tools/aner_cnn_mpi_rank.sh \
    build/cnn-validation/cnn_cuda_training_tests --compute fp16
```

`ANER_CNN_VALIDATION_DIR` must name a **new, nonexistent directory** whose parent already exists. Rank 0 creates it, publishes the checkpoint, and removes it when the test finishes. Every rank must see the same directory and file contents. A common local filesystem suffices on one host; several servers require shared storage at the same absolute path. Choose a new leaf for each concurrent run; do not create the leaf with `mkdir` first.

For several servers, first arrange host access through the site's scheduler or existing trusted MPI/SSH configuration. Use matching binaries and libraries with reachable MPI/NCCL network transport. The dedicated `cnn_distributed_training_tests` checks actual CUDA training and retained-model continuation without writing files, so independent local deployments need no shared filesystem or `ANER_CNN_VALIDATION_DIR`. It verifies exact canonical Float32 parameters/counters and CPU reference logits across ranks; native CUDA logits must match that reference within the stated strict/FP16 tolerance, allowing GPU architectures to round their own GEMMs differently.

In the following examples `gpu-a` and `gpu-b` are enrolled hostnames with one available GPU each. Matching repository/build files are deployed at `/opt/aner` on each host; these may be separate local copies at the same absolute path. Host enrollment and rank placement belong to the launcher. The [MPICH Hydra guide](https://github.com/pmodels/mpich/blob/main/doc/wiki/how_to/Using_the_Hydra_Process_Manager.md) and [Open MPI launcher manual](https://docs.open-mpi.org/en/v5.0.x/man-openmpi/man1/mpirun.1.html) describe their different host/environment flags.

MPICH/Hydra, one GPU/rank on each server:

```sh
mpiexec -hosts gpu-a,gpu-b -ppn 1 -n 2 \
    -genv ANER_CNN_GPUS 0 \
    /opt/aner/tools/aner_cnn_mpi_rank.sh \
    /opt/aner/build/cnn-validation/cnn_distributed_training_tests \
    --compute strict --collective nccl
```

Open MPI, one GPU/rank on each server:

```sh
mpiexec --host gpu-a:1,gpu-b:1 --map-by ppr:1:node -n 2 \
    -x ANER_CNN_GPUS=0 \
    /opt/aner/tools/aner_cnn_mpi_rank.sh \
    /opt/aner/build/cnn-validation/cnn_distributed_training_tests \
    --compute strict --collective nccl
```

`--compute strict` admits an available CUDA GTX 1060; use `--compute fp16` only when **every** GPU supports the FP16 policy. An unsupported rank causes a coordinated skip (77), which is not a successful training run. `--collective mpi` selects the CPU-staged MPI gradient path instead of NCCL. The test requires at least two ranks and an actual CUDA backend on each rank. It does not infer the number of distinct physical GPUs from the rank count; retain the device/host inventory with the result.

For two GPUs per server, use two ranks per host, four ranks total, and `ANER_CNN_GPUS=0,1`; the wrapper reuses local ordinals independently on each server. Preserve a scheduler's assigned visibility by omitting `ANER_CNN_GPUS` when each rank already receives one GPU. To test only resident all-reduce, replace the final executable with `cnn_nccl_tests` and omit its compute/collective arguments, passing `ANER_CNN_COLLECTIVE=nccl` through the launcher. Do not mix Open MPI launch flags/runtime with MPICH-linked binaries.

The separate `cnn_cuda_training_tests --compute fp16` checkpoint round-trip still requires a new `ANER_CNN_VALIDATION_DIR` shared by all ranks for a multi-rank launch. The no-file distributed test covers retained continuation; it does not replace checkpoint persistence validation.

Confirmed hardware validation:

| Hardware / placement | Actual passing evidence |
| --- | --- |
| V100 32 GB, `sm_70` | Strict/FP16 primitives and tiny-CNN training with exact checkpoint continuation; FP16 training/restore through one-rank resident NCCL; one finite SGD update of full-input (`224 × 224`) ResNet-18 in strict and FP16. Forced high-level FP16 overflow in serial and one-rank NCCL skipped five attempts before recovery, preserving weights, Adam step and BatchNorm buffers during skips. |
| RTX 3060 12 GB, `sm_86`, Ubuntu 24.04 under WSL2 | All 8 primitive/CNN training/checkpoint tests passed across strict, FP16, BF16 and TF32, including exact retained-state checkpoint continuation. Full-input ResNet-18 passed one finite SGD update in each of those four profiles. |
| Two Linux servers, one V100 32 GB (`sm_70`) and one GTX 1060 3 GB (`sm_61`) | Actual strict CUDA distributed training passed 21 checks with CPU-staged MPI and 21 with resident NCCL. Both runs completed nine global updates with zero skips and identical canonical Float32 parameter/CPU-logit snapshot hashes across the two ranks. The native two-rank NCCL test also passed resident-buffer immutability, uneven seven-sample counts, one-rank AMP overflow agreement and recovery after collective-sum overflow. |
| Two CPU MPI ranks on the V100 host | Reduction checks and 42 admission/continuation checks passed, including asymmetric invalid input/labels, BatchNorm policy mismatch and parameter-identical ReLU/GELU graph mismatch. |

The successful two-server NCCL run used the official NVIDIA NCCL 2.22.3 runtime built for CUDA 12.4 in a private dependency prefix. An earlier available NCCL 2.22.3 runtime built for CUDA 12.1 returned static-driver API errors on that test; this observation does not establish the packaging root cause. No system GPU driver was changed.

V100/RTX 3060 multi-node FP16 remains unvalidated: the WSL2 NAT deployment did not provide the required direct peer connectivity, and routing/firewall settings were not changed. Multi-node BF16/TF32, several GPUs within one server and distributed throughput scaling also remain outside the confirmed evidence. The local BF16/TF32 policies have been hardware-tested on the RTX 3060. Compute-path counters verify selected cuBLAS policies; no instruction-level profiler result establishes which Tensor Core instructions were executed.

These small-fixture and one-update results do not establish full model-zoo training or pretrained-weight parity. No throughput speedup is certified here. Keep the test output, toolkit/driver/library versions, GPU inventory, build flags and launcher placement with each subsequent validation run.

## Development and production

```sh
aner examples/cnn_basics.aner --prod
aner examples/cnn_basics.aner --dev reports/cnn-001
```

Production is the default. Both modes execute the same kernels, shapes, seeds and optimizer behavior. Development adds bounded snapshots and online epoch progress. `dev.capture("CNN architecture", model)` records architecture before fitting; the standalone inspector draws operation blocks, shape labels and residual connections offline. `model.diagram()` returns the complete Mermaid source for external documentation. Inspector diagrams are truncated within the ordinary recording budget; the truncation flag remains visible. The VS Code inspector retains escaped Mermaid source.

Guard additional expensive observations with `if dev.enabled()`. Report directories must be new. See [the development-mode guide](DEV_MODE.md) for the general observation contract and [the model-zoo example](../examples/cnn_architectures.aner) for topology-only inspection.

## Performance boundary and remaining work

Convolution lowers to native im2col/GEMM and existing provider operations. CPU Float32 uses the configured numerical provider; CUDA uses native CUDA/cuBLAS support; MPS uses native Metal/MPS operations. Resident prepared/fitted weights avoid repeated initialization, batched calls amortize setup, and frozen feature extraction reduces differentiation storage. Explicit resource admission prevents unbounded workspaces.

This is a native foundation with explicit CUDA GEMM compute and resident NCCL reduction paths, not a claim of peak GPU throughput. It does not yet provide fused cuDNN/MPSGraph convolution plans, convolution autotuning, channels-last layout selection, asynchronous communication overlap or gradient buckets. [PyTorch's AMP documentation](https://docs.pytorch.org/docs/2.14/notes/amp_examples.html) is a reference for selective autocasting and loss scaling; [its DDP documentation](https://docs.pytorch.org/docs/2.14/generated/torch.nn.parallel.DistributedDataParallel.html) describes mature synchronization/bucketing behavior beyond Aner's current whole-step reduction.

Benchmark initialization, upload, steady-state forward/backward, optimizer and communication separately on the target hardware. Compare equal shapes, batch sizes, precision, preprocessing and seeds, and synchronize the selected accelerator around timed regions. Measure throughput together with held-out accuracy and memory. CUDA feature admission, numerical tests and measured speedups are separate evidence. AMD, Intel and multi-host MPI/NCCL behavior cannot be certified by CPU, Mac or single-GPU test results. Full-scale model training and imported pretrained-weight parity require separate, hardware-specific evaluation.

## Low-level image operations

Custom experiments can call Tensor primitives directly through `aner.nn`:

```aner
let output = nn.conv2d(images, weight, bias,
    stride: 1, padding: 1, groups: 1, dilation: 1)
let pooled = nn.max_pool2d(output, kernel: 2)
let embedding = nn.adaptive_avg_pool2d(pooled, height: 1, width: 1)
```

`weight` is OIHW; image activations are NCHW. The public Tensor operations are `conv2d`, `max_pool2d`, `avg_pool2d`, `adaptive_avg_pool2d`, `channel_mean2d`, `channel_variance2d` and `batch_norm2d`. Tensor pooling uses `stride: 0` to mean the kernel size; model builders default to stride 2. Max-pool ties select the first valid position. Average pooling exposes `count_include_pad`; BatchNorm takes explicit gain, bias, mean, variance, `training` and `epsilon`. Inputs must agree on placement and precision. Autodiff follows these operations; unsupported provider capabilities reject explicitly.
