Skip to content

Enable backend-only functions where NetworkX is just an API - #7690

Merged
MridulS merged 15 commits into
networkx:mainfrom
eriknw:is_stub
Jan 19, 2025
Merged

MridulS merged 15 commits into
networkx:mainfrom
eriknw:is_stub

Conversation

@eriknw

@eriknw eriknw commented Oct 23, 2024

Copy link
Copy Markdown
Contributor

This adds is_stub to _dispatchable as a quick way to enable backend-only functions. Is there a better name than is_stub?

Alternative approaches:

  • make "networkx" a more proper backend
  • add e.g. default_backend= to _dispatchable to encourage other backends or libraries to wrap functions with @_dispatchable to use the dispatch machinery

This will let us expose cugraph-only functions such as Leiden or node2vec. CC @rlratzel

@eriknw eriknw added type: Enhancements Dispatching Related to dispatching and backend support labels Oct 23, 2024

@rossbar rossbar left a comment

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.

+1 for supporting this use-case. Is this machinery necessary though? If someone were to add, e.g.

@nx._dispatchable(...)
def leiden(G, ...):
    """Leiden docstring"""
    raise NotImplementedError

wouldn't that be sufficient? IMO if we can get away with not expanding the configuration input (which is already quite complicated) that's a win!

@eriknw

eriknw commented Oct 23, 2024

Copy link
Copy Markdown
Contributor Author

[...] wouldn't that be sufficient?

Yeah, that's certainly the easiest option to begin with, so thanks for bringing it up!

Where it falls short is introspection. With this PR, users can check "networkx" in func.backends to see if it's implemented by NetworkX. I also want us to eventually support more sophisticated introspection so the user can ask questions such as "what will the plan be, or what will probably happen, when I call func(G, ...)?". We had func.plan(...) in metagraph that was actually very nice. If it's not implemented by NetworkX, it would be nice to reflect that in the "plan".

The approach in this PR also allows for slightly better log and error messages.

Is this worth the added complexity? I'm not sure, hence why I wanted to see it in PR form ;)

@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.

I'm -0.5 on this. [I'm -0 on this,] But mostly because I can't understand how this impacts the dispatching logic, and I don't have the time to figure that out right now.

Isn't a function that returns NotImplemented should be sufficient. Why does it also need to be marked in the decorator as such.

I'm also worried that figuring out the decorator will make it difficult for people to contribute code.

Comment thread networkx/utils/backends.py Resolved
Comment thread networkx/utils/backends.py Outdated
backend implementation(s) using the `backend_info` entry-point."""

if not self.backends:
if self.backends.issubset({"networkx"}):

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.

Is this related to is_stub?
Can we just put it in a separate PR?

Why is it in this PR?

@eriknw eriknw Oct 23, 2024 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes, it's related. This PR adds "networkx" to self.backends. This check means we don't need to add "Backends" section to the docstring if it is not implemented by any backends or is only implemented by "networkx".

@eriknw

eriknw commented Oct 23, 2024

Copy link
Copy Markdown
Contributor Author

I removed self._is_stub and rely on checking whether "networkx" is in self.backends instead. I find this cleaner (thanks for the scrutiny!), and I do prefer reducing unnecessary state.

Comment on lines 1504 to +1507
def _does_backend_have(self, backend_name):
"""Does the specified backend have this algorithm?"""
if backend_name == "networkx":
return True
return "networkx" in self.backends

@eriknw eriknw Oct 23, 2024 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@dschult, this is the key location to understand how this PR affects dispatch logic. _does_backend_have is the method that answers whether a backend has a function. NetworkX "has" a function only if "networkx" is in self.backends.

Other key changes are basically updating

if nx.config.fallback_to_nx

to

if nx.config.fallback_to_nx and "networkx" in self.backends

which we could write as

if nx.config.fallback_to_nx and self._does_backend_have("networkx")

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.

Thanks for the pointer to this function. At the moment, it doesn't seem so central to the PR though -- the function _does_backend_have is only used to set up the error messages for NotImplemented cases.

But the phrase "networkx" in self.backends is key -- as you explain -- because it combines with fallback_to_nx to determine whether the networkx function is called. But couldn't this just be done by calling the networkx function to get the NotImplemented rather than storing and looking up this info in self.backends? I'm sure it is more complicated than that. There are always side-effects.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

... _does_backend_have is only used ...

Touche. Good catch. I also (just now) updated _can_backend_run to return False if "networkx" not in self.backends".

@dschult

dschult commented Oct 24, 2024 •

Copy link
Copy Markdown
Member

I've adjusted my scale for vote on this PR. I now understand that -0.5 is more negative than I was intending.

I was -0 for adding the is_stub, not -0.5. And my concerns are not blockers. With @mridul approving and @eriknw authoring, I think it can be merged.

I would suggest a name other than is_stub because "stub" is a new term that submitters of code to networkx will need to learn. Perhaps something like nx_func=True, or maybe no_nx_func=False. Or if longer is OK, nx_func_supported=True. Anyway, something that doesn't require learning a new term. :)

@Schefflera-Arboricola Schefflera-Arboricola 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.

Rather than adding stub functions in NetworkX to enable backend-only functions, could we instead temporarily add the stubs for backend-only functions from all the installed backends directly to NetworkX's namespace when NetworkX is imported? This way backend developers would be able to integrate backend-only functions without needing to request NetworkX to add stub functions, eliminating any bias toward specific backends.

Something like this:

In NetworkX(inside __init__.py):

backend_only_combined = []
backends = _get_backends("networkx.backends")
for backend_name in backends:
    _backend = _load_backend(backend_name)
    if hasattr(_backend, backend_only):
        for func_name, func in _backend.backend_only.items():
             if func_name not in backend_only_combined: 
                _dispatchable(func_name, is_stub=True)
                backend_only_combined.append(func_name)

In backend:

from nx_backend import leiden


BackendInterface.backend_only = {
    "leiden": leiden
}

here, BackendInterface is the object pointed by the "networkx.backends" entry_point. And backend_only doesn't have to be a dictionary, we can allow it to be any object, with the additional functions as its attributes.

Are there any major flaws/drawbacks to this approach?

Thank you :)

@dschult

dschult commented Oct 30, 2024

Copy link
Copy Markdown
Member

A similar approach would be to just have the backends provide functions on their own, without any NetworkX interfacing. The backend library doesn't hve to always work through a networkx interface -- only when it makes sense to do so.

So the user would do something like:

import networkx as nx
import nx_parallel as nxp

G = nx.path_graph(9)
result = nxp.new_feature(G)

@MridulS

MridulS commented Oct 30, 2024

Copy link
Copy Markdown
Member

But we want to keep the API design within networkx right? The docs, and function signature needs to be in networkx codebase to make the dispatch work this way.

@Schefflera-Arboricola

Schefflera-Arboricola commented Oct 30, 2024 •

Copy link
Copy Markdown
Member

A similar approach would be ...
...result = nxp.new_feature(G)

That is how it is currently. And I think we want to enable dispatching of the backend-only algorithms from networkx because of the "0 code change" thing. So, if a user sets the nx.config.backend_priority as ["parallel", "networkx", "cugraph"] and runs a python script with nx.leiden(G,...) call(and other nx calls too) then they could run their code without modifying it. But, it is misleading because it gives the impression that networkx has leiden implemented but it does not. So, I think the code should be changed by the user in this case. And the user would anyways have to change the code, because their code might run with this backend_priority but without any backends it will throw an error. So, I'm not sure if 0 code change makes sense here. But I think @eriknw can explain it in more depth as to why we need to enable this. Also, what did you(@eriknw) mean by:

make "networkx" a more proper backend

in the first comment?

[EDIT] : One more reason why a user should call nx.leiden(G,..., backend="cugraph") instead of nx.leiden(G,...) and set the backend_priority as as ["parallel", "networkx", "cugraph"]--- if someday networkx implements leiden then their code will suddenly become slow because now networkx's implementation would run instead of nx-cugraph's.

@rlratzel

rlratzel commented Nov 4, 2024

Copy link
Copy Markdown
Contributor

So, if a user sets the nx.config.backend_priority as ["parallel", "networkx", "cugraph"] and runs a python script with nx.leiden(G,...) call(and other nx calls too) then they could run their code without modifying it. But, it is misleading because it gives the impression that networkx has leiden implemented but it does not. So, I think the code should be changed by the user in this case. And the user would anyways have to change the code, because their code might run with this backend_priority but without any backends it will throw an error.

This is a good comment for a topic larger than what's covered in this PR, and I'm thinking we should have had a NXEP on "backend-only" APIs or "NetworkX as a standard graph analytics API" or some other name for this topic.

My thoughts about supporting backend-only APIs are:

  • They allow NetworkX to define a standard interface for functions which backends can use for their implementations, rather than have multiple backends implement the same function with different/incompatible interfaces. The API standard defined by NetworkX allows users to have compatibility across backends, just like they do for functions NX currently implements. When/if NX implements the function (no longer making it "backend only"), the user's code continues to work on systems without backends.
  • Having NX define the function signature also allows NX to provide a docstring, examples, and possibly tests which make it even easier for backend authors to share their implementations, and easier for users to adopt them.
  • Zero-code change becomes more of a relative term for backend-only APIs, meaning a user's code is portable across systems that have a backend installed that supports the backend-only function. So if cugraph and parallel both implement leiden, then users can have code portable to CPU-only systems using nx-parallel, and GPU systems using nx-cugraph, without code changes. When/if NX implements leiden, then their code will work everywhere without changes. But I agree that backend-only functions do stretch the meaning of zero code change, and maybe we wouldn't call it that for cases involving backend only APIs.

So, if a user sets the nx.config.backend_priority as ["parallel", "networkx", "cugraph"] ...

I'm a bit confused by this use case though. Is this saying the user has installed nx-cugraph, but doesn't want to use it for anything except functions not implemented in NX (leiden)? I'm just wondering if that's more of an uncommon corner case, and the recommendation for that is to set backend_priority=["parallel"] and then set backend="cugraph" for leiden in their code (assuming nx-cugraph is the only backend implementing leiden), which is similar to what I think you also suggested for this case.

@eriknw

eriknw commented Nov 5, 2024

Copy link
Copy Markdown
Contributor Author

Sorry for being AFK for so long! (Taking time off is nice though :) ). I will begin to address comments in this PR, but it will take me some time. Thanks for the discussions!

[@dschult] I would suggest a name other than is_stub because "stub" is a new term that submitters of code to networkx will need to learn. Perhaps something like nx_func=True, or maybe no_nx_func=False. Or if longer is OK, nx_func_supported=True. Anyway, something that doesn't require learning a new term. :)

I agree with that reasoning. I changed the name to implemented_by_nx and can change again if anyone has a preference.

Another reason to introduce this to dispatching machinery is so that when nx.config.fallback_to_nx is True, these backend-only functions will never convert backend graphs to networkx graphs only to raise NotImplementedError. Better to raise before doing the (possibly very expensive) conversion.

I'll reply more tomorrow. Cheers!

@eriknw

eriknw commented Nov 6, 2024

Copy link
Copy Markdown
Contributor Author

Also, what did you(@eriknw) mean by:

make "networkx" a more proper backend

in the first comment?

I mean in terms of implementation, to reduce the number of times we need to do e.g. if backend_name == "networkx": such as by having _load_backend("networkx") return a backend interface like other backends. I think it's likely that "networkx" will always be a privileged and special backend, so I don't think this is something we should push hard on until there is a compelling reason to.

@eriknw

eriknw commented Dec 4, 2024

Copy link
Copy Markdown
Contributor Author

This now automatically adds an "Attention" admonition near the top of the function. Other types of admonitions could also work; see: https://sphinx-book-theme.readthedocs.io/en/stable/reference/kitchen-sink/admonitions.html

Here's an example of online docs of a backend-only function:
leiden_docs

And here it is as text:

>>> import networkx as nx
>>> help(nx.community.leiden_communities)

Help on function leiden_communities in module networkx.algorithms.community.leiden:

leiden_communities(G, weight='weight', resolution=1, max_level=None, seed=None, *, backend=None, **backend_kwargs)
    Find the best partition of a graph using the Leiden Community Detection
    Algorithm.

    .. attention:: This function does not have a default NetworkX implementation.
        It may only be run with an installable :doc:`backend </backends>` that
        supports it such as "cugraph".

        Hint: use ``backend=...`` keyword argument to specify a backend or add
        backends to ``nx.config.backend_priority``.

    Leiden Community Detection Algorithm is a method to extract the community
    structure of a network based on modularity optimization.
    See :func:`~networkx.algorithms.community.louvain.louvain_communities`.

    Unlike the Louvain algorithm, it guarantees that communities are well connected in addition
    to being faster and uncovering better partitions. [1]_

    The algorithm works in 3 phases. On the first phase, it adds the nodes to a queue randomly
    and assigns every node to be in its own community. For each node it tries to find the

@eriknw

eriknw commented Jan 3, 2025

Copy link
Copy Markdown
Contributor Author

I cleaned this up slightly to try to make the code a little clearer.

Here's a summary (with remarks) of the changes in this PR:

  • Add implemented_by_nx= argument to _dispatchable
    • This controls whether "networkx" is added to e.g. func.backends
    • Previously, func.backends did not include "networkx"
    • No other internal state is added
  • Automatically update docstring and docs website that this is a backend-only function
    • See example in previous post
  • Do not try to "fall back" to NetworkX implementation for backend-only functions
    • Could occur when given a backend graph and nx.config.fallback_to_nx is True
    • Hence, this avoids a potentially costly conversion just to do something that would fail
  • Better and more consistent error messages
    • We are able to include informative blurbs in exceptions
      • e.g. "This function is included in NetworkX as an API to dispatch to other backends."
  • Implementation-wise...
    • _can_backend_run("networkx", args, kwargs) returns False
      • used to control whether NetworkX implementation will be attempted (possibly with conversions)
    • _does_backend_have("networkx") returns False
      • used to improve error messages

We discussed how this impacts the zero-code change use case in the NetworkX community call yesterday. In short: it doesn't. Code doesn't change. It just happens that the code will fail if it needs to use networkx implementation.

@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.

I've looked through this again and think it is ready to merge.

I hope that we don't get too many of these backend-only functions. That could get confusing for people looking at the NetworkX docs list of algorithms. They will see functions that they can't use without installing backends. Perhaps adding backend-only functions can give an expectation that NX will eventually implement them.

Anyway, I approve this PR

@eriknw

eriknw commented Jan 16, 2025

Copy link
Copy Markdown
Contributor Author

I hope that we don't get too many of these backend-only functions. That could get confusing for people looking at the NetworkX docs list of algorithms. They will see functions that they can't use without installing backends. Perhaps adding backend-only functions can give an expectation that NX will eventually implement them.

Thanks for taking a look @dschult! I agree with this sentiment. There is a specific need for Leiden, so hopefully there won't be that much demand/need to introduce too many backend-only functions. There should be a strong case for each one that gets added, and they should be appropriate to add to networkx and not just someones whim. Anyway, I consider each backend-only function to be an invitation for somebody to contribute an implementation ;)

@dschult

dschult commented Jan 16, 2025

Copy link
Copy Markdown
Member

@MridulS your approval was long ago -- sorry for the delay while I get up to speed with this stuff.
Could you check whether you still approve and then merge this if so? Thanks!

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.

7 participants