Fix broadcasting gradient reduction in ADD and MUL operations #1
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.
Summary
Fixes gradient computation when broadcasting occurs in element-wise ADD, MUL operations and batch MATMUL operations. This resolves the TODO at
src/tofu_graph.c:965and is the first feature for v1.1.0.Problem
When broadcasting occurs in forward pass, the backward pass was not correctly reducing gradients back to the original input shape:
[3,1] * [3,4] -> [3,4]- gradient had shape[3,4]but needed to be reduced to[3,1][1,3,4] @ [2,4,5] -> [2,3,5]- gradient had shape[2,3,4]but needed to be reduced to[1,3,4]Solution
New helper function:
reduce_grad_for_broadcast()tofu_tensor_sumreduce()Updated functions:
add_backward()- Now reduces gradients for both inputs when broadcasting occursmul_backward()- Now reduces gradients for both inputs when broadcasting occursmatmul_backward()- Fixed to:Testing
New Tests
Created comprehensive test suite (
test/standalone/test_broadcast_gradient.c):[3,1] * [3,4][2,1,3] * [1,4,3][1] + [3,4][1,3,4] @ [2,4,5] -> [2,3,5]Results: 5/5 tests pass
Existing Tests
Impact
Resolves
Part of v1.1.0 roadmap - Priority 1 (P1) bug fix