Fix backpropagation math and thread-safety in neural network core - #2
Draft
maybepritz with Copilot wants to merge 3 commits into
Draft
Fix backpropagation math and thread-safety in neural network core#2maybepritz with Copilot wants to merge 3 commits into
maybepritz with Copilot wants to merge 3 commits into
Conversation
Co-authored-by: maybepritz <79636615+maybepritz@users.noreply.github.com>
Co-authored-by: maybepritz <79636615+maybepritz@users.noreply.github.com>
Copilot
AI
changed the title
[WIP] Fix backpropagation weight update issue in DenseLayer
Fix backpropagation math and thread-safety in neural network core
Feb 1, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Three critical mathematical errors in backpropagation were causing incorrect gradient flow:
Backpropagation Issues
Weight update ordering - Weights were updated before computing error for previous layer, propagating incorrect gradients:
Activation derivatives - Derivatives computed from post-activation values instead of pre-activation:
preActivationfield to storezbefore activationgetGradient()to usepreActivation.map(activation::derivative)instead ofoutput.map(...)Sigmoid.derivative()to computesigmoid(x)from raw input firstDropout edge case - Added check for
dropoutRate < 1.0to prevent division by zeroConcurrency
Replaced
HashMapwithConcurrentHashMapinAdamOptimizerfor thread-safe multi-threaded training.Performance
Use
MatrixFactory.create(rows, cols)instead ofweights.copy().scale(0)for zero matrix initialization in Adam optimizer state.Original prompt
Описание проблем
В коде библиотеки JNeuro обнаружены следующие критические ошибки и проблемы, которые необходимо исправить:
🔴 Критические ошибки
1. Backprop использует уже обновлённые веса (
DenseLayer.java)Файл:
src/main/java/io/github/maybepritz/layers/DenseLayer.javaПроблема: В методе
backpropagate()сначала обновляются веса, а затем используются для вычисления ошибки предыдущего слоя. Это неправильно — нужно сначала вычислить ошибку, потом обновить веса.Текущий код (строки 89-98):
Исправление:
2. Производная считается от output вместо pre-activation (
DenseLayer.java)Проблема: В методе
getGradient()производная функции активации вычисляется отoutput(уже активированных значений), но для Tanh и ReLU производная должна вычисляться от pre-activation значенияz.Текущий forward():
Исправление: Добавить поле
private Matrix preActivation;и сохранятьz:И изменить
getGradient():3. Ошибка в производной Sigmoid (
Sigmoid.java)Файл:
src/main/java/io/github/maybepritz/activations/Sigmoid.javaПроблема: После исправления п.2, derivative будет получать исходное
x, а неsigmoid(x). Нужно исправить формулу.Текущий код:
Исправление:
🟠 Серьёзные проблемы
4. Деление на ноль при dropout (
DenseLayer.java)Проблема: Если
dropoutRate = 1.0, произойдёт деление на ноль.Текущий код:
Исправление:
5. Thread-safety в AdamOptimizer (
AdamOptimizer.java)Файл:
src/main/java/io/github/maybepritz/optimizers/AdamOptimizer.javaПроблема: Использование
HashMapнебезопасно при многопоточном обучении.Текущий код:
Исправление: Заменить на
ConcurrentHashMap:6. Неэффективная инициализация в AdamOptimizer (
AdamOptimizer.java)Проблема: Создание копии матрицы и умножение на 0 неэффективно.
Текущий код:
Исправление: Использовать MatrixFactory для создания нулевой матрицы: