Speed-up to O(1) from O(N) of the computation of each return in REINFORCE #1083
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.
Fix
The function finish_episode() in the reinforce.py script computes returns by insertion at the beginning of a list.
This is an expensive computation in python as shown by the official docs, since it requires O(N) time to shift all its successor elements.
The same can be achieved but with O(1) time complexity with the python deque data structure, natively supported by python.
To verify the above claims, i tested insertion of 100k elements at the beginning of a list and a deque.
The results are:
Result
Hence, this is a 250 x speed-up, which becomes relevant when the number of episodes becomes large, as this computation is done at the end of every episode.
Python docs Reference: https://docs.python.org/3/tutorial/datastructures.html#using-lists-as-queues
Test
As per the contribution guidelines, the following tests have been run and successfully completed.
./run_python_examples.sh "install_deps,reinforcement_learning,clean"