Skip to content

Commit 59eb02c

Browse files
committed
Optimise BPTT sequence batching inside NeuralNetwork training loop and add integration tests
1 parent 1a5a84d commit 59eb02c

2 files changed

Lines changed: 43 additions & 2 deletions

File tree

include/neuralnetwork/neuralnetwork.cpp

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -763,6 +763,9 @@ void NeuralNetwork::train(const std::vector<std::vector<double>>& training_input
763763

764764
std::vector<std::vector<double>> bptt_in;
765765
std::vector<std::vector<double>> bptt_out;
766+
// Initial creation of BPTT batches before the epoch loop
767+
create_bptt_batches(batch_training_inputs, batch_training_outputs, bptt_in, bptt_out);
768+
766769
for (auto epoch = 0; epoch < number_of_epoch; ++epoch)
767770
{
768771
// Learning rate
@@ -773,8 +776,11 @@ void NeuralNetwork::train(const std::vector<std::vector<double>>& training_input
773776

774777
_learning_rate = base_helper->learning_rate();
775778

776-
// (re) create the bptt batches (now returns flattened sequences)
777-
create_bptt_batches(batch_training_inputs, batch_training_outputs, bptt_in, bptt_out);
779+
// Only recreate/shuffle BPTT batches if shuffle is enabled
780+
if (_options.shuffle_bptt_batches())
781+
{
782+
create_bptt_batches(batch_training_inputs, batch_training_outputs, bptt_in, bptt_out);
783+
}
778784

779785
const size_t total_sequences = bptt_in.size();
780786
for (size_t i = 0; i < total_sequences; i += batch_size)

tests/network_integration_tests.cpp

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -427,3 +427,38 @@ TEST(NetworkIntegrationTest, LogTrainingInfoOptionAndSerialization)
427427
std::remove(test_path.c_str());
428428
}
429429

430+
TEST(NetworkIntegrationTest, ShuffleBpttBatchesBehavior)
431+
{
432+
auto options_no_shuffle = NeuralNetworkOptions::create({ 2, 2, 1 })
433+
.with_learning_rate(0.01)
434+
.with_number_of_epoch(5)
435+
.with_shuffle_bptt_batches(false)
436+
.with_enable_bptt(true)
437+
.with_bptt_max_ticks(3)
438+
.build();
439+
440+
auto options_shuffle = NeuralNetworkOptions::create({ 2, 2, 1 })
441+
.with_learning_rate(0.01)
442+
.with_number_of_epoch(5)
443+
.with_shuffle_bptt_batches(true)
444+
.with_enable_bptt(true)
445+
.with_bptt_max_ticks(3)
446+
.build();
447+
448+
std::vector<std::vector<double>> inputs = {
449+
{0.1, 0.2}, {0.3, 0.4}, {0.5, 0.6}, {0.7, 0.8}, {0.9, 1.0}
450+
};
451+
std::vector<std::vector<double>> outputs = {
452+
{0.3}, {0.7}, {1.1}, {1.5}, {1.9}
453+
};
454+
455+
NeuralNetwork nn_no_shuffle(options_no_shuffle);
456+
nn_no_shuffle.train(inputs, outputs);
457+
458+
NeuralNetwork nn_shuffle(options_shuffle);
459+
nn_shuffle.train(inputs, outputs);
460+
461+
SUCCEED();
462+
}
463+
464+

0 commit comments

Comments
 (0)