Skip to content

FEAT: adding a PoC of creating an internal cache - #7233

Closed
MridulS wants to merge 4 commits into
networkx:mainfrom
MridulS:cache_it_all
Closed

MridulS wants to merge 4 commits into
networkx:mainfrom
MridulS:cache_it_all

Conversation

@MridulS

@MridulS MridulS commented Jan 17, 2024

Copy link
Copy Markdown
Member

We had a nice discussion in the networkx developer meeting today about cache-ing intermediate scipy sparse states and also providing this cache dictionary to backends so they can store their objects once converted.

This is just a PoC to show how it could look like, we should probably create a NXEP or a doc to cover the cacheing policy.

There is considerable speedups on the second call as this caches the sparse array, even without a "backend" there is considerable speedup and we should look at this in a bit more detail.

In [1]: import networkx as nx

In [2]: G = nx.erdos_renyi_graph(10_000, 0.1)

In [3]: %time _ = nx.pagerank(G)
CPU times: user 7.85 s, sys: 1.53 s, total: 9.38 s
Wall time: 7.68 s

In [4]: %time _ = nx.pagerank(G)
CPU times: user 73.6 ms, sys: 11.4 ms, total: 85 ms
Wall time: 85.7 ms

In [5]: G.remove_node(0)

In [6]: %time _ = nx.pagerank(G)
CPU times: user 5.45 s, sys: 254 ms, total: 5.7 s
Wall time: 5.76 s

In [7]: %time _ = nx.pagerank(G)
CPU times: user 72.2 ms, sys: 12.2 ms, total: 84.4 ms
Wall time: 85.3 ms

@dschult dschult left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice results!

This POC is convincing (at least to me). Cache would need to be cleared for edge changes too of course. Anything else? G.graph-dict changes?

And I think it would be better for mainantence if the cache-handling happened in to_scipy_sparse_array. The closer to the conversion the better for ease of testing, readability of algorithm code and reducing duplication of code. Any downsides to that?

Thanks for this!!

Comment on lines +461 to +467
# Check if the cache exists
if "networkx-sparse" in G._cache_it_all:
# Get the cached sparse array
A = G._cache_it_all["networkx-sparse"]
else:
A = nx.to_scipy_sparse_array(G, nodelist=nodelist, weight=weight, dtype=float)
G._cache_it_all["networkx-sparse"] = A

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we should put this caching code into the conversion function (I mean to_scipy_sparse_array in this example). That saves us maintenance in many places and makes the code for readable in the algorithm itself.

Any downsides to doing that?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah I agree, that is probably the best place to add the cacheing!

Comment thread networkx/convert_matrix.py Outdated
"""
cache_key = f"sparse-{hash(tuple(nodelist))}-{dtype}-{weight}-{format}"
if cache_key in G._cache:
return G._cache[cache_key]

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alright, so if we do this at conversion function level will probably need to do something like this, I'm not sure if I'm happy with this way. The nodelist is the tricky one, the tuple(nodelist) could be an expensive operation (??)

Any thoughts @dschult @eriknw @rlratzel?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

perhaps don't cache if nodelist is not None

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps there is some way to keep the nodelist option. I really don't think te array formulation is very useful without a nodelist. And while most people can use the order of nodes in G, it can be pretty confusing if it is not what you expect. I'm not saying we shouldn't take that route, but maybe we can think about ways to make it work.

I'll start with an easier question - by making a cache_key based on dtype, weight and format, we are allowing people to cache multiple versions of the array for different dtype weight and format. I can see that people could want the different weight -- suppose they are doing analysis back-and-forth between two or more different weights. And I can see dtype being different for different kinds of weights. It's harder to see the motivation of storing different formats, but dtype and format are the two main parameters for sparse array.

By not hashing when nodelist is set, we are not allowing people to cache any array that is out of the order given by nodes in G. I would guess that anyone who specifies a nodelist would want to keep that same nodelist for all the arrays created -- for different weights, for different dtypes and for different formats. They would almost certainly want to have them all with the same nodelist. Do you think that is true?

So, could we advertise loudly that the cached array uses the nodelist as it was set for the first call to a sparse array conversion? Maybe we could even cache the nodelist alongside the array so that people could test whether their current nodelist matches the cached version. Or..... if you don't want the user to even know about the caching, we could cache the nodelist and in the check for a cache, if the array exists and it's nodelist is not None, we could check if it agrees with the called nodelist.

if cache_key in G._cache:
    cache_nodelist, A = G._cache[cache_key]
    if cache_nodelist != nodelist:
        A = nx.to_scipy_sparse_array(G, nodelist=nodelist, weight=weight, dtype=float)
        G._cache[cache_key] = (nodelist, A)
else:
    A = nx.to_scipy_sparse_array(G, nodelist=nodelist, weight=weight, dtype=float)
    G._cache[cache_key] = (nodelist, A)

We should be able to make something work so that people can cache even if they specify a nodelist. At worst, we don't track it, let them do it and warn them to clear the cache if they change the order of the nodelist.

I suppose this means we should have a public function to clear the cache -- and maybe even public functions to reset the node order of a graph.

def reorder_nodes(self, nodelist):
    # check set(nodelist) == set(G) and len(nodelist) == len(G)??
    old_node, old_adj = self._node, self._adj
    new_node = {n: old_node[n] for n in nodelist}
    new_adj = {n: old_adj[n] for n in nodelist}
    self._adj = new_adj  # the cached property resetters should make self.adj and self.nodes reset
    self._node = new_node

@rossbar rossbar added the Dispatching Related to dispatching and backend support label Jan 31, 2024
@dschult dschult closed this Mar 28, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Dispatching Related to dispatching and backend support type: Enhancements

Development

Successfully merging this pull request may close these issues.

4 participants