Source code for gigl.distributed.utils.native_neighbor_lookup

"""Serve one-hop neighbor lookups, local and remote, with a native lookup instead of GLT's sampler and Python callee.

GLT sends each remote neighbor request as a Python RPC (``graphlearn_torch.distributed.rpc.rpc_request_async``). torch
RPC holds the interpreter lock while it unpickles such a request, runs the callee and pickles the reply, so a sampling
worker serves them one at a time, and slower while its own sampling holds the lock. A native request is instead sent as
a TorchScript RPC function that calls ``torch.ops.gigl_core.lookup_neighbors``, a C++ lookup over the partition's
CSR (``gigl-core/core/sampling/neighbor_lookup.cpp``). The serving side runs C++ on the RPC thread with no Python
and no interpreter lock; TorchScript is only the transport.
The same operator serves the local partition: ``lookup_local`` calls it from Python, and a torch operator call
releases the interpreter lock while it runs. With the flag on, local and remote nodes go through the same kernel, so
one hop uses one kernel and one random stream.

On by default; ``GIGL_NATIVE_NEIGHBOR_LOOKUP=off`` (``NATIVE_NEIGHBOR_LOOKUP_ENV``) turns it off, identically on
every process.

How the pieces fit together
---------------------------

Registering a partition and reading it live in different files, joined by the sampler's RPC sampling callee id and an
edge-type key::

    Setup, once per sampler
      BaseDistNeighborSampler.__init__            gigl/distributed/base_sampler.py
        -> rpc_register(callee)                   returns the callee id, identical on every rank
        -> _enable_native_neighbor_lookup_on_all_ranks
                                                  base_sampler.py (a collective)
             -> register_partition_csr            this module; compiles _serve_remote_lookup in this process
                  -> registerCsr (C++)            neighbor_lookup.{h,cpp}: process-global registry
                                                  keyed by (callee id, edge-type key)
             -> all_gather                        every rank registered, or every rank raises

    Local read (nodes this rank owns)
      _sample_one_hop -> lookup_local -> torch.ops.gigl_core.lookup_neighbors   python_neighbor_lookup.cpp
        -> registry lookup by (callee id, edge-type key) -> kernel              neighbor_lookup.{h,cpp}

    Remote read (nodes a peer owns)
      _sample_one_hop -> lookup_remote -> torch RPC ---------------------> peer's RPC thread
        -> TorchScript _serve_remote_lookup   compiled in that process by its own registration; found by qualified name
        -> torch.ops.gigl_core.lookup_neighbors -> registry -> kernel     no Python, no interpreter lock
      reply tuple <- torch RPC <------------------------------------------ back on the caller:
        NeighborOutput(*reply) on the caller's event-loop thread, after ``collect_all``

The registry is keyed by the callee id because the serving process has no other handle to the sampler: the request
names the sampler only by that id, and ``rpc_register`` guarantees the id is the same on every rank. The files are
``gigl/distributed/base_sampler.py`` (the caller and the all-ranks check), this module (the Python API),
``gigl-core/core/sampling/python_neighbor_lookup.cpp`` (the torch operator and the pybind functions) and
``gigl-core/core/sampling/neighbor_lookup.{h,cpp}`` (the registry and the kernel).

Registration keeps references to the dataset's tensors; nothing is copied. Entries are removed only if registration
fails, so they live as long as the process.

Sampled neighbors are identical to GLT's whenever a neighbor list is no longer than the requested fan-out. A longer
list is sampled uniformly with replacement on both paths, but from different random generators.
"""

from typing import Callable, Final, Optional, Union, cast

import torch
from gigl_core import neighbor_lookup as native_lookup
from graphlearn_torch.data import Graph
from graphlearn_torch.sampler import NeighborOutput
from graphlearn_torch.typing import EdgeType
from torch.distributed import rpc

from gigl.common.logger import Logger
from gigl.src.common.types.graph_data import EdgeType as GiglEdgeType
from gigl.utils.csr import get_compressed_id_offset

[docs] logger = Logger()
# The registry key of a homogeneous graph. It cannot collide with a heterogeneous key, because those are GiGL # ``EdgeType`` reprs (``"src-relation-dst"``), which always contain ``-``. _HOMOGENEOUS_EDGE_TYPE_KEY: Final[str] = "homogeneous_edge" # The fields of ``NeighborOutput``, in order: flat neighbor ids, per-id neighbor counts and edge ids (or ``None``).
[docs] NativeLookupReply = tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]
# Registered by importing ``gigl_core.neighbor_lookup``. The cast gives the operator its schema's types; TorchScript # resolves this global to the operator itself. An annotated assignment does not type-check: ``ty`` rejects an # ``OpOverloadPacket`` as a ``Callable``. _lookup_neighbors_op = cast( Callable[[int, str, torch.Tensor, int], NativeLookupReply], torch.ops.gigl_core.lookup_neighbors, ) _compiled_lookup_function: Optional[torch.jit.ScriptFunction] = None def _edge_type_key(etype: Optional[EdgeType]) -> str: """The registry key of an edge type: ``"homogeneous_edge"`` for a homogeneous graph, else ``"src-relation-dst"``. The key is GiGL's ``EdgeType`` repr. GLT may pass a plain tuple, so it is converted first. Example: >>> _edge_type_key(None) 'homogeneous_edge' >>> _edge_type_key(("user", "to", "user")) 'user-to-user' Args: etype (Optional[EdgeType]): The edge type, or ``None`` for a homogeneous graph. Returns: str: The registry key. """ if etype is None: return _HOMOGENEOUS_EDGE_TYPE_KEY return repr(GiglEdgeType(*etype)) def _serve_remote_lookup( sampler_id: int, edge_type: str, ids: torch.Tensor, req_num: int, ) -> tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]: """The function the server runs for a native neighbor request; compiled by ``_load_lookup_function``. This wrapper exists because ``torch.jit.script`` cannot compile a ``torch.ops`` packet directly, and ``rpc_async`` does not treat a ``torch.ops`` op as a builtin (it would pickle it as a Python call, taking the interpreter lock on the server), so the scripted wrapper gives RPC a ``ScriptFunction`` with a qualified name. Args: sampler_id (int): The sampler's RPC sampling callee id. edge_type (str): The registry key of the edge type, from ``_edge_type_key``. ids (torch.Tensor): Global ids of the nodes to sample from, int64 on the CPU. req_num (int): Requested neighbors per node; negative means all. Returns: tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]: Flat neighbor ids, per-id neighbor counts and edge ids, or ``None`` for edge ids when the CSR was registered with ``with_edge=False``. """ return _lookup_neighbors_op(sampler_id, edge_type, ids, req_num) def _load_lookup_function() -> torch.jit.ScriptFunction: """Compiles ``_serve_remote_lookup`` once per process. Every process that serves native requests must call this before it receives one: torch RPC finds the function by its qualified name in the process's TorchScript compilation unit. Returns: torch.jit.ScriptFunction: The compiled function. """ global _compiled_lookup_function if _compiled_lookup_function is None: _compiled_lookup_function = torch.jit.script(_serve_remote_lookup) return _compiled_lookup_function def _unsupported_reason(graph: Graph) -> Optional[str]: if graph.mode != "CPU": return f"graph mode is {graph.mode}, not CPU" topo = graph.topo if topo.indptr.dtype not in (torch.int32, torch.int64): return f"indptr is {topo.indptr.dtype}, not int32 or int64" if topo.indices.dtype not in (torch.int32, torch.int64): return f"indices are {topo.indices.dtype}, not int32 or int64" if not (topo.indptr.is_contiguous() and topo.indices.is_contiguous()): return "the CSR is not contiguous" return None
[docs] def register_partition_csr( sampler_id: int, local_graph: Union[Graph, dict[EdgeType, Graph]], with_edge: bool, with_weight: bool, device: torch.device, seed: Optional[int], ) -> Optional[str]: """Registers this partition's CSR for native neighbor lookups, local and remote, addressed to ``sampler_id``. Never raises: a failure is returned as a reason, so that the caller's ``all_gather`` across ranks still runs on every rank (GLT's ``all_gather`` waits with no timeout, so a rank that raised first would hang the others). Args: sampler_id (int): The sampler's RPC sampling callee id, identical on every rank. local_graph (Union[Graph, dict[EdgeType, Graph]]): The partition's graph, or one graph per edge type. with_edge (bool): Whether replies carry edge ids; if not, they carry ``None``. with_weight (bool): Whether the sampler samples by edge weight, which the C++ lookup does not do. device (torch.device): The sampler's device; the lookup runs on the CPU only. seed (Optional[int]): The sampler's random seed, or ``None``. Seeds the lookup's sub-sampling as GLT's sampler seeds its own. Returns: Optional[str]: ``None`` if every edge type was registered, else the reason this rank cannot register. When a reason is returned, nothing is registered. """ graphs: dict[str, Graph] = {} if isinstance(local_graph, dict): for etype, graph in local_graph.items(): graphs[_edge_type_key(etype)] = graph else: graphs[_HOMOGENEOUS_EDGE_TYPE_KEY] = local_graph reason: Optional[str] = None if device.type != "cpu": reason = f"the sampler device is {device}, not CPU" # TODO: support weighted sampling in the native lookup. elif with_weight: reason = "weighted sampling is on" else: for key, graph in graphs.items(): graph_reason = _unsupported_reason(graph) if graph_reason is not None: reason = f"edge type '{key}': {graph_reason}" break if reason is not None: return reason try: _load_lookup_function() if seed is not None: native_lookup.set_random_seed(seed) for key, graph in graphs.items(): topo = graph.topo native_lookup.register_csr( sampler_id=sampler_id, edge_type=key, indptr=topo.indptr, indices=topo.indices, edge_ids=topo.edge_ids, compressed_id_offset=get_compressed_id_offset(topo), with_edge=with_edge, ) except Exception as e: logger.exception( "Registering this partition's CSR for native neighbor requests failed." ) native_lookup.unregister_csr(sampler_id) return f"registration raised {type(e).__name__}: {e}" return None
[docs] def lookup_remote( worker_name: str, sampler_id: int, etype: Optional[EdgeType], ids: torch.Tensor, req_num: int, ) -> torch.futures.Future[NativeLookupReply]: """Asks ``worker_name``'s process to look up neighbors in its partition, and returns a future of the reply. For nodes this process owns, see ``lookup_local``, which returns the neighbors directly. The request is a TorchScript RPC function, so the server needs no Python to answer it. Args: worker_name (str): The RPC worker that owns ``ids``. sampler_id (int): The sampler's RPC sampling callee id. etype (Optional[EdgeType]): The edge type to sample along, or ``None`` on a homogeneous graph. ids (torch.Tensor): Global ids of the nodes to sample from, int64 on the CPU. req_num (int): Requested neighbors per node. Returns: torch.futures.Future[NativeLookupReply]: A future of ``(neighbors, counts, edge_ids or None)``. The reply is a tuple, which the caller wraps with ``NeighborOutput(*reply)`` on its own event loop, not in a Python callback on the future: a callback would take the interpreter lock on an RPC thread, which also serves peers. """ return rpc.rpc_async( worker_name, _load_lookup_function(), args=(sampler_id, _edge_type_key(etype), ids, req_num), )
[docs] def lookup_local( sampler_id: int, etype: Optional[EdgeType], ids: torch.Tensor, req_num: int, ) -> NeighborOutput: """Looks up neighbors in this process's partition now, and returns them. For nodes another process owns, see ``lookup_remote``, which returns a future instead. Samplers call this for local nodes, with the lookup a native request runs on the server. A torch operator call releases the interpreter lock while it runs. A negative ``req_num``, or one above the int32 maximum, means all neighbors. An id outside the partition's rows has 0 neighbors. A row with at most ``req_num`` neighbors is copied in stored order. A longer row is sampled uniformly with replacement from a per-thread generator. Args: sampler_id (int): The sampler's RPC sampling callee id. etype (Optional[EdgeType]): The edge type to sample along, or ``None`` on a homogeneous graph. ids (torch.Tensor): Global ids of the nodes to sample from, int64 on the CPU. req_num (int): Requested neighbors per node. Returns: NeighborOutput: The flat neighbor ids, the neighbor count per id and the edge ids, or ``None`` for ``edge`` when the CSR was registered with ``with_edge=False``. Raises: RuntimeError: If no CSR is registered for ``sampler_id`` and ``etype``, if ``ids`` is not a 1-D int64 CPU tensor, or if the registration wants edge ids but the graph has none. """ return NeighborOutput( *_lookup_neighbors_op(sampler_id, _edge_type_key(etype), ids, req_num) )