Skip to content
class

SumTree

SumTree(capacity: int)

A flat segment tree over priorities: sample in O(log⁡n)O(\log n).

Parameters

capacityint
Number of leaves.

Raises

ValueError
If capacity is not positive.

Notes

Schaul et al. describe exactly this: "a 'sum-tree' data structure, where every node is the sum of its children, with the priorities as the leaf nodes, which can be efficiently updated and sampled from."

It is here rather than expressed with tensors because the obvious tensor formulation is a cumulative sum plus a search, and that is O(n)O(n) in the buffer rather than O(log⁡n)O(\log n) in it. Measured on this machine at a million leaves: the cumulative-sum form takes 196 ms to draw a batch of 32, the tree 0.20 ms — a factor of 973, against a training step of about 120 ms. The bottleneck is the algorithm, not the language, which is also why this is Python and not a new engine op: having fixed the complexity, a C++ tree would save a further 0.2% of a step.

Examples

>>> from lucid.utils.rollout import SumTree
>>> tree = SumTree(4)
>>> tree.set(0, 1.0)
>>> tree.set(3, 3.0)
>>> tree.total
4.0
>>> tree.find(0.5), tree.find(2.0)
(0, 3)

Used by 1

Constructors

1
dunder

__init__

→None
__init__(capacity: int)

Initialise an empty tree. See the class docstring.

Properties

1
prop

total

→float
total: float

Sum of every leaf — the root.

Instance methods

3
fn

find

→int
find(prefix: float)

The leaf whose cumulative range contains prefix.

Parameters

prefixfloat
In [0, total).

Returns

int

Leaf index. Descends the tree, so the cost is the depth.

fn

get

→float
get(index: int)

Read one leaf.

Parameters

indexint
Leaf position.

Returns

float

Its priority.

fn

set

→None
set(index: int, priority: float)

Write one leaf and repair the sums above it.

Parameters

indexint
Leaf position, in [0, capacity).
priorityfloat
Non-negative.

Raises

ValueError
If the index is out of range or the priority is negative.