This document summarizes the changes made to the Rust implementation (Burn framework) to achieve perfect numerical and gradient equivalence with the Python implementation (PyTorch).
- Forward Pass (VALOR): Difference < 1e-7 across sequence lengths 1-12.
- Backward Pass (GRADIENTS): Difference < 1e-6 across all trainable parameters and inputs.
- Verified via:
cargo run --release --bin mlstm_equivalenceandpython tests/mlstm_equivalence.py.
- State Initialization: The
empty_state()function was previously returning aTensor::zeroswithout the.require_grad()flag. In the recurrentstep(), Burn would drop the gradient flow when hitting the zeroed padding. - Graph Tracking in
step(): The manual multiplication of weights was using.val(), which in Burn 0.16 can detach the tensor from the Autodiff graph. This was replaced by calling the module's nativeforward()method on the sliding window state. - Fixed: Recurrent gradient now correctly matches the parallel gradient (e.g., from
0.1back to the expected0.6in testing).
- Cumulative Sum (
cumsum_matrix): Replaced the previoustril.matmul(x)approach with a native iterative reconstruction usingTensor::cat. The matrix multiplication method for cumsum was causing vanishing/exploding gradients in long sequences. - Stabilization Logic: Aligned the stabilized denominator calculation with the Python version using
max_pairagainst theexp(-max_log_D)term, ensuring the stabilizer logic is identical in both backends.
m_stateInitialization: Changed defaultm_statefrom-30.0to0.0inlayer.rsandcell.rsto match the Python implementation's starting point.- LayerNorm (
ln.rs): Replaced theGroupNormbasedMultiHeadLayerNormwith a custom implementation that manually calculates mean/variance and applies weights without an implicit bias, mirroring the specific configuration used in the Python version.
Execute the equivalence suite in both environments to verify:
# Rust
cd rust
cargo run --release --bin mlstm_equivalence
# Python
cd ..
$env:PYTHONPATH = "."
python tests/mlstm_equivalence.py