17. Capability reference¶
This page lists the main capabilities of NNx, grouped by task. Each entry names
its entry points and links to the guide or example that shows it. It describes
the current source; an older PyPI release can lack some entries (see
Release or source). For installation and a
first trained model, see the README and the
Quickstart. Extras named here are installed as
pip install "thekaveh-nnx[<extra>]".
1. Training loop¶
- Supervised loop.
NNModelbuilds the network from frozen configuration objects and runstrain(),evaluate()andpredict(). Callbacks, early stopping, gradient clipping, gradient accumulation and seeded reproducibility are built in. - Schedulers. The
Schedulersenum providesREDUCE_LR_ON_PLATEAU,STEP,COSINE_ANNEALING,ONE_CYCLEandLINEAR_WARMUP_DECAY. A scheduler steps once per epoch by default, or once per committed optimizer update withNNSchedulerParams(clock="optimizer_update"). - Precision.
PrecisionPolicyselects FP32, FP16 or BF16 explicitly. - Metrics and monitors.
NNTrainParams.extra_metricsaccepts anycallable(y_true, y_pred) -> float. Declared metrics (MetricSpec) and one named monitor (MonitorSpec) drive BEST selection, plateau scheduling and anEarlyStoppinggiven the same monitor. - Objectives.
LossTerms with explicit denominators run over one shared update engine, which gives accumulation, clipping and the precision policy toNNModelandTraineralike. Built-in objectives:supervised_objective,kd_objective,diffusion_objectiveandjepa_objective. - Custom steps. The
train_step_fnhook replaces the per-batch supervised step with your own function. Use it for autoencoders, VAEs, recommendation or other methods without changing NNx internals. - Multi-optimizer
Trainer.nnx.trainer.TrainerparallelsNNModel.train()for disjoint optimizers, such as GAN generator and discriminator or actor-critic. Each entry of its name-keyed optimizer dictionary is scoped by anNNParamGroupSpec; the groups must partition the parameters. - Optimizers.
Optimsprovides SGD, Nesterov SGD, Adam, AMSGrad and AdamW. Any othertorch.optim.Optimizeris a registered factory (nnx.register_optimizer_factorywithNNOptimFactoryParams).run.yamlstores only the factory's id, version and config, so runs reload offline. See Concepts §3.1. - Callbacks. The
Callbackbase class hason_{train,epoch}_{begin,end}hooks. Built in:EarlyStopping,LRMonitor,ModelCheckpoint(custom epoch tags),TensorBoardCallback(tensorboardextra) andWandbCallback(wandbextra). A legacyCallable[[List[IDP]], None]is still accepted. - Data-parallel training.
model.train(params, distributed=nnx.distributed.DDP())runs one process per device undertorchrunon one machine. NNx partitions the data and keeps every update equal to the union batch's, and one rank writes the run. See Quickstart §3.10. - Opt-in compilation.
model.train(params, compile=CompileSpec())compiles the built-in step's FP32 forward pass; checkpoints, export and later inference stay eager. It records requested and effective state and never guarantees a speedup.nnx.benchmarkingseparates first-call compile cost from warmed latency. It is not available with DDP or quantization. See Concepts §28.
2. Runs, checkpoints and resume¶
- Content-addressed runs.
NNRunsavesrun.yaml,idps.csvandmetadata.yamlunderruns/<id>/, whereidis the MD5 of the configuration'sstate(). - Checkpoints.
NNCheckpointsaves the FIRST, Q1, Q2, Q3, LAST and BEST tags. LAST is the epoch commit marker: a failed LAST write rolls the history back, andNNRun.load()drops history newer than LAST after an interrupted process. - Warm resume. Each checkpoint names a generation-addressed training-state sidecar. A resume restores the optimizer, scheduler, scaler, loader generators and every RNG stream; a torn or corrupted resume point is refused before anything is restored. See Concepts §14.
- Bounded history.
history=nnx.history.HistoryJournal(retention, chunk_size)keeps a bounded window in memory and appends each record once toruns/<id>/history/, with lazy tail reads and CSV export. - Experiment plans. An immutable
ExperimentPlanbranches a configuration (with_epochs,with_seed,with_data, ...).validate()reports every problem without reading data.probe(batch)runs an eval-mode no-grad forward pass, plus a train-mode loss pass when the batch has a target. It then restores the ambient state.fit()trains a distinct attempt. Seeexamples/experiment_plan.py. - Budgeted search (
optunaextra).nnx.search.search(plan, space, ...)runs a sequential Optuna study over an experiment plan; each trial fits a new plan in its own run directory. See Concepts §29. - Provenance.
train(..., provenance=ExperimentManifest(...))records the declared task, labels, model, data and split identities with a SHA-256 fingerprint and one attempt record per fit.nnx.provenance.comparediffs two plans without loading models. - Run bundles and the Hub.
nnx.bundlesexports a checkpoint as a verified, portable bundle. With thehubextra,NNModelsupportssave_pretrained,push_to_hubandfrom_pretrained, and checkpoints can be saved as safetensors. See HuggingFace Hub.
3. Tasks¶
- Task adapters.
NNModelParams(task=TaskSpec.regression(n)),.multilabel(n, threshold=...)or.categorical(n, ignore_index=...)validates batches before any update and masks NaN or ignored targets out of the loss and metrics. The loss is averaged over valid targets. Seeexamples/regression_task.py. - Ranking.
nnx.ranking.RankingTasktrains a scorer with a pairwise logistic objective within each query. It reports MRR@k, Recall@k and NDCG@k per complete query. Seeexamples/ranking_offline.py. - Graph classification.
nnx.graph_tasksclassifies whole graphs from aGraphCollectionwith stable graph ids and mean or sum pooling. Seeexamples/graph_classification_offline.py(graphextra). - Link prediction.
nnx.link_taskssplits edges into a replayable manifest, passes messages over training edges only and reports exact AUROC and AP. A held-out positive edge in a message graph is refused before any update. Seeexamples/link_prediction_offline.py(graphextra). - Your own modules.
NNModeltrains anytorch.nn.Module. Register a factory (register_model_factory,ModelSpec) for a model that rebuilds from checkpoints, safetensors and the Hub, or pass an instance withNNModel(module=m, ...)for runtime-only use. Seeexamples/custom_module.py.
4. Training methods¶
- Diffusion (DDPM).
nnx.diffusionprovides LINEAR and COSINE noise schedules and a conditional MLP denoiser (DiffusionMLP). Train with a step factory ordiffusion_objective, and sample withsample. - Distillation.
kd_train_step_factorymixes Hinton-style soft and hard losses with a frozen teacher.feature_kd_train_step_factoryadds an MSE term between named intermediate activations.born_again_trainiterates self-distillation over generations. - Offline teacher distributions.
nnx.paradigms.offline_distillationdistills from stored teacher probabilities, aligned by sample and candidate id, without a live teacher. - Contrastive and augmentation. SimCLR (NT-Xent), Mixup and CutMix step factories.
- Mixture of Experts. Sparse top-k routing with a Switch-style
load-balancing loss, and a drop-in
nnx.MoELinear. - I-JEPA. Masked-patch latent prediction against an EMA target encoder,
with
JEPAPredictor,build_target_encoder,update_ema,random_block_maskand a smallViTNNencoder. See I-JEPA. - DPO. Preference-pair fine-tuning against a frozen reference policy. See DPO.
Paradigm and diffusion step factories share a NaN guard and gradient clipping.
5. Fine-tuning and model transforms¶
- Transfer learning.
nnx.finetunefreezes layers by glob pattern, loads external state dicts with optional key remapping and sets per-group learning rates throughNNOptimParams.param_groups. - Parameter-efficient fine-tuning.
nnx.peftprovides LoRA, DoRA, IA3, prefix tuning, prompt tuning and adapter layers. Eachsave_*_weightsfunction saves only the trainable delta (DoRA'smagnitudeneeds the fullstate_dict()). LoRA starts from the pretrained behavior because its second factor is zero-initialized. - Quantization (
quantizeextra).nnx.quantize.quantize_int8(model)applies torchao INT8 weight-only post-training quantization without calibration data and returns the same model class. QAT 8da4w usesqat_train_step_factorywithQATLifecycleCallback. - Pruning.
nnx.prune.magnitude_pruneapplies unstructured masks, baked into checkpoint-safe weights by default;semi_structured_24applies 2:4 sparsity through torchao. - Model surgery.
nnx.surgeryprovideswidenanddeepen(function-preserving Net2Net edits on validated topologies),drop_layer,low_rank_factorize(SVD) andexpand_embedding. See Model surgery. - Recorded recipes.
nnx.transforms.TransformReciperecords LoRA and SVD low-rank transforms in every checkpoint and Hub save, sofrom_checkpointandfrom_pretrainedrebuild the transformed topology.
6. Networks, language models and export¶
- Networks.
FeedFwdNN,FeedFwdMoENN,ConvNN,GraphConvNN,GraphSageNN,GraphAttNN,TransformerNNandViTNN(Nets.VITwithNNViTParams). The graph networks need thegraphextra. - Causal language-model task.
nnx.lm_tasks.CausalLMTaskprovides the next-token objective and evaluation for aTransformerNN, reporting token NLL, perplexity and accuracy. See Quickstart §3.6. - Language modeling.
TransformerNNis a decoder-only model with RMSNorm, RoPE, SwiGLU, tied embeddings and a KV cache.GenerativeNNModel.generate()supports greedy, top-k, top-p and repetition-penalty sampling. Thelmextra adds the BPE tokenizer. See Language modeling. - KV-cache scope. A CPU regression test requires cached decoding to be at
least 1.2× faster than full recomputation for its fixed 256-token workload.
Results on other hardware and workloads vary. Past
max_seq_len, the cache rebuilds every step. - Decoding order.
LogitsChain.builder()sorts logit processors into the canonical order.OrderedLogitsPipelineruns stages exactly as declared, throughgenerate(logits_pipeline=...). - ONNX export.
NNModel.to_onnx(path, example_input)uses the legacytorch.onnx.export, which needs theonnxextra.dynamo=Trueuses thetorch.export-based exporter, which also needsonnxscript(onnx-dynamoextra).nnx.export_conformancechecks numerical parity in ONNX Runtime (onnx-runtimeextra). See Export conformance. - Experimental GGUF (
gguf-writeextra).nnx.interop.write_ggufwrites an NNx-tagged GGUF file. Stock llama.cpp, Ollama and LM Studio do not implement its architecture. See Experimental GGUF export. - Embeddings (
embeddingsextra).nnx.embeddingstrains a text embedder from(anchor, positive)pairs and exports a FAISS index for downstream retrieval. See Embeddings.
7. Data, evaluation and decisions¶
- Datasets.
NNDataset(torchvision,visionextra),NNGraphDataset(PyTorch Geometric,graphextra),NNTabularDataset(pandas) andNNPreferenceDataset(DPO preference triples). - Reproducible splits.
nnx.data_splits.plan_splitplans group, chronological and stratified splits into a JSONSplitManifest, whichNNTabularDatasetreplays by sample id. Seeexamples/split_replay.py. - Train-only preprocessing.
nnx.preprocessing.Standardizerfits on the training rows only and reloads from JSON. Seeexamples/preprocessing_offline.py. - Probabilities.
NNModel.predict_proba(X, ProbabilitySpec(...))returns probabilities for an explicitly declared task;predict()is unchanged. - Streaming prediction and metrics.
NNModel.iter_predict(loader)yields predictions batch by batch with bounded memory, andnnx.streamingprovides mergeable metrics. See Concepts §21. - Calibration.
nnx.calibration.fit_temperaturefits one temperature on a named calibration split and reports NLL, Brier and reliability before and after. Seeexamples/calibration_offline.py. - Abstention.
nnx.abstentionaccepts a prediction only above a probability or margin threshold;select_thresholdtunes it against a risk ceiling. Seeexamples/abstention_offline.py. - Multi-seed comparisons.
nnx.comparisonsummarizes repeated runs without pooling incompatible observations and pairs two configurations by replicate key. Seeexamples/compare_seeds.py. - Typed decisions.
nnx.decisionsasksChoice,BooleanorScorequestions and returns validated, labelled probabilities. Providers serve a trained classifier, a local NLI model or hosted Jev models (jevextra). See Typed decisions.
8. Configuration, diagnostics and typing¶
- Configuration objects.
NNParams,NNModelParams,NNTrainParams,NNOptimParams,NNSchedulerParamsandNNTrainerParamsare frozen dataclasses that round-trip throughstate()andfrom_state(). A field at its default is left out ofstate(), so adding a field does not change existing run ids. - Builders.
NNOptimParams.builder(),NNSchedulerParams.builder(),NNTransformerParams.builder()andNNTrainerParams.builder()expose one method per valid variant, such as.adam(...)or.one_cycle(...), so an invalid combination cannot be built..copy()branches a Builder andBuilder.from_params(params)rebuilds an existing value. Seeexamples/builder_branching.py. - Enum factories.
Nets,Losses,Optims,Schedulers,Activations,DevicesandNoiseSchedulersconstruct their objects when called.Checkpointsnames the checkpoint tags. - Reproducibility.
nnx.set_seed(seed)seeds every RNG and cuDNN;nnx.dataloader_worker_init_fnseeds loader workers. - Learning-rate finder (
plotsextra).nnx.lr_finderruns an exponential sweep, suggests a one-cyclemax_lrand restores the model and RNG state afterwards. - Run plots (
plotsextra).VisUtilsreturns Plotly figures (confusion matrix, line and scatter plots, t-SNE of checkpoint logits) and a classification-report DataFrame. - Model internals (
vizextra).nnx.vizprovidessummary,weight_histogram,activation_map,attribute(Captum),gradient_flowandnetron_export, which also needs theonnxextra. - Errors as values.
nnx.resultprovides opt-inOkandErrvalues for code that prefers to branch on a value; every NNx API still raises. See Concepts §27. - Typing. NNx ships a PEP 561
py.typedmarker, sopyrightandmypyuse its annotations.