Browse documentation
aner.nn · Reference

Convolutional neural networks

Build native CNNs and model zoo architectures, choose explicit AMP and collective policies, inspect diagrams and resume training snapshots.

Implemented

Learn from spatial neighborhoods

CNN: preserve spatial structure, then classify

An NCHW image batch passes through shared local convolution filters, activation and pooling. A head reduces spatial features to class logits. Targets enter the loss during training; they are separate from image inputs.

CNN: preserve spatial structure, then classifyAn NCHW image batch passes through shared local convolution filters, activation and pooling. A head reduces spatial features to class logits. Targets enter the loss during training; they are separate from image inputs.Shared filter at each spatial positionImage batchN × C × H × WConvolution+ activationPoolingspatial reductionHeadclass logitsLayers infer the next shape from the declared input.Training snapshot → held out evaluation → retained checkpoint

Follow the arrows in the diagram. On a narrow screen, scroll inside the figure or read its caption.

A complete research workflow

1 / Separate the observations

Split images before fitting normalization or selecting a model. Keep class IDs and preprocessing with the experiment.

2 / Fit an immutable snapshot

Keep the starting model. Declare optimizer, clip norm, weight decay and shuffle policy. A deliberate new phase uses reset_optimizer().

3 / Evaluate held out data

Inspect evaluate(...).loss(), samples() and observations(); classification also reports accuracy(). This detached result does not advance optimizer state.

Head replacement or a changed backbone freeze policy starts a fresh optimizer, dataset and shuffle phase while retaining compatible learned weights. Use reset_optimizer() explicitly for a deliberate new data phase. Repeating the same freeze flag preserves continuation.

Read the CNN parameter reference for every model/configuration argument, its actual default, accepted shape/range, effect and persistence contract. Neural networks and the model directory connect the technique specific guides.

Implemented CPU APIs in Aner 0.0.4 or newer. Use the matching editor integration. The 0.0.4 research packages include native CPU APIs, and supported Mac packages include Metal/MPS. CUDA and MPI/NCCL source backends require separately prepared compatible runtimes; the current Linux and Windows release packages do not include CUDA or MPI/NCCL. Follow each device, precision and operation contract before choosing an accelerator.

aner
import aner.nn
import aner.tensor

let images = tensor.reshape(nn.random(8, 64, seed: 2026, scale: 1.0), List(8, 1, 8, 8))
let labels = nn.zeros(8, 1)
let model = nn.cnn(channels: 1, height: 8, width: 8, seed: 42)
    .conv2d(outputs: 4, kernel: 3, stride: 1, padding: 1).relu()
    .max_pool2d(kernel: 2, stride: 2, padding: 0).head(classes: 2)
    .on(device: "cpu", precision: "Float32")
let fitted = model.fit(images, labels, epochs: 3, batch: 4,
    rate: 0.001, seed: 91, optimizer: "adam", clip_norm: 1.0,
    weight_decay: 0.0001, shuffle: true)
print(fitted.predict(images).rows())

This complete synthetic example prints 8 and demonstrates shapes/update mechanics. Its all zero teaching labels do not measure classification quality; use independent real validation/test images for that purpose.

For a complete example with distinct training and validation rows, held out metrics, uneven batches, CPU replicas and staged fine tuning, run CNN workflow. evaluate(validation_images, validation_labels, batch: 32) returns a detached NeuralEvaluation; its loss(), accuracy(), samples(), observations() and summary() describe the supplied held out data without changing weights, BatchNorm buffers or optimizer counters. last_loss() is an online training observation, rather than this final parameter evaluation loss.

Images are preprocessed NCHW [samples,channels,height,width] tensors. Targets are zero based IDs [samples,1] or one hot [samples,classes]. Keep preprocessing and label mappings with the experiment. Split before fitting transforms, use validation data for model selection and reserve held out test data for evaluation. The arbitrary Tensor interface does not attach protected Dataset roles automatically. See the complete synthetic example.

Build or select an architecture

Shapes are inferred after the input declaration. Builders return immutable models; training returns a new retained snapshot. head(classes) adds global average pooling when needed and the terminal raw class projection. .summary(), .diagram() and .parameter_count() inspect the architecture without a forward pass. .prepare() initializes a reusable resident inference snapshot.

aner
let resnet = nn.vision("resnet50", classes: 10).on("cuda")

Available native graphs include ResNet-18/34/50/101/152, ResNeXt 50 32×4d, DenseNet 121, EfficientNet B0, ConvNeXt Tiny and InceptionV3. Inspect nn.architectures() for canonical names. Construction downloads no weights. Import compatible local weights explicitly with .load_weights(path) and retain the required preprocessing and class mapping. .head(classes) can replace a terminal classifier; .freeze_backbone() restricts fine tuning to that head. Checkpoint restoration preserves optimizer state; a weight import starts a separate training run.

After training only the head, head_fit.freeze_backbone(false) preserves learned weights and starts a new optimizer/dataset/shuffle phase for full network fine tuning. reset_optimizer() starts that phase explicitly when deliberately switching datasets. Moments and optimizer step reset; lifetime update/attempt/skip counters and precision policy remain. Repeating the existing frozen flag preserves continuation. Public fit controls include global clip_norm (zero disables clipping), decoupled kernel/dense weight_decay (normalization gain and bias excluded), and deterministic optional shuffle.

For a manual loader or learning rate schedule, use train_step(batch_images, batch_labels, rate: ..., clip_norm: ..., weight_decay: ...). Each independent batch preserves moments and cumulative counters and attempts one canonical update, with optional execution. It retains no whole dataset fingerprint or shuffle epoch; the caller retains loader position and chooses validation/checkpoints.

Operators include grouped/dilated convolution, max/average/global pooling, BatchNorm, ReLU/GELU, flattening, dense projection and training only dropout. .budget(tensor_elements, graph_elements) bounds numeric storage and the differentiation graph. Inputs are complete tensors, not an automatic streaming image loader. .read_images(path, samples) accepts exact size preprocessed little endian raw Float32/Float64 NCHW data; it does not decode JPEG/PNG or infer normalization.

Workflow coverage

This summary describes the native CNN API. Match the runtime, backend and hardware to the experiment. The complete native CNN reference retains the full capability matrix and method contracts.

WorkflowImplemented pathBoundary to plan around
Classification and topologyNCHW 2D operators, native model zoo classifiers and held out loss/accuracyNo CNN regression, segmentation or detection objective, or public custom branch builder
Data and fittingPreprocessed tensors/raw image files, Adam/SGD and explicit independent minibatch updatesCaller owns decoding, augmentation, streaming, preprocessing, schedules, early stopping and split provenance
Transfer and persistenceLocal Safetensors weights, head replacement, backbone freezing, optimizer phase reset and checked checkpointsNo automatic weight download or inferred normalization/label mapping; preprocessing remains external
Local CPU replicasSeparate replica graphs contribute to one sample weighted canonical updateRunning BatchNorm statistics must be frozen; synchronized BatchNorm is unavailable
MPI and GPU executionExternal MPI launch with MPI host reductions or supported CUDA/NCCL reductionsIsolate one visible CUDA device per rank; indexed GPU replicas and parallel.cluster CNN transport are unavailable

CUDA precision and collectives

aner
import aner.parallel

let tuned = resnet.performance(amp: "fp16", collectives: "auto")
let fitted = tuned.fit(images, labels, execution: parallel.local())

AMP packs eligible GEMM operands into FP16/BF16 while retaining FP32 master weights, gradients, moments and output storage. amp: "fp16" requires supported Tensor Core hardware; BF16 and matmul: "tf32" require Ampere or newer. Strict FP32 is the default. FP16 loss scaling skips a whole optimizer update when gradients overflow. .performance_summary(), .attempts(), .skipped_updates() and .loss_scale() expose retained policy and counters.

Native MPI sessions coordinate ranks and NCCL can sum resident GPU gradient buffers. collectives: "nccl" requires a CUDA/MPI/NCCL build and a configured rank to GPU assignment. "mpi" selects the MPI reduction path; "auto" chooses a supported session path. Use one process per physical GPU, consistent architecture/data/settings across ranks and a global batch large enough for useful shards. Local CPU replica contexts also work. There is no automatic cluster provisioning. See parallel computing.

The MPI launcher or scheduler must isolate one visible CUDA device per rank. CNN does not accept indexed multi GPU replicas within a process, and the Dense only parallel.cluster SSH/process protocol does not transport CNN graphs. See the workflow coverage for remaining boundaries such as streaming data loaders, synchronized BatchNorm, custom residual builders and nonclassification CNN objectives.

CUDA supports Float32/Float64; Metal/MPS supports Float32. Unsupported explicit placement fails. Intel and AMD GPU providers remain reserved without a validated backend. Small models and small matrices can run slower on a GPU or under AMP. Time the whole training step with warm up and synchronization; Tensor Core availability alone does not establish end to end speedup or scaling efficiency.

Validation covers numerical agreement, resident gradients, optimizer continuation and overflow handling. Hardware correctness tests do not establish accuracy on a production dataset, peak GPU utilization or linear multi server scaling. Architecture construction is separate from pretrained weight compatibility.

Checkpoints and development

aner
fitted.save("vision.anercnn")
let resumed = nn.load_cnn("vision.anercnn").on("auto")

Save to a new path. Versioned snapshots retain model parameters, BatchNorm state, optimizer moments, training continuation and precision/scaler policy. Preserve preprocessing separately. Use .prepare() and the same .predict() in inference.

aner
import aner.dev

dev.capture("CNN architecture", model)

Run with --dev reports/cnn-first to record bounded diagrams and training progress; use a fresh directory. --prod runs the same kernels, checks, limits and seeds without automatic development recording. See development mode and recurrent networks.

Aner documentation · Reference and guides