Kevin Fang
Kevin Fang

Reputation: 2012

Python - high disk usage in SumTree

I've encountered some weird behaviour of my python program. Basically when I tried to create adn fill a SumTree of length larger than 1000, my disk usage increases a lot to ~300MB/s then the programme died.

I'm pretty sure there's no file r/w involved in this process, and the problem is with the add function. The code is shown below.

import numpy as np

class SumTree():

    trans_idx = 0

    def __init__(self, capacity):
        self.num_samples = 0
        self.capacity = capacity
        self.tree = np.zeros(2 * capacity - 1)
        self.transitions = np.empty(self.capacity, dtype=object)

    def add(self, p, experience):
        tree_idx = self.trans_idx + self.capacity - 1
        self.transitions[self.trans_idx] = experience
        self.transitions.append(experience)
        self.update(tree_idx, p)

        self.trans_idx += 1
        if self.trans_idx >= self.capacity:
            self.trans_idx = 0

        self.num_samples = min(self.num_samples + 1, self.capacity)

    def update(self, tree_idx, p):
        diff = p - self.tree[tree_idx]
        self.tree[tree_idx] = p
        while tree_idx != 0:
            tree_idx = (tree_idx - 1) // 2
            self.tree[tree_idx] += diff

    def get_leaf(self, value):
        parent_idx = 0
        while True:  
            childleft_idx = 2 * parent_idx + 1  
            childright_idx = childleft_idx + 1
            if childleft_idx >= len(self.tree):  
                leaf_idx = parent_idx
                break
            else:  
                if value <= self.tree[childleft_idx]:
                    parent_idx = childleft_idx
                else:
                    value -= self.tree[childleft_idx]
                    parent_idx = childright_idx

        data_idx = leaf_idx - self.capacity + 1
        return leaf_idx, self.tree[leaf_idx], self.transitions[data_idx]

    @property
    def total_p(self):
        return self.tree[0]  # the root

    @property
    def volume(self):
        return self.num_samples  # number of transistions stored

Here's an example where this SumTree object will be used:

def add(self, experience)
    max_p = np.max(self.tree.tree[-self.tree.capacity:])
    if max_p == 0:
        max_p = 1.0
    exp = self.Experience(*experience)
    self.tree.add(max_p, exp)  

where Experience is a named tuple and self.tree is a Sumtree instance, when I removed the last line the high disk usage disappears.

Can anyone help me with this?

Upvotes: 0

Views: 132

Answers (1)

Kevin Fang
Kevin Fang

Reputation: 2012

I finally sort this out because each experience is a tuple of namedtuple and I'm creating another namedtuple Experience from it. Fixed by changing experience to a tuple of numpy arrays.

Upvotes: 0

Related Questions