#I have found a few errors by looking at this code dear CeHaP, pls fix, these are big problems. No AI.
The most concrete bug is checkpoint handling in mnist.cpp.
The ofstream saveFile is opened with truncation right after the old weights are loaded. The existing mnist-conv.nn is wiped at startup, and the weights live only in memory until the first full epoch finishes.
bestLoss starts at max(), so the first epoch after a resume always overwrites the checkpoint, even if it is worse than the one you resumed from.
The stream is never flushed. The loop only stops through patience or learning-rate decay, so Ctrl-C is the normal way to end a run, and that can leave the last "saved" checkpoint truncated.
Other problems, roughly in order of severity:
load() doesn't validate anything. The is.read(...) calls are unchecked, and the file has no header, version or shape. A truncated file or one from a different architecture, such as the committed mnist-mlp.nn from before the CNN layers, loads without any error. The raw bytes also depend on endianness and sizeof(T).
network::train() breaks Adam. It creates a fresh learning_state on every call, so the moments and time reset each step. At time = 1 the bias-corrected update is rate * g/(|g|+ε), which is sign-descent. mnist.cpp is unaffected because it keeps one persistent state, but train() is a trap.
Initialisation is off. The He scale sqrt(2/fan_in) assumes a unit-variance distribution, but mnist.cpp passes uniform(-1, 1), which has variance 1/3. The weights come out about 1.7× smaller than intended.
Random numbers can't be seeded.tensor::random uses a function-local static mt19937 seeded from random_device, so training runs aren't reproducible. The dist you pass in only supplies the distribution, not the generator. tok2vec_layer has its own separate hidden RNG.
Dense and conv layers divide by zero if apply() runs before any backprop.m_count is 0, so the average gradient is NaN. tok2vec_layer guards against this and the others don't.
maxpool_layer is missing the size checks conv2d_layer has.IN_HEIGHT - PoolSize underflows as size_t when the input is smaller than the pool window. It also doesn't check Stride > 0.
tok2vec_layer is a dead end for now. Its output is a math::matrix<float, dynamic, E>, but every other layer static-asserts on mat<1, N, T> or tensor, so nothing can follow it yet. Its Adam update also walks the whole V×E table every step, and it has three unused pointer locals.
Performance:
feed<I> returns auto, so every layer's output is copied.
relu_layer stores a copy of its input even though backward already receives it.
Layer 0's backward computes an input gradient that is thrown away.
Tensors are stack arrays that get memset on every construction. mnist.cpp already uses new for the network and state, which suggests you've hit stack limits.
Minor issues:
layer.hpp uses std::sqrt, std::pow, std::max, std::copy and std::uint32_t without including <cmath>, <algorithm> or <cstdint>.
tensor::view::operator[] const can hand back a writable sub-view.
The .nn binaries are committed to git, and each retrain bloats the history.
#I have found a few errors by looking at this code dear CeHaP, pls fix, these are big problems. No AI.
**The most concrete bug is checkpoint handling in `mnist.cpp`.**
- The `ofstream saveFile` is opened with truncation right after the old weights are loaded. The existing `mnist-conv.nn` is wiped at startup, and the weights live only in memory until the first full epoch finishes.
- `bestLoss` starts at `max()`, so the first epoch after a resume always overwrites the checkpoint, even if it is worse than the one you resumed from.
- The stream is never flushed. The loop only stops through patience or learning-rate decay, so Ctrl-C is the normal way to end a run, and that can leave the last "saved" checkpoint truncated.
**Other problems, roughly in order of severity:**
- **`load()` doesn't validate anything.** The `is.read(...)` calls are unchecked, and the file has no header, version or shape. A truncated file or one from a different architecture, such as the committed `mnist-mlp.nn` from before the CNN layers, loads without any error. The raw bytes also depend on endianness and `sizeof(T)`.
- **`network::train()` breaks Adam.** It creates a fresh `learning_state` on every call, so the moments and `time` reset each step. At `time = 1` the bias-corrected update is `rate * g/(|g|+ε)`, which is sign-descent. `mnist.cpp` is unaffected because it keeps one persistent state, but `train()` is a trap.
- **Initialisation is off.** The He scale `sqrt(2/fan_in)` assumes a unit-variance distribution, but `mnist.cpp` passes `uniform(-1, 1)`, which has variance 1/3. The weights come out about 1.7× smaller than intended.
- **Random numbers can't be seeded.** `tensor::random` uses a function-local `static mt19937` seeded from `random_device`, so training runs aren't reproducible. The `dist` you pass in only supplies the distribution, not the generator. `tok2vec_layer` has its own separate hidden RNG.
- **Dense and conv layers divide by zero if `apply()` runs before any `backprop`.** `m_count` is 0, so the average gradient is NaN. `tok2vec_layer` guards against this and the others don't.
- **`maxpool_layer` is missing the size checks `conv2d_layer` has.** `IN_HEIGHT - PoolSize` underflows as `size_t` when the input is smaller than the pool window. It also doesn't check `Stride > 0`.
- **`tok2vec_layer` is a dead end for now.** Its output is a `math::matrix<float, dynamic, E>`, but every other layer static-asserts on `mat<1, N, T>` or `tensor`, so nothing can follow it yet. Its Adam update also walks the whole `V×E` table every step, and it has three unused pointer locals.
- **Performance:**
- `feed<I>` returns `auto`, so every layer's output is copied.
- `relu_layer` stores a copy of its input even though `backward` already receives it.
- Layer 0's `backward` computes an input gradient that is thrown away.
- Tensors are stack arrays that get `memset` on every construction. `mnist.cpp` already uses `new` for the network and state, which suggests you've hit stack limits.
- **Minor issues:**
- `layer.hpp` uses `std::sqrt`, `std::pow`, `std::max`, `std::copy` and `std::uint32_t` without including `<cmath>`, `<algorithm>` or `<cstdint>`.
- `tensor::view::operator[] const` can hand back a writable sub-view.
- The `.nn` binaries are committed to git, and each retrain bloats the history.
The most important problem on this branch is a sign error in the new loss code. I read network.hpp, layer.hpp, layers/dense.hpp, layers/convolutional.hpp, loss/mse.hpp and example/mnist.cpp. I haven't read the new math/ library, gpt.cpp, xor.cpp, CMakeLists.txt or the four open issues, and I haven't compiled or run anything.
The MSE gradient has the wrong sign, and the example only works because it passes the arguments swapped.
mean_squared_error::calculate(L&& result, R&& expected) returns expected - result. Every optimizer in the layers does weights -= rate * …, so the gradient has to be output - target. With target - output the network climbs the loss instead of descending it.
mnist.cpp calls calculate(trainSet[i+j].ys, output), which puts the label in the result slot and the prediction in the expected slot. The two mistakes cancel, so MNIST trains.
Anyone who calls it as the parameter names suggest, calculate(output, expected), gets silent divergence. Either flip the subtraction in mse.hpp and fix the call site, or rename the parameters so the order is unambiguous.
Other problems:
network::train() can't compile. It calls backward(input, expected, state), but backward now takes (loss, state). It's a template member, so nothing complains until someone calls it.
get_output() always returns zeros. It returns m_output, which nothing ever writes, because feed() returns by value without storing the result. The example only works because it uses feed()'s return value. The leftover struct loss { double value; } is also unused.
mnist.cpp destroys the committed checkpoint on every run.
The load_network branch is commented out, so every run starts from random weights.
saveFile still opens mnist-conv.nn with truncation, so the tracked trained weights are wiped at startup. This same commit modified that file.
The earlier flush and bestLoss issues are still there.
MAX_EPOCHS = 2 looks like a debug leftover, and the <= makes it run 3 epochs.
The init scale is inconsistent between layers.conv2d now uses sqrt(6/fan_in), which is correct He-uniform for uniform(-1, 1). dense still uses sqrt(2/fan_in), which assumes unit variance. With the example's distribution, dense weights are about 1.7× too small, and a normal(0, 1) distribution would make conv about 1.7× too large. Deriving the scale from the distribution's variance would fix both.
Two parallel layer sets exist.layer.hpp still defines the old dense_layer, conv2d_layer, maxpool_layer, tok2vec_layer and others, and layers/*.hpp defines the new layers::dense, conv2d and so on. layers/dense.hpp includes ../layer.hpp for layer_info. This will drift, and tok2vec hasn't been ported at all.
The new maxpool still has no size checks. There is no assert that the input is at least PoolSize, so a small input underflows size_t in the output-shape math. It also has no Stride > 0 check. It still stores a full copy of its input, while conv2d uses retained.
Carried over from master:load() still doesn't check reads or have a header, apply() still divides by zero if called before any backward, and layer.hpp still uses std::sqrt and std::pow without including <cmath>.
I'd fix the MSE sign first, since the example hides it.
new stuff
The most important problem on this branch is a sign error in the new loss code. I read `network.hpp`, `layer.hpp`, `layers/dense.hpp`, `layers/convolutional.hpp`, `loss/mse.hpp` and `example/mnist.cpp`. I haven't read the new `math/` library, `gpt.cpp`, `xor.cpp`, `CMakeLists.txt` or the four open issues, and I haven't compiled or run anything.
**The MSE gradient has the wrong sign, and the example only works because it passes the arguments swapped.**
- `mean_squared_error::calculate(L&& result, R&& expected)` returns `expected - result`. Every optimizer in the layers does `weights -= rate * …`, so the gradient has to be `output - target`. With `target - output` the network climbs the loss instead of descending it.
- `mnist.cpp` calls `calculate(trainSet[i+j].ys, output)`, which puts the label in the `result` slot and the prediction in the `expected` slot. The two mistakes cancel, so MNIST trains.
- Anyone who calls it as the parameter names suggest, `calculate(output, expected)`, gets silent divergence. Either flip the subtraction in `mse.hpp` and fix the call site, or rename the parameters so the order is unambiguous.
**Other problems:**
- **`network::train()` can't compile.** It calls `backward(input, expected, state)`, but `backward` now takes `(loss, state)`. It's a template member, so nothing complains until someone calls it.
- **`get_output()` always returns zeros.** It returns `m_output`, which nothing ever writes, because `feed()` returns by value without storing the result. The example only works because it uses `feed()`'s return value. The leftover `struct loss { double value; }` is also unused.
- **`mnist.cpp` destroys the committed checkpoint on every run.**
- The `load_network` branch is commented out, so every run starts from random weights.
- `saveFile` still opens `mnist-conv.nn` with truncation, so the tracked trained weights are wiped at startup. This same commit modified that file.
- The earlier flush and `bestLoss` issues are still there.
- `MAX_EPOCHS = 2` looks like a debug leftover, and the `<=` makes it run 3 epochs.
- **The init scale is inconsistent between layers.** `conv2d` now uses `sqrt(6/fan_in)`, which is correct He-uniform for `uniform(-1, 1)`. `dense` still uses `sqrt(2/fan_in)`, which assumes unit variance. With the example's distribution, dense weights are about 1.7× too small, and a `normal(0, 1)` distribution would make conv about 1.7× too large. Deriving the scale from the distribution's variance would fix both.
- **Two parallel layer sets exist.** `layer.hpp` still defines the old `dense_layer`, `conv2d_layer`, `maxpool_layer`, `tok2vec_layer` and others, and `layers/*.hpp` defines the new `layers::dense`, `conv2d` and so on. `layers/dense.hpp` includes `../layer.hpp` for `layer_info`. This will drift, and `tok2vec` hasn't been ported at all.
- **The new `maxpool` still has no size checks.** There is no assert that the input is at least `PoolSize`, so a small input underflows `size_t` in the output-shape math. It also has no `Stride > 0` check. It still stores a full copy of its input, while `conv2d` uses `retained`.
- **Carried over from `master`:** `load()` still doesn't check reads or have a header, `apply()` still divides by zero if called before any `backward`, and `layer.hpp` still uses `std::sqrt` and `std::pow` without including `<cmath>`.
I'd fix the MSE sign first, since the example hides it.
new stuff
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.
#I have found a few errors by looking at this code dear CeHaP, pls fix, these are big problems. No AI.
The most concrete bug is checkpoint handling in
mnist.cpp.ofstream saveFileis opened with truncation right after the old weights are loaded. The existingmnist-conv.nnis wiped at startup, and the weights live only in memory until the first full epoch finishes.bestLossstarts atmax(), so the first epoch after a resume always overwrites the checkpoint, even if it is worse than the one you resumed from.Other problems, roughly in order of severity:
load()doesn't validate anything. Theis.read(...)calls are unchecked, and the file has no header, version or shape. A truncated file or one from a different architecture, such as the committedmnist-mlp.nnfrom before the CNN layers, loads without any error. The raw bytes also depend on endianness andsizeof(T).network::train()breaks Adam. It creates a freshlearning_stateon every call, so the moments andtimereset each step. Attime = 1the bias-corrected update israte * g/(|g|+ε), which is sign-descent.mnist.cppis unaffected because it keeps one persistent state, buttrain()is a trap.sqrt(2/fan_in)assumes a unit-variance distribution, butmnist.cpppassesuniform(-1, 1), which has variance 1/3. The weights come out about 1.7× smaller than intended.tensor::randomuses a function-localstatic mt19937seeded fromrandom_device, so training runs aren't reproducible. Thedistyou pass in only supplies the distribution, not the generator.tok2vec_layerhas its own separate hidden RNG.apply()runs before anybackprop.m_countis 0, so the average gradient is NaN.tok2vec_layerguards against this and the others don't.maxpool_layeris missing the size checksconv2d_layerhas.IN_HEIGHT - PoolSizeunderflows assize_twhen the input is smaller than the pool window. It also doesn't checkStride > 0.tok2vec_layeris a dead end for now. Its output is amath::matrix<float, dynamic, E>, but every other layer static-asserts onmat<1, N, T>ortensor, so nothing can follow it yet. Its Adam update also walks the wholeV×Etable every step, and it has three unused pointer locals.feed<I>returnsauto, so every layer's output is copied.relu_layerstores a copy of its input even thoughbackwardalready receives it.backwardcomputes an input gradient that is thrown away.memseton every construction.mnist.cppalready usesnewfor the network and state, which suggests you've hit stack limits.layer.hppusesstd::sqrt,std::pow,std::max,std::copyandstd::uint32_twithout including<cmath>,<algorithm>or<cstdint>.tensor::view::operator[] constcan hand back a writable sub-view..nnbinaries are committed to git, and each retrain bloats the history.The most important problem on this branch is a sign error in the new loss code. I read
network.hpp,layer.hpp,layers/dense.hpp,layers/convolutional.hpp,loss/mse.hppandexample/mnist.cpp. I haven't read the newmath/library,gpt.cpp,xor.cpp,CMakeLists.txtor the four open issues, and I haven't compiled or run anything.The MSE gradient has the wrong sign, and the example only works because it passes the arguments swapped.
mean_squared_error::calculate(L&& result, R&& expected)returnsexpected - result. Every optimizer in the layers doesweights -= rate * …, so the gradient has to beoutput - target. Withtarget - outputthe network climbs the loss instead of descending it.mnist.cppcallscalculate(trainSet[i+j].ys, output), which puts the label in theresultslot and the prediction in theexpectedslot. The two mistakes cancel, so MNIST trains.calculate(output, expected), gets silent divergence. Either flip the subtraction inmse.hppand fix the call site, or rename the parameters so the order is unambiguous.Other problems:
network::train()can't compile. It callsbackward(input, expected, state), butbackwardnow takes(loss, state). It's a template member, so nothing complains until someone calls it.get_output()always returns zeros. It returnsm_output, which nothing ever writes, becausefeed()returns by value without storing the result. The example only works because it usesfeed()'s return value. The leftoverstruct loss { double value; }is also unused.mnist.cppdestroys the committed checkpoint on every run.load_networkbranch is commented out, so every run starts from random weights.saveFilestill opensmnist-conv.nnwith truncation, so the tracked trained weights are wiped at startup. This same commit modified that file.bestLossissues are still there.MAX_EPOCHS = 2looks like a debug leftover, and the<=makes it run 3 epochs.conv2dnow usessqrt(6/fan_in), which is correct He-uniform foruniform(-1, 1).densestill usessqrt(2/fan_in), which assumes unit variance. With the example's distribution, dense weights are about 1.7× too small, and anormal(0, 1)distribution would make conv about 1.7× too large. Deriving the scale from the distribution's variance would fix both.layer.hppstill defines the olddense_layer,conv2d_layer,maxpool_layer,tok2vec_layerand others, andlayers/*.hppdefines the newlayers::dense,conv2dand so on.layers/dense.hppincludes../layer.hppforlayer_info. This will drift, andtok2vechasn't been ported at all.maxpoolstill has no size checks. There is no assert that the input is at leastPoolSize, so a small input underflowssize_tin the output-shape math. It also has noStride > 0check. It still stores a full copy of its input, whileconv2dusesretained.master:load()still doesn't check reads or have a header,apply()still divides by zero if called before anybackward, andlayer.hppstill usesstd::sqrtandstd::powwithout including<cmath>.I'd fix the MSE sign first, since the example hides it.
new stuff