CNet framework builds complex-valued neural networks in C++ and CUDA
CNet is a C++/CUDA framework for building and researching deep complex valued neural networks as well as for optimization of complex valued functions using gradient descent with Wirtinger derivatives. The framework provides researchers a transparent substrate where complex numbers are the default rather than a bolted-on data type.
Layers include CPU reference and CUDA kernel
Every built-in layer ships both a CPU reference and a CUDA kernel. Adding a new operator means writing its CPU forward/backward class and a CUDA kernel then wiring the kernel into the GPU dispatch via GpuMapping (gpu/gpumapping.h) and the GPU_LAYER_TABLE registration macro (gpu/gpu_data.h). There is no automatic CPU→GPU codegen; the kernel is written once by hand.
Why complex-valued neural networks matter
Complex valued neural networks remain a research area that is currently neglected due to the huge commercial success of the real valued ones. Mainstream frameworks such as PyTorch and JAX both support complex tensors and complex-aware autodiff and for mainstream work they are the right tools far more mature faster at scale multi-GPU and backed by large ecosystems. CNet does not compete on that axis. It exists because for research on complex-valued networks specifically a complex-first transparent substrate has concrete advantages.
- Complex is the default not a bolted-on dtype. In the mainstream frameworks complex coverage is uneven many layers normalizations activations initializers and optimizers assume real tensors so a CVNN is assembled from real building blocks plus hand-written patches whose gradient conventions must be checked case by case. In CNet every variable layer loss and the optimizer are complex by construction.
- Wirtinger gradients are explicit first-class objects. Each layer manipulates the pair (∂L/∂z ∂L/∂z̄) directly and the non-holomorphic case (e.g. |z|²) is handled in the open rather than hidden behind a conjugation convention. Every layer ships a CPU reference and a GPU kernel checked against each other and against finite differences so the complex gradient is auditable not trusted.
- Spectral structure is built in. The DFT the Hadamard (spectral) product the inverse DFT and the conv = IFFT(FFT · FFT) equivalence are first-class layers so problems whose natural domain is the frequency plane map onto the framework directly.
- A physics-native model and loss the Born rule. This is the sharpest departure from the mainstream frameworks. CNet reads a networks output as a complex amplitude vector z (a state) and defines the class probabilities by the quantum-measurement (Born) rule p_k = |z_k|² / |z|² with loss L(z,y) = -∑_k y_k log(|z_k|² / |z|²). Classification is a measurement on an amplitude produced by a cascade of complex often unitary operations rather than real logits passed through a softmax. This inductive bias is natural for physical and wave/field data an IQ baseband sample is the complex envelope of a real passband signal an MRI k-space sample is a complex Fourier coefficient and a wavefunction is a complex amplitude. PyTorch and JAX provide no such head or loss out of the box.
- A small auditable substrate. The full forward/backward of every layer and its CUDA kernel is explicit and readable and the GPU execution model a depth-ordered graph cloned across the batch is visible and controllable.
Building and running CNet
For sequence models (text bytes Go moves or any other token stream) you write only the model graph and the data impl/cnet_app.h supplies training on one GPU or many (NCCL) Adam with warm-up and cosine decay gradient clipping validation with best-checkpoint saving and inference.
#include "../impl/cnet_app.h"
struct MyData : app::DataSource { // vocab() context() sample(heldout rng in tgt)
...
};
struct MyModel : app::ModelDef { // build(net vocab context) -> app::Heads(embedding loss)
...
};
int main(int argc, char **argv) {
FLAGS::Parse(argc argv);
MyData data(...); MyModel model(...);
app::Trainer trainer(model data); // options from standard flags: -steps -lr -batch -save_path ...
return trainer.run();
}
Inference on a saved model:
app::Infer inf;
inf.loadModel("model.mod");
std::vector out = inf.generate(prompt_ids 300 0.8 /*seed*/ 1); // or nextProbs() sample() score()
Build and run:
make app SRC=examples/char_lm.cpp # multi-GPU build (NCCL=0 for a single-GPU box)
./char_lm -data book.txt -steps 5000 -batch 8 -save_path lm.mod -tw_cublas true -tw_real_loss true
./char_lm -data book.txt -generate true -model lm.mod -prompt "ROMEO:" -gen_len 300
for r in 0 1 2 3; do ./char_lm -data book.txt -batch 24 -world 4 -rank $r -save_path lm.mod & done; wait # 4 GPUs
examples/char_lm.cpp is a complete byte-level language model in about 100 lines and examples/README_app.md lists every flag and API call. Fresh weights use a normal initialization (-init_std 0.02) which trains much better than CNet's older init_inputs() start.
Minimal neural net for MNIST Fashion MNIST
The following code shows how to build a minimal neural net for the MNIST Fashion MNIST datasets using the Fourier Transform and Hadamard layers with a Gelu activation function:
CNet cnet;
auto inp = cnet.add(new CInput(OutSize(28 * 28)));
auto fft = cnet.add(new FourierTrans(InSize(28 * 28)), {inp});
auto h_data = cnet.add(new CInput(OutSize(28 * 28)));
auto hdm = cnet.add(new Hadamard(InSize(28 * 28) InSize(28 * 28)), {fft h_data});
auto gelu = cnet.add(new CGelu(InSize(28 * 28)), {hdm});
auto l_data = cnet.add(new CInput(OutSize(28 * 28 * 10)));
auto lin = cnet.add(new Linear(InSize(28 * 28) InSize(28 * 28 * 10)), {gelu l_data});
auto outp = cnet.add(new CrossEntropy(InSize(10)), {lin});
Please see the file cnet.cpp for how to train on CPU/GPU the above complex valued neural net with the MNIST Fashion MNIST datasets.
Adding a new complex-valued function
In order to add a new complex valued function say CFunc class and implement forward() plus either backward() or more simply the two Wirtinger derivatives dz() and dz_star() from which CNet builds the backward pass. A layer also needs a constructor that takes a Uid a clone() method and a getName(): CNet clones every layer once per batch entry on the GPU and uses the name when saving and restoring models.
class CSigmoid: public CFunc {
public:
CSigmoid(Uid uid InSize in_size) : CFunc(uid in_size OutSize(in_size.value())) {}
CSigmoid(InSize in_size) : CFunc(in_size OutSize(in_size.value())) {}
virtual CFunc* clone(Uid uid) { return new CSigmoid(uid InSize(input().length_)); }
virtual std::string getName() { return "CSigmoid_" + std::to_string(uid_); }
};
While writing an implementation for the forward() method is usually straightforward providing an implementation for the backward() method is in general more difficult. The CNet framework makes things easier whenever you can compute the Wirtinger derivatives for the corresponding multivariable functions as you can write implementations for the dz() and the dz_star() methods instead.
virtual complex dz(int out_indx int in_indx) {
if (out_indx != in_indx) {
return 0;
}
auto g = 1.0f / (1.0f + exp(-input().z(in_indx)));
return g * (1.0f - g);
}
virtual complex dz_star(int out_indx int in_indx) {
return 0;
}
GPU execution and benchmarks
On an NVIDIA GPU the CNet framework will try to clone the CPU net and execute the forward and the backward passes in parallel following the graph computation depth. Because the clones execute concurrently across the batch GPU memory grows linearly with the batch size while the per-step wall-clock time stays essentially flat.
| batch | GPU mem MB | fwd ms/step | bwd ms/step |
|---|---|---|---|
| 16 | 167.8 | 0.33 | 0.32 |
| 32 | 335.5 | 0.33 | 0.32 |
| 64 | 671.1 | 0.33 | 0.32 |
| 128 | 1342.2 | 0.33 | 0.32 |
| 256 | 2684.4 | 0.33 | 0.32 |
Memory is linear in the batch size each clone holds its own activations while the forward and backward times per step remain near-constant from batch 16 up to 256 since the clones are launched level by level and run in parallel. Throughput therefore scales with the batch at roughly fixed latency. A reduced-memory inference layout Vars INFER_DIMS drops the per-example footprint further by not allocating the gradient optimizer buffers that only training needs.
Because the clone arena is static across steps device pointers for activations weights and Wirtinger gradients never move after allocateOnGpu the entire level-by-level launch schedule can be captured once into a CUDA graph and replayed with a single cudaGraphLaunch (CNet GpuForwardGraphed GpuBackwardGraphed). This removes the per-kernel launch sync overhead: on an H100 the forward+backward step drops from 0.65 ms to 0.32 ms (~2× flat across batch) while staying bit-identical to eager execution and the captured step runs faster than eager torch.complex64. The standalone bench_clone example reproduces this:
make bench_clone
./bench_clone -fft_fast true # eager
./bench_clone -fft_fast true -bc_graph 1 # replay captured CUDA graphs
./bench_clone -fft_fast true -bc_check 1 # verify graph replay == eager (bit-identical)