# hwaminclaude/nmfc architecture

> Architecture diagram of the GitHub repository hwaminclaude/nmfc, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-07-17). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/hwaminclaude/nmfc
- Repository: https://github.com/hwaminclaude/nmfc

## Overview

#### Purpose and Entry Points
NMFC is a PyTorch reproduction and experimental framework for Nonlinear Marginal Fisher Classification: local geometric energy logits, automatic phase transition (APT), reference-bank inference, baselines, and OOD evaluation. Primary CLI entry point: `src/train.py`, driven by YAML experiment definitions such as `configs/synthetic.yaml`, `configs/cifar100.yaml`, and `configs/ood_cifar10.yaml`. Main user-facing artifact is generated/curated notebooks under `notebooks/`.

#### Experiment Orchestration and Lifecycle
`src/train.py` selects synthetic, image benchmark, or OOD runners; constructs datasets, encoder/head or baseline, optimizer, and executes two phases: linear MFA warm-up followed by APT-controlled NMFC training. It writes checkpoints, epoch history, test embeddings, and final metrics. `src/utils/experiments.py` owns the cache contract: a final `results/<exp>/metrics.json` is the completion sentinel, so completed runs load rather than retrain.

#### NMFC Mathematical Core
The stateless formulation is concentrated in `src/nmfc/`:
- `src/nmfc/affinity.py`: pairwise distances, adaptive variance, and masked-softmax neighborhood affinity.
- `src/nmfc/energy.py`: within-class and cross-class energies, scale normalization, and geometric logits.
- `src/nmfc/losses.py`: NMFC likelihood, linear MFA warm-up loss, scatter matrices, and Fisher ratio.
- `src/nmfc/apt.py`: pure-Python controller that watches Fisher-ratio convergence and switches phases.
Variant-era extensions reside in `src/nmfc/acs.py` and `src/nmfc/softmin.py`.

#### Model and Inference Boundary
`src/models/encoders.py` maps synthetic vectors or images to embeddings (MLP or ResNet-50). `src/models/heads.py` provides `NMFCHead`, separating batch-local training energy calculations from inference through a per-class ReferenceBank. `src/models/banks.py` maintains the bounded train-embedding bank used to freeze inference statistics. `src/models/heads_v3.py` and `src/variants.py` allow config-selected v1/v3 energy, logit, APT, and bank combinations without changing the standard path.

#### Data and Batch Structure
`src/datasets/synthetic.py` generates and splits moons, circles, and Swiss-roll manifolds. `src/datasets/image.py` loads CIFAR-10, CIFAR-100, and SVHN, including Windows-safe transform construction. `src/datasets/samplers.py` supplies PK-balanced batches; this is a critical data boundary because NMFC, triplet, and Deep-MFA require meaningful same-class and cross-class in-batch neighborhoods.

#### Evaluation and Comparative Experiments
`src/models/baselines.py` implements Softmax CE, ArcFace, batch-hard Triplet, Prototype, and Deep-MFA comparators under shared orchestration. `src/evaluate.py` computes classification Top-1/Top-5, embedding silhouette, and OOD AUC. NMFC OOD scoring is derived from total geometric energy rather than softmax confidence.

#### Runtime, Infrastructure, and Outputs
The runtime is Python/PyTorch with CUDA-capable NVIDIA GPUs recommended; dependencies are declared in `requirements.txt`, and environment bootstrap is `scripts/setup_env.ps1`. External datasets/services are torchvision-accessible CIFAR-10/100 and SVHN, with a documented BrainChip mirror fallback. Results form a durable three-part interface: checkpoint weights, `logs/<exp>/history.json`, and `results/<exp>/metrics.json` plus embeddings for visualization. `scripts/run_all.ps1` executes configured experiments sequentially; notebook builders such as `scripts/build_notebook.py` regenerate presentation artifacts from cached outputs.

Main entry points: [`src/train.py`](https://github.com/hwaminclaude/nmfc/blob/main/src/train.py) (Training CLI), [`src/models/heads.py`](https://github.com/hwaminclaude/nmfc/blob/main/src/models/heads.py) (NMFC Head), [`src/datasets/samplers.py`](https://github.com/hwaminclaude/nmfc/blob/main/src/datasets/samplers.py) (PK Batch Sampler), [`src/models/encoders.py`](https://github.com/hwaminclaude/nmfc/blob/main/src/models/encoders.py) (Embedding Encoders)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_orchestration["Experiment Runtime"]
  node_train["Training CLI<br/>Python entry point<br/>[train.py]"]
  node_experiments["Experiment Cache<br/>cache lifecycle<br/>[experiments.py]"]
  node_configs["Experiment YAML<br/>configuration<br/>[synthetic.yaml]"]
  node_evaluation["Evaluation<br/>metrics and OOD<br/>[evaluate.py]"]
end

subgraph group_data["Data Pipeline"]
  node_synthetic_data["Synthetic Datasets<br/>dataset builder<br/>[synthetic.py]"]
  node_image_data["Image Datasets<br/>torchvision loader<br/>[image.py]"]
  node_pk_sampler["PK Batch Sampler<br/>balanced sampler<br/>[samplers.py]"]
end

subgraph group_nmfc["NMFC Core"]
  node_affinity["Neighborhood Affinity<br/>NMFC geometry<br/>[affinity.py]"]
  node_energy["Geometric Energy<br/>NMFC logits<br/>[energy.py]"]
  node_losses["NMFC Losses<br/>optimization objective<br/>[losses.py]"]
  node_apt["APT Controller<br/>phase controller<br/>[apt.py]"]
end

subgraph group_models["Models &amp; Inference"]
  node_encoder["Embedding Encoders<br/>PyTorch model<br/>[encoders.py]"]
  node_nmfc_head["NMFC Head<br/>training/inference head<br/>[heads.py]"]
  node_reference_bank[("Reference Bank<br/>embedding bank<br/>[banks.py]")]
  node_baselines["Baseline Models<br/>comparators<br/>[baselines.py]"]
  node_variants["Variant Selection<br/>extension layer<br/>[variants.py]"]
end

subgraph group_outputs["Results &amp; Presentation"]
  node_results["Cached Results<br/>durable artifacts"]
  node_notebooks["Generated Notebooks<br/>presentation artifacts"]
  node_notebook_builder["Notebook Builder<br/>artifact generator<br/>[build_notebook.py]"]
end

node_configs -->|"drives"| node_train
node_train -->|"checks cache"| node_experiments
node_experiments -->|"loads or writes"| node_results
node_train -->|"builds"| node_synthetic_data
node_train -->|"builds"| node_image_data
node_synthetic_data -->|"examples"| node_pk_sampler
node_image_data -->|"examples"| node_pk_sampler
node_pk_sampler -->|"balanced batches"| node_encoder
node_train -->|"constructs"| node_encoder
node_encoder -->|"embeddings"| node_nmfc_head
node_affinity -->|"neighborhood weights"| node_energy
node_energy -->|"geometric logits"| node_nmfc_head
node_losses -->|"Fisher ratio"| node_apt
node_apt -->|"phase transition"| node_train
node_nmfc_head -->|"updates train embeddings"| node_reference_bank
node_reference_bank -->|"inference statistics"| node_nmfc_head
node_train -.->|"alternative model"| node_baselines
node_variants -.->|"config-selected implementation"| node_nmfc_head
node_train -->|"test embeddings and logits"| node_evaluation
node_evaluation -->|"final metrics"| node_results
node_results -->|"cached outputs"| node_notebook_builder
node_notebook_builder -->|"regenerates"| node_notebooks

click node_train "https://github.com/hwaminclaude/nmfc/blob/main/src/train.py"
click node_experiments "https://github.com/hwaminclaude/nmfc/blob/main/src/utils/experiments.py"
click node_configs "https://github.com/hwaminclaude/nmfc/blob/main/configs/synthetic.yaml"
click node_synthetic_data "https://github.com/hwaminclaude/nmfc/blob/main/src/datasets/synthetic.py"
click node_image_data "https://github.com/hwaminclaude/nmfc/blob/main/src/datasets/image.py"
click node_pk_sampler "https://github.com/hwaminclaude/nmfc/blob/main/src/datasets/samplers.py"
click node_encoder "https://github.com/hwaminclaude/nmfc/blob/main/src/models/encoders.py"
click node_nmfc_head "https://github.com/hwaminclaude/nmfc/blob/main/src/models/heads.py"
click node_reference_bank "https://github.com/hwaminclaude/nmfc/blob/main/src/models/banks.py"
click node_baselines "https://github.com/hwaminclaude/nmfc/blob/main/src/models/baselines.py"
click node_affinity "https://github.com/hwaminclaude/nmfc/blob/main/src/nmfc/affinity.py"
click node_energy "https://github.com/hwaminclaude/nmfc/blob/main/src/nmfc/energy.py"
click node_losses "https://github.com/hwaminclaude/nmfc/blob/main/src/nmfc/losses.py"
click node_apt "https://github.com/hwaminclaude/nmfc/blob/main/src/nmfc/apt.py"
click node_variants "https://github.com/hwaminclaude/nmfc/blob/main/src/variants.py"
click node_evaluation "https://github.com/hwaminclaude/nmfc/blob/main/src/evaluate.py"
click node_notebooks "https://github.com/hwaminclaude/nmfc/blob/main/notebooks/1.NMFC_version1.ipynb"
click node_notebook_builder "https://github.com/hwaminclaude/nmfc/blob/main/scripts/build_notebook.py"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_train,node_experiments,node_configs,node_evaluation toneBlue
class node_synthetic_data,node_image_data,node_pk_sampler toneAmber
class node_affinity,node_energy,node_losses,node_apt toneMint
class node_encoder,node_nmfc_head,node_reference_bank,node_baselines,node_variants toneRose
class node_results,node_notebooks,node_notebook_builder toneIndigo
```

## Components

### Experiment Runtime

- [Training CLI](https://github.com/hwaminclaude/nmfc/blob/main/src/train.py): Python entry point · Selects runners and executes warm-up plus APT training. · `src/train.py`
- [Experiment Cache](https://github.com/hwaminclaude/nmfc/blob/main/src/utils/experiments.py): cache lifecycle · Final metrics file is the completed-run sentinel. · `src/utils/experiments.py`
- [Experiment YAML](https://github.com/hwaminclaude/nmfc/blob/main/configs/synthetic.yaml): configuration · `configs/synthetic.yaml`
- [Evaluation](https://github.com/hwaminclaude/nmfc/blob/main/src/evaluate.py): metrics and OOD · Computes Top-1/5, silhouette, and energy-based OOD AUC. · `src/evaluate.py`

### Data Pipeline

- [Synthetic Datasets](https://github.com/hwaminclaude/nmfc/blob/main/src/datasets/synthetic.py): dataset builder · `src/datasets/synthetic.py`
- [Image Datasets](https://github.com/hwaminclaude/nmfc/blob/main/src/datasets/image.py): torchvision loader · Loads CIFAR-10/100 and SVHN. · `src/datasets/image.py`
- [PK Batch Sampler](https://github.com/hwaminclaude/nmfc/blob/main/src/datasets/samplers.py): balanced sampler · Provides meaningful intra- and cross-class neighborhoods. · `src/datasets/samplers.py`

### NMFC Core

- [Neighborhood Affinity](https://github.com/hwaminclaude/nmfc/blob/main/src/nmfc/affinity.py): NMFC geometry · Computes distances, adaptive variance, and masked affinities. · `src/nmfc/affinity.py`
- [Geometric Energy](https://github.com/hwaminclaude/nmfc/blob/main/src/nmfc/energy.py): NMFC logits · Computes class energies and normalized geometric logits. · `src/nmfc/energy.py`
- [NMFC Losses](https://github.com/hwaminclaude/nmfc/blob/main/src/nmfc/losses.py): optimization objective · Provides likelihood, MFA warm-up, and Fisher-ratio calculations. · `src/nmfc/losses.py`
- [APT Controller](https://github.com/hwaminclaude/nmfc/blob/main/src/nmfc/apt.py): phase controller · Switches from linear MFA warm-up on Fisher convergence. · `src/nmfc/apt.py`

### Models & Inference

- [Embedding Encoders](https://github.com/hwaminclaude/nmfc/blob/main/src/models/encoders.py): PyTorch model · MLP or ResNet-50 maps inputs to embeddings. · `src/models/encoders.py`
- [NMFC Head](https://github.com/hwaminclaude/nmfc/blob/main/src/models/heads.py): training/inference head · Separates batch-local energy training from bank-based inference. · `src/models/heads.py`
- [Reference Bank](https://github.com/hwaminclaude/nmfc/blob/main/src/models/banks.py): embedding bank · Bounded per-class train embeddings freeze inference statistics. · `src/models/banks.py`
- [Baseline Models](https://github.com/hwaminclaude/nmfc/blob/main/src/models/baselines.py): comparators · CE, ArcFace, Triplet, Prototype, and Deep-MFA alternatives. · `src/models/baselines.py`
- [Variant Selection](https://github.com/hwaminclaude/nmfc/blob/main/src/variants.py): extension layer · Selects v1/v3 energy, logits, APT, and bank combinations. · `src/variants.py`

### Results & Presentation

- **Cached Results**: durable artifacts · Checkpoints, history, embeddings, and final metrics.
- [Generated Notebooks](https://github.com/hwaminclaude/nmfc/blob/main/notebooks/1.NMFC_version1.ipynb): presentation artifacts · Curated visualizations are regenerated from cached outputs. · `notebooks/1.NMFC_version1.ipynb`
- [Notebook Builder](https://github.com/hwaminclaude/nmfc/blob/main/scripts/build_notebook.py): artifact generator · `scripts/build_notebook.py`

## Connections

- Experiment YAML → Training CLI: drives
- Training CLI → Experiment Cache: checks cache
- Experiment Cache → Cached Results: loads or writes
- Training CLI → Synthetic Datasets: builds
- Training CLI → Image Datasets: builds
- Synthetic Datasets → PK Batch Sampler: examples
- Image Datasets → PK Batch Sampler: examples
- PK Batch Sampler → Embedding Encoders: balanced batches
- Training CLI → Embedding Encoders: constructs
- Embedding Encoders → NMFC Head: embeddings
- Neighborhood Affinity → Geometric Energy: neighborhood weights
- Geometric Energy → NMFC Head: geometric logits
- NMFC Losses → APT Controller: Fisher ratio
- APT Controller → Training CLI: phase transition
- NMFC Head → Reference Bank: updates train embeddings
- Reference Bank → NMFC Head: inference statistics
- Training CLI → Baseline Models: alternative model
- Variant Selection → NMFC Head: config-selected implementation
- Training CLI → Evaluation: test embeddings and logits
- Evaluation → Cached Results: final metrics
- Cached Results → Notebook Builder: cached outputs
- Notebook Builder → Generated Notebooks: regenerates
